diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index ebe8cdd68..f635790f5 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -245,6 +245,11 @@ 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. 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 # run-tests restarts the server daemonized to apply the import/export @@ -456,6 +461,11 @@ 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. 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 # Same rationale as the postgres job: the daemonized server logs to diff --git a/.github/workflows/search-inequality-filters.yml b/.github/workflows/search-inequality-filters.yml new file mode 100644 index 000000000..a52e1c5d4 --- /dev/null +++ b/.github/workflows/search-inequality-filters.yml @@ -0,0 +1,168 @@ +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 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: 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 a list of accounts, and against the build with the feature compiled +# out. +# +# 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 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. +jobs: + compiled-out: + runs-on: extenddb_ubuntu-2404_4-core + timeout-minutes: 40 + 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' }} + - 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 + run: cargo clippy --locked --workspace --all-targets -- -D warnings + - name: Unit tests with the feature compiled out + run: | + 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 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + backend: [sqlite, postgres] + # `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 + 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: 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 }} + + - 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. 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 == '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" + + - 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: [compiled-out, wire] + if: always() + steps: + - run: | + if [ "${{ needs.compiled-out.result }}" != "success" ] \ + || [ "${{ needs.wire.result }}" != "success" ]; then + exit 1 + fi diff --git a/Cargo.toml b/Cargo.toml index e31f15c3c..16216d44b 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 e9d2cf1d9..9254b73bb 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 @@ -18,6 +19,15 @@ 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, every account when it is absent. On by default. +# 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] extenddb-auth = { workspace = true } 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/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/core/Cargo.toml b/crates/core/Cargo.toml index 5515035ae..b56a79a7d 100755 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -89,7 +89,14 @@ hex = "0.4" wasm-bindgen-test = "0.3.80" [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, 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/evaluator.rs b/crates/core/src/expression/evaluator.rs index 7db0635b0..f2df2ccc5 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -18,7 +18,20 @@ 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(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, +} + +/// Evaluate a condition expression against an item, comparing numbers +/// exactly. /// /// Returns `true` if the condition is satisfied, `false` otherwise. /// @@ -29,6 +42,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(crate) fn evaluate_condition_at( + expr: &Expr, + item: &BTreeMap, + maps: &ExpressionMaps, + precision: NumberPrecision, ) -> Result { match expr { Expr::Compare { left, op, right } => { @@ -38,18 +66,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)?; @@ -59,33 +85,24 @@ pub fn evaluate_condition( 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) { - 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)) => { 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 +115,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 +177,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 +189,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 +200,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 +213,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, @@ -373,12 +404,51 @@ 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 +/// 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 b08150044..1520a2778 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(); @@ -228,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/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 629a03617..4e68df885 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -20,6 +20,9 @@ mod projection; mod reserved_words; mod resolver; mod search_condition; +#[cfg(feature = "search-inequality-filters")] +pub mod search_filter; +pub mod search_params; #[cfg(test)] mod test_timeout; mod tokenizer; @@ -32,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; @@ -43,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..b0a0523db 100644 --- a/crates/core/src/expression/search_condition.rs +++ b/crates/core/src/expression/search_condition.rs @@ -109,6 +109,29 @@ 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) +} + +/// 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 @@ -141,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)); } } @@ -162,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_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/gate.rs b/crates/core/src/expression/search_filter/gate.rs new file mode 100644 index 000000000..fbe0ee756 --- /dev/null +++ b/crates/core/src/expression/search_filter/gate.rs @@ -0,0 +1,109 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Which accounts get the extended grammar. +//! +//! 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 +//! another account is refused before the grammar is chosen, so the caller +//! owns the table. + +use std::collections::BTreeSet; + +/// The parsed value of the setting. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum EnabledAccounts { + /// No account. + Off, + /// Every account. The default, and the value when the setting is absent + /// or empty. + #[default] + 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 empty, '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` gets the grammar. + #[must_use] + pub fn enabled_for(&self, caller: &str) -> bool { + match self { + Self::Off => false, + Self::All => true, + Self::Listed(accounts) => accounts.contains(caller), + } + } +} + +#[cfg(test)] +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)); + assert_eq!(EnabledAccounts::parse("all"), Ok(EnabledAccounts::All)); + assert!(!EnabledAccounts::Off.enabled_for("123456789012")); + assert!(EnabledAccounts::All.enabled_for("123456789012")); + } + + #[test] + fn a_list_enables_the_accounts_it_names() { + let listed = EnabledAccounts::parse("111111111111, 222222222222").unwrap(); + assert!(listed.enabled_for("111111111111")); + assert!(listed.enabled_for("222222222222")); + assert!(!listed.enabled_for("333333333333")); + } + + #[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..ba6ac3271 --- /dev/null +++ b/crates/core/src/expression/search_filter/grammar.rs @@ -0,0 +1,460 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! 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 )* +//! 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 := '(' 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; + +/// 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), +} + +// 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 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) { + 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 +/// +/// 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))` 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 && group(i - 1)), + 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(()) +} + +/// 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, +} + +/// 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], + 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()) + } + } + + /// `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 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; + } + 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 { + 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(); + } + } + } + + /// 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, + 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 { + 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(); + Operand::Value(value) + } + Kind::Name if self.peek_kind(1) == &Kind::LParen => { + let name = self.text().to_owned(); + self.bump(); + self.bump(); + open.push(Some(Call { + name, + args: Vec::new(), + })); + continue; + } + Kind::Name | Kind::NameRef => self.path().map_err(Unparsed::other)?, + _ => return Err(Unparsed::other(self.error())), + }; + loop { + 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); + } + } + } + } + } + + 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..dc4c03eb2 --- /dev/null +++ b/crates/core/src/expression/search_filter/lexer.rs @@ -0,0 +1,190 @@ +// 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 + } + // 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; + } + 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..60f5f100f --- /dev/null +++ b/crates/core/src/expression/search_filter/mod.rs @@ -0,0 +1,230 @@ +// 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 `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; +//! 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 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. + +mod gate; +mod grammar; +mod lexer; +mod rules; +mod schema; +mod walk; + +use std::collections::{BTreeSet, HashMap}; + +pub use gate::EnabledAccounts; +use rules::Condition; + +use crate::error::DynamoDbError; +use crate::expression::search_params::check_unused_keys; +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; + +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, + limits: &LimitsConfig, +) -> Result { + if expr.is_empty() { + return Err(invalid("The expression can not be empty;")); + } + 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 }; + 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 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() +} + +/// 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 `:`. +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. + #[cfg(test)] + pub(super) fn conditions(&self) -> &[Condition] { + &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. + /// + /// # 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::evaluator::evaluate_condition_at( + &self.expr, + item, + &self.maps, + crate::expression::evaluator::NumberPrecision::Binary64, + ) + } +} + +#[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; + +#[cfg(test)] +mod tests_depth; + +#[cfg(test)] +mod tests_operands; 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..1ac994408 --- /dev/null +++ b/crates/core/src/expression/search_filter/schema.rs @@ -0,0 +1,127 @@ +// 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::expression::search_condition::{ + HASH_ATTRIBUTES_MISSING as HASH_MISSING, not_in_search_schema, +}; +use crate::types::{ + AttributeDefinition, AttributeValue, ScalarAttributeType, SearchSchemaElement, + SearchSchemaElementType, +}; + +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(not_in_search_schema(&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_depth.rs b/crates/core/src/expression/search_filter/tests_depth.rs new file mode 100644 index 000000000..7bbefc31c --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_depth.rs @@ -0,0 +1,243 @@ +// 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, + &crate::limits::LimitsConfig::default(), + ) { + 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")); +} + +#[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); +} + +/// 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] +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, + &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); + 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/tests_eval.rs b/crates/core/src/expression/search_filter/tests_eval.rs new file mode 100644 index 000000000..5c006f9a1 --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_eval.rs @@ -0,0 +1,334 @@ +// 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 +//! 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}; + +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), + ]; + 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, + &crate::limits::LimitsConfig::default(), + ) + .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"], + ), + (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); +} + +/// 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"], + ), + ( + h("NOT (Price = :p10)"), + vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10"], + ), + ( + h("Category <> :a"), + vec!["i2", "i3", "i5", "i7", "i9", "i10"], + ), + ( + 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"], + ), + ]; + let refs: Vec<(&str, &[&str])> = cases + .iter() + .map(|(e, x)| (e.as_str(), x.as_slice())) + .collect(); + assert_matches(&refs); +} + +/// `1E2` against `100`, and 38-digit values. +#[test] +fn numbers_compare_as_binary64() { + let cases = [ + (h("Price = :p100"), vec!["i6", "i7"]), + (h("Price > :big"), vec![]), + (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); +} + +/// 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, + &crate::limits::LimitsConfig::default(), + ) + .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")); +} + +#[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"], + ), + ( + 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"], + ), + ( + 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"], + ), + ("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..8d3ad3476 --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -0,0 +1,549 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The grammar and the tree-building checks, before any search schema. +//! +//! Every expected answer was measured against the live service in +//! 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}; + +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 :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", + p( + "The first operand must be distinct from the remaining operands for this \ + operator or function; operator: BETWEEN, first operand: [a]", + ), + ), + ], + ); +} + +/// 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, + &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:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[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, + &crate::limits::LimitsConfig::default(), + ) + .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, + &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, + &crate::limits::LimitsConfig::default(), + ) + .unwrap_err(); + assert_eq!( + super::tests_support::message(err), + 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, + &crate::limits::LimitsConfig::default(), + ) { + 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")); +} + +/// 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 new file mode 100644 index 000000000..f7ef35e0a --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -0,0 +1,416 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! 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. +//! `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, message, 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. +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)| { + let values = used_values(expr, &all); + 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:?}"), + }; + (&actual != expected) + .then(|| format!("{expr:?}: expected {expected:?}, got {actual:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +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()), + ]); +} + +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}"), + ), + ], + ); +} + +/// 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}" + ); + } + } + } +} + +/// 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 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 +/// 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_filter/tests_rules.rs b/crates/core/src/expression/search_filter/tests_rules.rs new file mode 100644 index 000000000..90d10a4d7 --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_rules.rs @@ -0,0 +1,234 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! 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 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::{ + 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..192e7671d --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_schema.rs @@ -0,0 +1,456 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The search condition against the index search schema. +//! +//! Every expected answer was measured against the live service in +//! 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; + +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, + &crate::limits::LimitsConfig::default(), + ) + .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, + &crate::limits::LimitsConfig::default(), + ) + .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, + &crate::limits::LimitsConfig::default(), + ) + .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..e472fa0bd --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_support.rs @@ -0,0 +1,129 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Fixtures shared by the search filter tests. Each test file states where +//! its expected answers were measured. + +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, + &crate::limits::LimitsConfig::default(), + ) +} + +/// `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..5a7934afc --- /dev/null +++ b/crates/core/src/expression/search_filter/walk.rs @@ -0,0 +1,459 @@ +// 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; +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`. +/// +/// 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> { + 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)?, + } + } + 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)?; + 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) => 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> { + 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> { + 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. The operands were already checked by [`calls`]. +fn function(call: &Call, condition: bool, maps: &Maps<'_>) -> Result<(), String> { + 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}" + )); + } + // 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 Some(code) = operand_code(arg, maps) + && !fits.contains(&code) + { + return Err(operand_type_code(name, code)); + } + } + if expected == 2 { + distinct_first_operand(name, &call.args[0], [&call.args[1]], maps)?; + } + match name { + "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()) => { + Ok(()) + } + 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(()), + } +} + +/// 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, + } +} + +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 { + 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: {code}" + ) +} + +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, 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(()); + }; + 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, +/// IN and function is one, a function used as an operand included. +/// Parentheses are none. +pub(super) fn operators(node: &Node) -> usize { + 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), + } + while let Some(o) = operands.pop() { + on_operand(o); + if let Operand::Call(call) = o { + operands.extend(&call.args); + } + } + } +} + +/// The expression's bytes plus the bytes each substitution adds, counted at +/// 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 names: HashMap<&str, usize> = HashMap::new(); + let mut values: HashMap<&str, usize> = HashMap::new(); + each_operand( + node, + |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(_) => {} + }, + |_| {}, + ); + // 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() + .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/crates/core/src/expression/search_params.rs b/crates/core/src/expression/search_params.rs new file mode 100644 index 000000000..e41ae2fbf --- /dev/null +++ b/crates/core/src/expression/search_params.rs @@ -0,0 +1,202 @@ +// 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 +//! 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 +//! 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::expression::validate_expression_param_usage; +use crate::limits::LimitsConfig; +use crate::serde_helpers::validate_placeholder_key; +use crate::types::AttributeValue; +use crate::validation::{AttributeNameRequestForm, validate_expression_attribute_name_sizes}; + +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. 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, + 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;" + ))); + } + validate_placeholder_key(key, prefix, field, true).map_err(invalid) + }) +} + +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}" + ))); + } + validate_expression_attribute_name_sizes( + Some(names), + None, + limits, + AttributeNameRequestForm::SearchRequest, + )?; + 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, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + if let Some(names) = names { + check_names(names, limits)?; + } + if let Some(values) = values { + check_keys(VALUES, ':', values.keys())?; + } + // 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, + &[], + ) +} + +/// 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-keys `ValidationException`. +pub fn check_unused_keys( + field: &str, + map: Option<&HashMap>, + used: &BTreeSet<&str>, +) -> Result<(), DynamoDbError> { + let unused: BTreeSet<&str> = map + .into_iter() + .flat_map(HashMap::keys) + .map(String::as_str) + .filter(|k| !used.contains(k)) + .collect(); + if unused.is_empty() { + return Ok(()); + } + Err(invalid(format!( + "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 +/// 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>, + condition_names: &BTreeSet<&str>, + projection: &str, +) -> Result { + match 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, condition_names, projection)?; + 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..c37f21233 --- /dev/null +++ b/crates/core/src/expression/search_params_tests.rs @@ -0,0 +1,362 @@ +// 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 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; + +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, + &LimitsConfig::default(), + )) +} + +#[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, + &LimitsConfig::default() + )), + "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" + ); +} + +/// 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!( + 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, + &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, + &LimitsConfig::default(), + )) + }; + 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, &LimitsConfig::default()).is_ok()); + assert!(check_search_maps(Some(&n), Some(&v), true, false, &LimitsConfig::default()).is_ok()); +} + +#[test] +fn a_name_is_used_by_the_condition_or_the_projection() { + let n = names(&[("#p", "Price"), ("#c", "Country")]); + 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), &cond(&[]), "Price")), + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#c, #p}" + ); + assert_eq!( + refused(check_unused_names(Some(&n), &cond(&["#c"]), "")), + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#p}" + ); +} + +/// 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)] + .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")]); + 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}"; + let none = BTreeSet::new(); + assert_eq!( + refused(with_unused_names(syntax(), Some(&n), &none, "")), + "Invalid SearchConditionExpression: Syntax error" + ); + assert_eq!( + refused(with_unused_names(Ok(()), Some(&n), &none, "")), + 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), + &none, + "" + )), + names_msg + ); + assert_eq!( + refused(with_unused_names( + unused_values(values_msg), + None, + &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()); +} + +/// 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/serde_helpers.rs b/crates/core/src/serde_helpers.rs index 3a4ffb3cd..a9036c809 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'_') } @@ -28,7 +28,7 @@ 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, diff --git a/crates/core/src/settings_keys.rs b/crates/core/src/settings_keys.rs index 27ab58054..45652baf2 100644 --- a/crates/core/src/settings_keys.rs +++ b/crates/core/src/settings_keys.rs @@ -100,6 +100,19 @@ 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: `all` (the default when the row is +/// absent or empty), `off`, or a comma-separated list of 12-digit account +/// 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"; + +/// 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/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/Cargo.toml b/crates/engine/Cargo.toml index fbf55e345..b8eca3739 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 = [] @@ -20,6 +20,14 @@ 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, every account when it is absent. On by default. +# 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] extenddb-auth = { workspace = true } 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/lib.rs b/crates/engine/src/lib.rs index 4fe89b969..c53ad8d34 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -51,6 +51,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 @@ -64,6 +66,8 @@ mod read_helpers; 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; @@ -97,7 +101,12 @@ 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::{ + 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}; pub use streams::{ShardIterator, decode_shard_iterator, encode_shard_iterator}; pub use streams::{ 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.rs b/crates/engine/src/search_vectors.rs index 731c011ce..282e801a3 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -4,59 +4,32 @@ //! `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; -use serde::{Deserialize, Serialize}; +use serde::Serialize; 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, - item_size_bytes, -}; +use extenddb_core::expression::{ExpressionMaps, Projection}; +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, -} - /// A single search result: the item plus its similarity score. #[derive(Debug, Serialize)] struct SearchResult { @@ -75,6 +48,33 @@ 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. +/// +/// # 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 { + request::check(body, storage, account_id, limits) + .await + .map(CheckedSearchVectors) +} + /// Handle a `SearchVectors` request. /// /// # Errors @@ -85,54 +85,36 @@ 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 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, + } = checked; 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 - ))); - } - - // Structural validation of the filter expression (schema-independent). - let conditions = match input.search_condition_expression.as_deref() { - Some(expr) => validate_search_condition_expression( - expr, - input.expression_attribute_names.as_ref(), - input.expression_attribute_values.as_ref(), - )?, - None => Vec::new(), - }; - let key_info = ctx .table_key_info(&input.table_name) .await @@ -185,11 +167,14 @@ pub async fn handle_search_vectors( ))); } - let (hash_key, filters) = resolve_search_scope( - &conditions, + let (hash_key, filters, item_filter) = condition::resolve( + &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 { @@ -199,6 +184,7 @@ pub async fn handle_search_vectors( top_k: input.top_k, hash_key, filters: &filters, + item_filter, }) .await .map_err(storage_err_to_dynamo)?; @@ -323,50 +309,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 @@ -438,97 +380,17 @@ 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)] +#[path = "search_vectors_order_tests.rs"] +mod order_tests; #[cfg(test)] mod tests { + use super::condition::resolve_search_scope; + use super::request::{MAX_SEARCH_VECTOR_LENGTH, parse_search_vector}; 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_condition.rs b/crates/engine/src/search_vectors_condition.rs new file mode 100644 index 000000000..d3f057220 --- /dev/null +++ b/crates/engine/src/search_vectors_condition.rs @@ -0,0 +1,312 @@ +// 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. +//! +//! 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 +//! values exactly and inline-filter numbers as binary64, and the equality +//! pairs compare every value exactly. So the pairs carry a condition of +//! 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; + +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, +}; +use extenddb_storage::{StorageEngine, VectorItemFilter}; + +#[cfg(feature = "search-inequality-filters")] +use crate::search_vectors_extended::Extended; + +/// 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 +/// 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), +/// with each grammar that may serve the caller. The caller has already +/// found that the backend serves vector search. +/// +/// # Errors +/// +/// Returns the `ValidationException` of the first failed check, and +/// `ServiceUnavailable` when the answer depends on the setting and +/// the setting cannot be read. +pub(crate) async fn parse( + storage: &Arc, + account_id: &str, + expr: Option<&str>, + names: Option<&HashMap>, + values: Option<&HashMap>, + projection: Option<&str>, + limits: &LimitsConfig, +) -> Result { + let Some(expr) = expr else { + return Ok(Parsed::Equality(Vec::new())); + }; + 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, limits); + 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, limits); + equality.map(Parsed::Equality) + } +} + +/// The scope of the search, once the schema checks pass. +/// +/// # Errors +/// +/// Returns the `ValidationException` of the first failed schema check, and +/// `ServiceUnavailable` 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> { + 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, 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, true, search_schema, attribute_definitions); + if same_scope(&equality, &extended) + || !crate::search_vectors_extended::enabled_for(storage, account_id).await? + { + equality + } else { + extended + } + } + } +} + +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: 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, + as_pairs: bool, + 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 as_pairs + .then(|| equality_pairs(extended, search_schema)) + .flatten() + { + 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>( + 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 &(name, value) in &conditions { + if Some(name) == hash_attr { + continue; + } + if !matches!(value, AttributeValue::S(_) | AttributeValue::B(_)) { + return None; + } + filters.push((name, 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> = ( + 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)) +} + +#[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..fabc7a38d --- /dev/null +++ b/crates/engine/src/search_vectors_condition_tests.rs @@ -0,0 +1,454 @@ +// 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::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use extenddb_core::limits::LimitsConfig; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, Item, ScalarAttributeType, SearchSchemaElement, + SearchSchemaElementType, +}; +use extenddb_storage::StorageEngine; +use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; +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 = crate::test_context::memory_engine().await; + 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 values: HashMap = values() + .into_iter() + .filter(|(k, _)| expr.contains(k.as_str())) + .collect(); + let parsed = parse( + &storage, + "111111111111", + Some(expr), + None, + Some(&values), + None, + &LimitsConfig::default(), + ) + .await + .unwrap(); + let schema = schema(hash); + let (hash_key, filters, item_filter): Scope<'_> = resolve( + &parsed, + Some(&schema), + &definitions(), + &storage, + "111111111111", + ) + .await + .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) + ); +} + +/// 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 = crate::test_context::memory_engine().await; + let store = Arc::new(Failing::default()); + crate::install_search_filter_settings(&storage, store.clone()); + 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, + "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()); + (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}" + ); + } +} + +/// 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 new file mode 100644 index 000000000..69c01417e --- /dev/null +++ b/crates/engine/src/search_vectors_extended.rs @@ -0,0 +1,153 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `SearchVectors` with the extended `SearchConditionExpression` grammar. +//! +//! 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 +//! 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. 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(all(feature = "search-inequality-filters", not(target_arch = "wasm32")))] +#[path = "search_vectors_settings.rs"] +mod settings; + +#[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; + use std::sync::Arc; + + use extenddb_core::error::DynamoDbError; + use extenddb_core::expression::search_filter::{ + 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}; + + /// 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, + ); + + /// 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. + /// + /// # Errors + /// + /// Returns the `ValidationException` of the first failed check. + pub(crate) fn parse( + expr: &str, + names: Option<&HashMap>, + values: Option<&HashMap>, + projection: Option<&str>, + limits: &LimitsConfig, + ) -> Result { + with_unused_names( + parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS, limits), + names, + &name_refs(expr), + projection.unwrap_or_default(), + ) + .map(|filter| Extended(Arc::new(filter))) + } + + /// Whether the setting gives `account_id` the extended grammar on the + /// server `storage` belongs to. + /// + /// # Errors + /// + /// Returns `ServiceUnavailable` 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)) + } + + /// 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; 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..6ff3825bf --- /dev/null +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -0,0 +1,188 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Which requests the extended grammar parses, and the filter it hands the +//! backend. +//! +//! Each test installs its store against a storage engine of its own. + +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::StorageEngine; +use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; +use futures::future::BoxFuture; + +use super::imp::{enabled_for, parse, resolve_scope}; +use super::install_search_filter_settings; + +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()) }) + } +} + +/// A storage engine whose server reads `value` for the setting. +async fn install(value: Result, ()>) -> Arc { + 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 +} + +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 enabled(storage: &Arc) -> Result { + enabled_for(storage, CALLER).await +} + +static LIMITS: std::sync::LazyLock = + std::sync::LazyLock::new(extenddb_core::limits::LimitsConfig::default); + +fn parsed(expr: &str) -> Result { + parse( + expr, + None, + Some(&values()), + None, + &extenddb_core::limits::LimitsConfig::default(), + ) +} + +#[tokio::test] +async fn the_setting_selects_the_accounts() { + for (value, expected) in [ + // 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 is logged and enables no account + (Ok(Some("on")), false), + ] { + let storage = install(value).await; + 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 = enabled(&storage).await.unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ServiceUnavailable(m) + if m == "Service is temporarily unavailable"), + "{err:?}" + ); +} + +#[tokio::test] +async fn without_an_installed_store_every_account_gets_the_grammar() { + let storage = crate::test_context::memory_engine().await; + assert!(enabled(&storage).await.unwrap()); +} + +#[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:?}"); + }; + assert_eq!( + message, + "Invalid SearchConditionExpression: The function is not allowed in a search \ + condition; function: begins_with" + ); +} + +#[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(INEQUALITY, Some(&names), Some(&values), None, &LIMITS) + .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(); + assert!(parse(INEQUALITY, Some(&used), Some(&values), Some("#u"), &LIMITS).is_ok()); +} + +fn item(country: &str, price: &str) -> Item { + [ + ("Country".to_owned(), AttributeValue::S(country.to_owned())), + ("Price".to_owned(), AttributeValue::N(price.to_owned())), + ] + .into() +} + +#[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(), + 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/engine/src/search_vectors_order_tests.rs b/crates/engine/src/search_vectors_order_tests.rs new file mode 100644 index 000000000..d4343475a --- /dev/null +++ b/crates/engine/src/search_vectors_order_tests.rs @@ -0,0 +1,199 @@ +// 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. The +//! combined size check answers ahead of a missing table too. + +use std::time::Duration; + +use serde_json::{Value, json}; + +use extenddb_core::error::DynamoDbError; +use extenddb_storage::server_components::ServerComponentsOptions; +use extenddb_storage_sqlite::SqliteConfig; +use tempfile::TempDir; + +use crate::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(); + crate::test_context::context_on(components.engine, &account_id) +} + +/// 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:?}" + ); +} + +/// 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. 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(); + 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:?}" + ); +} diff --git a/crates/engine/src/search_vectors_params.rs b/crates/engine/src/search_vectors_params.rs new file mode 100644 index 000000000..c2d9759a3 --- /dev/null +++ b/crates/engine/src/search_vectors_params.rs @@ -0,0 +1,83 @@ +// 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::{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, search_condition_name_refs, + 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(), + limits, + )?; + 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, &BTreeSet::new(), 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, + &search_condition_name_refs(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()); +} diff --git a/crates/engine/src/search_vectors_request.rs b/crates/engine/src/search_vectors_request.rs new file mode 100644 index 000000000..9e72e5bdb --- /dev/null +++ b/crates/engine/src/search_vectors_request.rs @@ -0,0 +1,170 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! 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; + +use super::condition; + +/// 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, +} + +/// A `SearchVectors` request whose checks that need no table passed. +pub(super) struct Checked { + pub(super) input: SearchVectorsInput, + pub(super) query_vector: Vec, + pub(super) parsed: condition::Parsed, +} + +/// 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( + body: &Value, + storage: &Arc, + account_id: &str, + limits: &LimitsConfig, +) -> Result { + let input = SearchVectorsInput::deserialize(body).map_err(crate::deserialize_error)?; + + 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, + 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(), + limits, + ) + .await?; + + Ok(Checked { + input, + query_vector, + parsed, + }) +} + +/// 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) +} diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs new file mode 100644 index 000000000..09071865c --- /dev/null +++ b/crates/engine/src/search_vectors_settings.rs @@ -0,0 +1,293 @@ +// 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. 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 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`]. 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 `ServiceUnavailable`, 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 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 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; + +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::{OpResult, 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 `ServiceUnavailable`. +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.changed(); + } +} + +/// The accounts the setting enables on the server that `storage` belongs +/// to. An absent or empty value enables every account, a malformed one none. +/// +/// # Errors +/// +/// Returns `ServiceUnavailable` 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::All), + } +} + +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, + /// The value of the last read that answered, this one or an earlier one. + /// `None` when no read has answered yet. + 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, + /// When the read was sent. + sent_at: Instant, + task: JoinHandle>>, +} + +struct Settings { + store: Arc, + kept: 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 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>, +} + +impl Settings { + fn new(store: Arc) -> Self { + Self { + store, + kept: Mutex::new(None), + last: Mutex::new(None), + 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; + } + + /// The value of the last read that answered. + fn last(&self) -> Option { + self.last + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + 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(), + sent_at: Instant::now(), + task: tokio::spawn(async move { + store.get_setting_bounded(SEARCH_INEQUALITY_FILTERS).await + }), + } + } + + /// 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; + } + // 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.last() { + Some(accounts) => return Ok(accounts), + None => self.reading.lock().await, + }, + }; + if let Some(answer) = self.fresh() { + return answer; + } + 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; + // 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; + } + 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(Ok(raw))) => { + let (accounts, ignored) = Self::parse(raw.as_deref(), previous.as_deref()); + if let Some(ignored) = ignored { + tracing::warn!("{ignored}"); + } + *self.last.lock().unwrap_or_else(PoisonError::into_inner) = Some(accounts.clone()); + (raw, Some(accounts)) + } + Ok(Ok(Err(e))) => { + tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e:?}"); + (previous, self.last()) + } + Ok(Err(e)) => { + tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e}"); + (previous, self.last()) + } + Err(_) => { + tracing::warn!( + "{SEARCH_INEQUALITY_FILTERS} could not be read within {READ_TIMEOUT:?}" + ); + (previous, self.last()) + } + }; + let answer = accounts.clone().ok_or_else(unavailable); + if sent == self.changes() { + *kept = Some(Kept { + read_at: Instant::now(), + raw, + accounts, + }); + } + answer + } + + /// 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 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); + }; + match EnabledAccounts::parse(value) { + Ok(accounts) => (accounts, None), + Err(reason) => ( + EnabledAccounts::Off, + (previous != Some(value)).then(|| { + format!("{SEARCH_INEQUALITY_FILTERS} = {value:?} enables no account: {reason}") + }), + ), + } + } +} + +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_fault_tests.rs b/crates/engine/src/search_vectors_settings_fault_tests.rs new file mode 100644 index 000000000..64a625156 --- /dev/null +++ b/crates/engine/src/search_vectors_settings_fault_tests.rs @@ -0,0 +1,127 @@ +// 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, 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; + 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); + poison(&settings.last); + 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); + 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. +#[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 new file mode 100644 index 000000000..b238de22d --- /dev/null +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -0,0 +1,566 @@ +// 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, one read at a time, and a +//! fault answered as a retryable error. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +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 futures::future::BoxFuture; +use tokio::sync::Notify; + +use super::{ + READ_TIMEOUT, REFRESH, SERVERS, Settings, enabled_accounts, install_search_filter_settings, + same, search_filter_settings_changed, +}; + +/// How a read of the store answers. +#[derive(Clone)] +enum Answer { + Value(Option), + /// The value, after a delay that lets concurrent readers interleave. + 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. +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::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, + Answer::Gated(gate, v) => { + gate.notified().await; + Ok(Some(v)) + } + } + }) + } + + 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 { + crate::test_context::memory_engine().await +} + +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_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")); + assert!(!listed.enabled_for("222222222222")); +} + +/// A malformed value enables no account and is logged once per change. +#[test] +fn a_malformed_value_is_logged_once_and_enables_no_account() { + let (accounts, logged) = Settings::parse(Some("on"), None); + assert_eq!(accounts, EnabledAccounts::Off); + assert_eq!( + logged.as_deref(), + Some( + "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::Off, None) + ); + assert!(Settings::parse(Some("on"), Some("off")).1.is_some()); +} + +#[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::All + ); + // installing again replaces the server's store + install_search_filter_settings(&first, Store::value("off")); + assert_eq!( + enabled_accounts(&first).await.unwrap(), + EnabledAccounts::Off + ); +} + +/// 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); + 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(); + // 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); +} + +#[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 keeps the last value read as briefly, then the next read + // recovers + store.set(Answer::Fail); + tokio::time::advance(REFRESH).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + store.set(Answer::Value(None)); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + tokio::time::advance(REFRESH).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + assert_eq!(store.reads(), 4); +} + +#[tokio::test(start_paused = true)] +async fn concurrent_requests_share_one_read() { + let store = Store::new(Answer::Slow("all".to_owned())); + 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 + ); +} + +/// 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(); + until_the_read_ends(&settings).await; + 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); +} + +/// 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_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 + ); + 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)] +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); +} + +/// 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); +} + +/// 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; + +#[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..729ec33a5 --- /dev/null +++ b/crates/engine/src/search_vectors_settings_wait_tests.rs @@ -0,0 +1,128 @@ +// 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); +} + +/// 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)); +} 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, + } +} diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 4b49f73d5..2d04c35de 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; @@ -21,12 +22,23 @@ 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, every account when it is absent. On by default. +# 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/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/handler.rs b/crates/server/src/handler.rs index 24734bd8a..cac42ed59 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -131,6 +131,65 @@ pub(crate) async fn handle_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). The checked request goes + // 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, + &account_id, + &state.limits, + ) + .await + { + 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, + &e, + &account_id, + 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); + state.metrics.record_segments( + &account_id, + &operation, + &extenddb_core::metrics::LatencySegments { + auth_us, + authz_us: 0.0, + throttle_us: 0.0, + dispatch_us, + response_us, + total_us, + }, + ); + return response; + } + } + } + // --- Authz segment --- let authz_start = std::time::Instant::now(); let authorized_key_info; @@ -267,8 +326,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. diff --git a/crates/server/src/management/ops_settings.rs b/crates/server/src/management/ops_settings.rs index 82cd8962b..f5f0940dd 100755 --- a/crates/server/src/management/ops_settings.rs +++ b/crates/server/src/management/ops_settings.rs @@ -46,8 +46,33 @@ 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(|_| ()) +} + +/// 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", @@ -188,6 +213,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", @@ -195,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); +} diff --git a/crates/server/src/request_attributes.rs b/crates/server/src/request_attributes.rs index 3404240e6..df8c3d5cf 100644 --- a/crates/server/src/request_attributes.rs +++ b/crates/server/src/request_attributes.rs @@ -61,8 +61,11 @@ //! 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. +//! - `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 //! `Keys` are not read: on a table that does not exist, under a Deny on the @@ -118,12 +121,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 @@ -172,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 7a4ecb2dc..48e720ac2 100644 --- a/crates/server/src/request_attributes/tests.rs +++ b/crates/server/src/request_attributes/tests.rs @@ -525,18 +525,53 @@ fn scan_holds_its_filter_projection_and_start_key_names() { ); } -#[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"]) - ); +/// 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_no_attributes() { + let v = || json!({":v": {"S": "1"}}); + let rows = [ + ( + "projected paths", + json!({ + "ProjectionExpression": "#v.x, name", + "ExpressionAttributeNames": {"#v": "vec"}, + }), + None, + ), + ( + "a projection of ssn", + json!({"ProjectionExpression": "ssn"}), + None, + ), + ( + "a key without #", + json!({"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}), + None, + ), + ( + "a condition on ssn", + json!({ + "SearchConditionExpression": "ssn = :v", + "ExpressionAttributeValues": v(), + "ProjectionExpression": "cat", + }), + None, + ), + ( + "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/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 6c205c5eb..ba3c4e083 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -498,6 +498,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/crates/server/src/serve.rs b/crates/server/src/serve.rs index 788593630..1b64336f6 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, so a change applies without a restart. + #[cfg(feature = "search-inequality-filters")] + extenddb_engine::install_search_filter_settings(&storage, catalog_store.clone()); + let throttle = Arc::new(extenddb_core::throttle::ThrottleManager::new( limits.per_account_max_rcu, limits.per_account_max_wcu, diff --git a/crates/storage-postgres/Cargo.toml b/crates/storage-postgres/Cargo.toml index fda1a04b6..4b08d9c7a 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"] @@ -18,6 +19,12 @@ 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. On by default. The backend applies whatever filter +# 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] # The storage-level vector control-plane tests drive the engine directly against 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..8aaf4a9e3 --- /dev/null +++ b/crates/storage-postgres/src/catalog_settings_read.rs @@ -0,0 +1,86 @@ +// 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::{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}"); + 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 conn = pool.acquire().await.map_err(failed)?; + // A text with no parameters goes as one simple query, in which a + // statement outside a block starts when its transaction does. The + // extended protocol sets the statement's start again at Execute. + let in_block: bool = (&mut *conn) + .fetch_one(IN_TRANSACTION_BLOCK) + .await + .and_then(|row| row.try_get(0)) + .map_err(failed)?; + if in_block { + sqlx::query("SAVEPOINT extenddb_bounded_setting_read") + .execute(&mut *conn) + .await + .map_err(failed)?; + let bound = sqlx::query(SETTING_READ_BOUND).execute(&mut *conn).await; + let row = match bound { + Ok(_) => { + 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 = sqlx::query_scalar::<_, String>(READ) + .bind(&key) + .fetch_optional(&mut *tx) + .await + .map_err(failed)?; + tx.commit().await.map_err(failed)?; + Ok(row) +} diff --git a/crates/storage-postgres/src/catalog_store.rs b/crates/storage-postgres/src/catalog_store.rs index 9e49c0625..cd7d0242c 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 @@ -94,6 +97,16 @@ impl extenddb_storage::management_store::SettingsStore for PostgresCatalogStore }) } + fn get_setting_bounded( + &self, + key: &str, + ) -> futures::future::BoxFuture<'_, OpResult>> { + 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<()>> { let key = key.to_string(); let value = value.to_string(); diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 885a8f925..234e07a98 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -44,6 +44,8 @@ mod ttl_worker; 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 ee6e1053c..b0d7d2031 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. @@ -177,6 +215,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?; @@ -255,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 @@ -284,35 +362,22 @@ impl VectorSearchEngine for PostgresEngine { query = query.bind(name).bind(value_json); } - let rows = query.fetch_all(&self.data_pool).await.map_err(|e| { - 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 = 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 new file mode 100644 index 000000000..3cb37c86f --- /dev/null +++ b/crates/storage-postgres/src/vector_search_filtered.rs @@ -0,0 +1,272 @@ +// 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. +//! +//! 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; + +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)>(sqlx::AssertSqlSafe(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)>(sqlx::AssertSqlSafe(sql.as_str())) + .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")) +} + +/// 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, 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: &MapSql<'_>, +) -> Result, StorageError> { + let wanted = usize::try_from(top_k.max(0)).unwrap_or(0); + if wanted == 0 { + return Ok(Vec::new()); + } + 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()); + } + 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(sqlx::AssertSqlSafe(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..cc9bb20a7 --- /dev/null +++ b/crates/storage-postgres/src/vector_search_scan.rs @@ -0,0 +1,351 @@ +// 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. +//! +//! The cancel names the backend by process id and by the start time of the +//! 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}; + +/// One pooled connection inside the search transaction. +pub(crate) struct ScanConnection { + conn: Option>, + /// The backend's process id and the transaction's start, in + /// microseconds since the epoch. + backend: Option<(i32, i64)>, + 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: None, + pool: pool.clone(), + }; + sqlx::query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY") + .execute(scan.connection()) + .await?; + // `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 = Some(backend); + 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 the pool can lend this connection to no other + // request. + drop(conn.detach()); + let (Some(backend), Ok(runtime)) = (self.backend, tokio::runtime::Handle::try_current()) + else { + return; + }; + let pool = self.pool.clone(); + 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 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 \ + 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, XACT_OF_THIS_BACKEND, cancel_if_in_transaction}; + + /// 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; + } + 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(sqlx::AssertSqlSafe(scan_query.as_str())) + .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"); + } + + /// 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(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!( + 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() + ); + } +} diff --git a/crates/storage-postgres/tests/catalog_nul_index_writes.rs b/crates/storage-postgres/tests/catalog_nul_index_writes.rs index 48f200175..679109766 100644 --- a/crates/storage-postgres/tests/catalog_nul_index_writes.rs +++ b/crates/storage-postgres/tests/catalog_nul_index_writes.rs @@ -366,6 +366,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-postgres/tests/common/vector_filter_fixture.rs b/crates/storage-postgres/tests/common/vector_filter_fixture.rs new file mode 100644 index 000000000..baaa64c5b --- /dev/null +++ b/crates/storage-postgres/tests/common/vector_filter_fixture.rs @@ -0,0 +1,373 @@ +// 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:?}"))) + } +} + +/// 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; + } + 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(sqlx::AssertSqlSafe(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(sqlx::AssertSqlSafe(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, + &extenddb_core::limits::LimitsConfig::default(), + ) + .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/settings_read_bound.rs b/crates/storage-postgres/tests/settings_read_bound.rs new file mode 100644 index 000000000..5d43e4f95 --- /dev/null +++ b/crates/storage-postgres/tests/settings_read_bound.rs @@ -0,0 +1,119 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! 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. 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; +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_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"); + }; + 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 = Arc::new(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 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_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), + "the read failed after {:?}", + started.elapsed() + ); + + // 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_bounded("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" + ); + + // 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, plain) + .await + .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; + catalog.close().await; + admin.close().await; +} 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..dcaf0363e --- /dev/null +++ b/crates/storage-postgres/tests/settings_read_in_transaction.rs @@ -0,0 +1,135 @@ +// 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::{Executor, PgPool, Row}; + +/// 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) { + // 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 +/// `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; +} 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..2dc6dab70 --- /dev/null +++ b/crates/storage-postgres/tests/vector_search_filter.rs @@ -0,0 +1,151 @@ +// 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 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 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`. + +#![cfg(feature = "search-inequality-filters")] + +#[path = "common/vector_filter_fixture.rs"] +mod fixture; + +use std::sync::Arc; + +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}; + +/// 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")), +]; + +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() +} + +#[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"] + ); + // a missing Price satisfies <>, and 1E2 equals 100 + assert_eq!( + ids_for(f, "Country = :us AND Price <> :p10", 10).await, + ["n1", "n3", "n4", "n5"] + ); + assert_eq!( + ids_for( + f, + "Country = :us AND (attribute_not_exists(Price) OR Price = :p100)", + 10 + ) + .await, + ["n3", "n4"] + ); + assert_eq!( + ids_for(f, "Country = :us AND NOT Price BETWEEN :p5 AND :p10", 10).await, + ["n3", "n4", "n5"] + ); + }) + .await; +} + +#[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; +} + +#[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 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, + &extenddb_core::limits::LimitsConfig::default(), + ) + .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; + 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..4b7e8a773 --- /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(sqlx::AssertSqlSafe(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; +} diff --git a/crates/storage-sqlite/Cargo.toml b/crates/storage-sqlite/Cargo.toml index b34778443..26996205c 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 @@ -19,6 +20,12 @@ 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. On by default. The backend applies whatever filter +# 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] extenddb-core = { workspace = true } diff --git a/crates/storage-sqlite/src/lib.rs b/crates/storage-sqlite/src/lib.rs index 041899a2f..74086e098 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -207,6 +207,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_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_filter_tests.rs b/crates/storage-sqlite/src/vector_filter_tests.rs new file mode 100644 index 000000000..6f67fe794 --- /dev/null +++ b/crates/storage-sqlite/src/vector_filter_tests.rs @@ -0,0 +1,242 @@ +// 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 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; + +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, + &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 + .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"] + ); +} + +/// 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; + 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"] + ); +} diff --git a/crates/storage-sqlite/src/vector_search.rs b/crates/storage-sqlite/src/vector_search.rs index 0bf38134b..078af873f 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?; @@ -273,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() @@ -282,6 +284,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..6dd949889 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, @@ -185,15 +187,18 @@ 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 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>, } /// TTL table info: `(account_id, table_name, ttl_attribute)`. pub type TtlTableInfo = (String, String, String); @@ -983,6 +988,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/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<()>>; diff --git a/crates/storage/src/vector_filter.rs b/crates/storage/src/vector_filter.rs new file mode 100644 index 000000000..366d09bdb --- /dev/null +++ b/crates/storage/src/vector_filter.rs @@ -0,0 +1,33 @@ +// 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 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. +//! 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; +} 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/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, diff --git a/devtools/compile-out-search-inequality-filters b/devtools/compile-out-search-inequality-filters new file mode 100755 index 000000000..4cad81433 --- /dev/null +++ b/devtools/compile-out-search-inequality-filters @@ -0,0 +1,127 @@ +#!/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. 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 +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. + +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 +from pathlib import Path + +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: + return subprocess.run( + ["cargo", "tree", "--locked", "-e", "features", *args], + cwd=root, + check=True, + capture_output=True, + text=True, + ).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`, + 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: + 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 + + +def compile_out(root: Path) -> int: + default = re.compile(r'^default = \[(.*)\]$', re.MULTILINE) + 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}"'] + 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 + for manifest, text in edits: + manifest.write_text(text) + 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 + 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: + 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__": + sys.exit(main()) 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 92b0b10a4..fe200d26a 100755 --- a/devtools/run-tests +++ b/devtools/run-tests @@ -48,6 +48,14 @@ # 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; an +# absent setting gives every account the +# extended grammar. # # REQ-TEST-001, D-1, D-2, D-3, D-4, D-5 @@ -125,6 +133,12 @@ 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; + 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 @@ -410,6 +424,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 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." + 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 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" + fi # Import/export paths. The Python tests write fixtures via tempfile, which # honours $TMPDIR — on macOS that is under /var/folders, not /tmp. Allow @@ -706,8 +733,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 @@ -742,8 +775,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/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 diff --git a/docs/adr/0006-pgvector-storage-and-scoring.md b/docs/adr/0006-pgvector-storage-and-scoring.md index 938858fb4..9f109ed73 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-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, +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/0031-search-condition-grammar.md b/docs/adr/0031-search-condition-grammar.md new file mode 100644 index 000000000..ee3d4e314 --- /dev/null +++ b/docs/adr/0031-search-condition-grammar.md @@ -0,0 +1,101 @@ +# 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 +- 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 +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 + +- 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..d7d13b1ef 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 | +| [0031](0031-search-condition-grammar.md) | SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting | Proposed | --- diff --git a/docs/manuals/03-usage-guide.md b/docs/manuals/03-usage-guide.md index 8f04d34aa..559844eb7 100755 --- a/docs/manuals/03-usage-guide.md +++ b/docs/manuals/03-usage-guide.md @@ -434,7 +434,15 @@ 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 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 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 396e55aa0..214040065 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, 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 0c7556061..4c1d19235 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -388,6 +388,34 @@ 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 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, 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. + +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 `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 + +**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`, and on a backend without vector search a denied caller gets that refusal where it got `AccessDeniedException`. No catalog migration is required. + ### v1.1.0: latency `segments` are summed into time buckets **What changed** (#398). The latency `segments` that `/metrics` and the console's `/console/metrics-data` return come from time buckets per account and operation. 1.0.0 kept one record per request for 24 hours. Each operation's count and means are still exact over the requests that the window covers. Four things change: diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index d13bfa13a..a3f4f58b6 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -238,12 +238,12 @@ 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` | -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/docs/troubleshooting.md b/docs/troubleshooting.md index 3117e61ab..80db7da72 100755 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -461,7 +461,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/search_vectors_wire.py b/tests/search_vectors_wire.py new file mode 100644 index 000000000..068249a45 --- /dev/null +++ b/tests/search_vectors_wire.py @@ -0,0 +1,237 @@ +# 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 never change 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 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. 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: + return None + url, auth = api + resp = requests.get(url, auth=auth, timeout=30, verify=False) + if resp.status_code == 404: + 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": + return "equality" + if value in ("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 _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. + + 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..d348ce931 100644 --- a/tests/test_authz_search_vectors_index.py +++ b/tests/test_authz_search_vectors_index.py @@ -13,6 +13,34 @@ 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`` 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 +{"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. @@ -38,10 +66,13 @@ 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 +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 +169,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 +178,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 +189,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 +214,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 +302,266 @@ 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"]}}, + }, + ], +} + + +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": [ + {"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 + + +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-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, + ), + "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}", + ), + "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"}}, + "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", + TOP_K_OF_ZERO, + ), + "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) + + +@pytest.fixture(scope="module") +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( + "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, deny_null, bare_not_equals, vector_table, row +): + policy, members, error, expected = ROWS[row] + 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}" + 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 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}" diff --git a/tests/test_search_vectors_condition_limit.py b/tests/test_search_vectors_condition_limit.py index 0f3f873f4..8aa0c6c73 100644 --- a/tests/test_search_vectors_condition_limit.py +++ b/tests/test_search_vectors_condition_limit.py @@ -3,10 +3,12 @@ """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, 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 @@ -28,6 +30,18 @@ ExtendDB's wording differs from the service's. Those tests assert that the check, not the count, answers. +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`` +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. + 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 @@ -38,25 +52,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 = ( @@ -67,10 +71,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" @@ -82,6 +82,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] @@ -93,82 +118,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 ], @@ -192,33 +149,29 @@ 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.""" + return grammar_of(lambda: _search_expr(search_table, ["h = :v0", "f1 <> :v1"])) + + +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]: @@ -273,12 +226,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 @@ -297,40 +244,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 +385,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,47 +422,50 @@ 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) - 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_deep_conditions.py b/tests/test_search_vectors_deep_conditions.py new file mode 100644 index 000000000..22a600286 --- /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, 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) diff --git a/tests/test_search_vectors_expression_maps.py b/tests/test_search_vectors_expression_maps.py new file mode 100644 index 000000000..6780f6bdd --- /dev/null +++ b/tests/test_search_vectors_expression_maps.py @@ -0,0 +1,228 @@ +# 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, each request twice with +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. +""" + +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 + + 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): + 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) + + 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) + 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 new file mode 100644 index 000000000..4e6c0f6ca --- /dev/null +++ b/tests/test_search_vectors_inequality_filters.py @@ -0,0 +1,559 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""SearchVectors with the extended SearchConditionExpression grammar. + +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 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. + +Every expected response was measured against the live service in +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`` +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 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. + +The checks on the expression maps are in ``test_search_vectors_expression_maps.py``, +which runs under both grammars. +""" + +from __future__ import annotations + +import re +import time +import pytest +import requests + +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: " +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})" + ) + + +# 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 _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, + } + 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) + + +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"]} + + +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 vector_table(): + """Table with HASH Country (S), inline filters Category (S), Price (N), Tag (B).""" + name = table_name() + create_vector_table(name, CREATE) + try: + 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 + # 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, "Country = :us")) != US: + if time.monotonic() > deadline: + raise TimeoutError("items did not reach the vector index") + time.sleep(0.1) + yield name + finally: + 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: + 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: + """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")) + 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_binary64(self, grammar_table): + assert _ids(_search(grammar_table, H + "Price = :p100")) == {"i6", "i7"} + 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"} + + 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 resp.status_code == 200, resp.text + 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 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) + _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_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( + _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", + ) + + +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 TestExpressionMapsUnderTheExtendedGrammar: + """Map checks whose request only the extended grammar parses.""" + + def test_unused_names(self, grammar_table): + unused = "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}" + 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"') + + 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", + 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. + + 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") + 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") + _refused(resp, INDEX_NOT_SUPPORTED) + _refused(_search(name, "Country = = :us"), SEARCH_NOT_SUPPORTED) diff --git a/tests/test_search_vectors_metrics.py b/tests/test_search_vectors_metrics.py new file mode 100644 index 000000000..701717298 --- /dev/null +++ b/tests/test_search_vectors_metrics.py @@ -0,0 +1,131 @@ +# 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]}" + # The response leaves out `segments` when it has no entry. + return sum( + s["count"] + for s in resp.json().get("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