Skip to content

fix(query): classify and order key conditions on a multi-attribute GSI the way the service does - #429

Merged
LeeroyHannigan merged 5 commits into
mainfrom
fix/gsi-multi-range-query
Oct 31, 2026
Merged

LeeroyHannigan merged 5 commits into
mainfrom
fix/gsi-multi-range-query

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #381.

What the service does

Measured on 2026-10-21 against live DynamoDB with the issue's schema (GSI with HASH h and RANGE a, b, c, d) and a two-HASH index:

  • Results are ordered over every RANGE attribute in key-schema order, then the base table key; ScanIndexForward = false returns the exact mirror. LastEvaluatedKey carries every key attribute.
  • A key condition is served when every HASH attribute has an equality and the RANGE conditions cover a leading run of the RANGE attributes, with an equality on every one before the last; the last may use <, <=, >, >=, BETWEEN or begins_with. Clause order is free.
  • Refusals, in the order the service applies them: a second condition on one key attribute (KeyConditionExpressions must only contain one condition per key); more conditions than key attributes (The number of query conditions (6) exceeds the number of key attributes defined in the schema (5)); a HASH attribute without an equality (HASH key attributes h1, h2 must have equality conditions specified in the query); a RANGE gap (RANGE key attributes a must have equality conditions specified in the query because a condition is present on key attribute b); a value whose type differs from the attribute definition (One or more parameter values were invalid: Condition parameter type does not match schema type); a condition on an attribute outside the key schema, named by the first RANGE attribute without a condition (Query condition missed key schema element: a). begins_with on a number attribute is Incorrect operand type for operator or function; operator or function: begins_with, operand type: N.
  • dynamodb:LeadingKeys on a Query of a GSI with two HASH attributes is the first HASH attribute's value (measured 2026-10-20). g1 = :a on HASH g1, g2 answers ValidationException to every principal, including one fenced away from the value (measured 2026-10-21).
  • A clause on an attribute outside the queried key schema is refused by the key schema rule whatever its value's type. Measured 2026-10-30 on a GSI with HASH GSI2PK (S) and RANGE GSI2SK (S) of a table keyed on PK (S): GSI2PK = :h AND PK = :k answers Query condition missed key schema element: GSI2SK with :k an S, the type the table defines for PK, and with :k an N, two samples each.

What ExtendDB did

KeyCondition::resolve_multipart returned early for one HASH attribute, so the parser's assignment stood: results were ordered by the first RANGE attribute then the table key, every key condition with three or more clauses was refused as Query condition missed key schema element: h, and h = :h AND b = :b was accepted and returned nothing.

Changes

  • crates/core/src/expression/key_condition.rs: resolve_multipart classifies every clause by name and applies the rules above in the service's order. resolve_multipart_with takes a per-clause value check, which the engine supplies with the attribute definitions, so a wrong-typed value is reported after the structural rules and before the non-key rule, as measured. resolve_key_schema_with chooses between the classifier and resolve_pk_sk for the key schema the query reads, and both the engine and authorization call it.
  • crates/engine/src/query.rs: the key condition goes through resolve_key_schema_with with the type check. On a multi-attribute key schema the type check reads the queried key schema's attribute definitions only, so a clause on another attribute gets the non-key rule, as measured. The single-attribute path runs the type check, against the table's definitions, ahead of its missing-key check (a wrong-typed sort key value answered 500 before). That path has no non-key rule yet (see the known divergences below), so a clause on another attribute reaches storage, and the table's definitions are what refuse a value of the wrong type for it. begins_with on a number attribute is refused with the measured wording.
  • crates/server/src/leading_keys.rs: query_leading_keys assigns the clauses with resolve_key_schema, the engine's classification. With resolve_pk_sk it found no partition key in three-clause orders such as g2 = :g AND g1 = :v AND gs = :x or b > :lo AND a = :a AND h = :v, which the engine now serves, so a ForAllValues:StringEquals LeadingKeys fence let the query read any partition of the index.
  • crates/engine/src/legacy_filter.rs: KeyConditions on a multi-attribute schema go through the same classifier.
  • crates/storage-sqlite and crates/storage-postgres: every RANGE condition is applied to its column; ORDER BY and the row-comparison cursor cover all RANGE columns.
  • crates/storage/src/util/key.rs, crates/storage-mongodb, crates/storage-cassandra: these two backends filter the first RANGE attribute of such an index only. A condition on a later RANGE attribute is refused with a ValidationException naming the attribute and the backend, instead of being applied to the wrong column.
  • crates/storage-cassandra/src/data/query.rs: on main, every Query on a Cassandra index with two or more RANGE attributes answers 500 (measured on ec81e9d4: hash-only, first-RANGE equality and first-RANGE range conditions all return Order by currently only supports the ordering of columns following their declared order in the PRIMARY KEY from Cassandra). The index table clusters on every RANGE column ahead of base_pk, so the ORDER BY now names every index RANGE column in declared order; those queries answer 200 with the page in clustering order. A Query with an ExclusiveStartKey on such an index also answered 500 and is now refused with a ValidationException (ExclusiveStartKey on index gsi: the Cassandra backend pages a Query over an index with one RANGE attribute only), because the cursor compares the first RANGE attribute only. docs/differences-from-dynamodb.md records both backends.

Changes from the review of 30 October

  • fix(auth): bind LeadingKeys through the engine's key condition classification: authorization reads a multi-attribute key condition the way the engine does, so the three-clause orders from the review are denied to a principal fenced away from the first HASH attribute's value, and g1 = :a on HASH g1, g2 answers ValidationException to every principal, as the service does.
  • test(core): pin the condition count refusal ahead of the HASH and RANGE checks: unit cases with the HASH attribute missing or a RANGE gap and more conditions than key attributes.
  • test(query): take the first-RANGE-only branch from the backend under test: tests/test_gsi_multi_range_query.py reads the backend from EXTENDDB_TEST_BACKEND or the server's config file and fails when the server's reply does not match it, instead of skipping the served-result cases.
  • fix(query): type-check only the queried key schema on a multi-attribute index: a value of another type on an attribute the table defines for its base key or another index gets Query condition missed key schema element in place of the type sentence, which is the service's answer.

Verification

tests/test_gsi_multi_range_query.py, 64 cases: order, pages and LastEvaluatedKey, each accepted shape, each refusal and its text, legacy KeyConditions, the value type rule, and the MongoDB and Cassandra refusal. Every expectation in the first 61 cases was measured on the service. On 2026-10-30 the whole file at 3893bf63 ran against the service and passed, 63 passed and 1 skipped (the MongoDB and Cassandra refusal, which runs only on a target that refuses), so the three cases for a value on an attribute outside the queried key schema are measured on indexes with several key attributes too.

target result
live DynamoDB 63 passed, 1 skipped (the MongoDB and Cassandra refusal case), at 3893bf63 on 2026-10-30
SQLite 63 passed, 1 skipped
PostgreSQL 16 63 passed, 1 skipped
MongoDB 7 42 passed, 22 skipped (served-result cases), at 46a66b53
Cassandra 4.1 42 passed, 22 skipped (served-result cases), at 46a66b53. The first push of this branch errored at the module fixture (61 errors, the hash-only Query answered 500 as on main); the ORDER BY change fixed that
main at ec81e9d4, SQLite 30 of the 30 then-existing cases failed
2b05987b (before the review fixes), SQLite and PostgreSQL the three cases for an attribute outside the queried key schema fail, answering the type sentence

tests/test_fgac_leading_keys.py on servers built from this branch: 29 passed on SQLite, PostgreSQL and MongoDB, and 28 passed on Cassandra, where test_oversized_requests_fail_validation_before_authorization was not run. On servers built from 2b05987b the Query shape test fails on both: each of the eleven three-clause orders returns rows to the principal fenced away from the partition, and g1 = :a on the two-HASH index answers AccessDeniedException to that principal where the service answers ValidationException. The new orders combine two measured rules, LeadingKeys is the first HASH attribute's value and clause order is free; the shapes themselves were run against ExtendDB only.

Regression on the branch servers: test_multipart_gsi.py, test_query_scan.py, test_conditional_operator.py, test_expression_param_usage.py and test_item_operations.py, 309 passed on SQLite and 309 passed on PostgreSQL. A 67-request probe comparing the branch with the service case by case leaves 13 differences, all present on main and outside this change: the parser's wording for two non-equality clauses (#427), the 2048-byte hash key and 1024-byte aggregate range key limits on Query, and an extra page with a LastEvaluatedKey when Limit lands on the last item.

Negative controls on the committed tree, each restored with git checkout: the eight classifier mutations (missing-HASH order, RANGE duplicate detection, non-equality duplicate detection, RANGE gap window, non-equality excluded from the gap, early return widened, non-key refusal disabled, count refusal disabled) each fail their unit test; the count check moved after the missing-HASH and RANGE-gap checks fails the new count ordering test and passes the other 39 key_condition tests; the type check disabled fails 6 wire cases; the begins_with rule disabled fails 1; the MongoDB refusal disabled fails 18 wire cases on wrong items or order. With EXTENDDB_TEST_BACKEND=mongodb against a SQLite server, tests/test_gsi_multi_range_query.py from 2b05987b passes (60 passed, 1 skipped) and the new file fails with 23 errors.

Gates: cargo fmt --check; cargo +1.97.0 clippy --all-targets -D warnings on core, engine, storage and the four storage crates, and on core, engine and server for the review changes; cargo +1.88.0 build on the same, and cargo +1.88.0 check on core, engine and server; unit tests core 537, engine 178 and server 204 on this revision, and storage 72, storage-sqlite 101, storage-postgres 46, storage-mongodb 96 and storage-cassandra 52 on the earlier push (the review changes do not touch the storage crates). No dependency change.

Not in this change

Pre-existing, filed separately: #427 (the parser refuses a lone non-equality, or two non-equalities, before the key schema is known, so the wording differs from the service); Query does not enforce the key value size limits the service applies (Size of hashkey has exceeded the maximum size limit of2048 bytes, Aggregated size of all range keys has exceeded the size limit of 1024 bytes); a Limit that lands on the last item returns a LastEvaluatedKey and one more empty page where the service returns none. Full support for several RANGE attributes on the MongoDB and Cassandra backends (typed fields and clustering for every RANGE attribute) is a separate change.

Known divergences found in review, present on main, filed as #673 (Cassandra) and #674 (single-attribute key schema):

  • Cassandra: paging a Query on a GSI with HASH h1, h2 and RANGE r reads h2 as the cursor's sort key (crates/storage-cassandra/src/data/query.rs, query_key_schema[1]). Page 2 of h1 = :x AND h2 = :y repeats page 1 when h2 is N and answers 500 when it is S. On any GSI with a RANGE attribute, a key condition on that attribute together with an ExclusiveStartKey answers 500 on page 2. The new row in docs/differences-from-dynamodb.md covers indexes with several RANGE attributes only.
  • SQLite and PostgreSQL, single-attribute key schema: a key condition clause on a non-key attribute is applied to the first RANGE column. pk = :p AND zz = :v returns the item whose sort key equals :v, and a value of another type than the sort key answers 500. The service refuses such a clause with Query condition missed key schema element: <RANGE attribute> whatever the value's type (measured 2026-10-30, above), and the multi-attribute path here does the same. Until the single-attribute path has that rule, its type check keeps reading the table's definitions, so ExtendDB answers the measured GSI2PK = :h AND PK = :k with the type sentence when :k is an N, and with 200 and the condition applied to GSI2SK when :k is an S.

Also not changed here: the type check runs before the unused-value check, so pk = :p AND sk > :s with a wrong-typed :s and an unused :u gets the type sentence, where main reports the unused value; the #544 paragraph below covers where the service reports it. Legacy KeyConditions with two or more non-EQ conditions report the RANGE-gap message, or Query key condition not supported, before the count, HASH and non-key rules; only the wording differs, and the service is measured for one shape in that class.

Overlap with other open PRs

Rebase on #395

Rebased on main at 3051e500 (#395) on 30 October, after the review commits. Main's tests/conftest.py already has configured_backend(), so the LeadingKeys commit now reads the backend through it in tests/test_fgac_leading_keys.py and tests/test_ttl.py instead of adding its own copy. That was the only conflict in the review commits; the first commit had one more, a row in docs/differences-from-dynamodb.md. 46a66b53 is the head before the rebase, with the same changes, and the MongoDB and Cassandra rows above are from it.

On 3893bf63: workspace clippy with -D warnings; --lib tests core 713, engine 183 and server 222; tests/test_fgac_leading_keys.py, tests/test_gsi_multi_range_query.py and tests/test_ttl.py on a SQLite server, 103 passed and 1 skipped; and tests/test_gsi_multi_range_query.py against the service, 63 passed and 1 skipped.

Rebase on #511

Rebased on main at 1c0523c9 (#511) on 30 October. #511 binds LeadingKeys to the partition operand of a key condition the engine refuses, and it changed query_leading_keys and key_condition.rs as well, so the two conflicted. #511's path through the clauses stays. When a clause compares the partition attribute by equality, equality_pk_value reads the condition through resolve_key_schema with the queried key schema in place of resolve_pk_sk, and a single clause under an operator the engine rejects binds its operand. The legacy KeyConditions path keeps #511's operator list. multi hash gsi missing g2 now answers ValidationException to every principal, as the service does, so QUERY_REJECTED_CODE_DIVERGES, which held only that entry, is removed from tests/test_fgac_leading_keys.py. In key_condition.rs both sides added tests at the end of the test module, and both are kept.

On a7e14d8e: cargo fmt --check; workspace clippy with -D warnings; --lib tests core 715, engine 183 and server 237; tests/test_fgac_leading_keys.py, tests/test_gsi_multi_range_query.py and tests/test_ttl.py on a SQLite server, 105 passed and 1 skipped, and on a PostgreSQL 16 server, 105 passed and 1 skipped. The two extra passes are #511's tests. The run against the service is the one at 3893bf63 and was not repeated on this head.

@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

Measured on the service on 2026-10-23 while working #427 (each row twice, identical answers), for the placement of the type check this PR adds:

  • Multi-attribute index (multi-idx, HASH h, RANGE a b c d), h > :n with :n = {"N": "1"}: HASH key attributes h must have equality conditions specified in the query. The HASH wording precedes the type check on a multi-attribute index.
  • Single-attribute schema, pk > :n with :n = {"N": "1"} on an S key: One or more parameter values were invalid: Condition parameter type does not match schema type. The type check precedes the no-HASH-equality wording there.
  • pk > :n with an unused :y: Value provided in ExpressionAttributeValues unused in expressions: keys: {:y}; pk > :n with FilterExpression="nope(": Invalid FilterExpression: Syntax error; token: "<EOF>", near: "(". Both precede the type check.
  • sk >= :v with :v = {"N": "1"} on an S sort key, with or without an ExclusiveStartKey: the type sentence. ExtendDB answers InternalServerError for the sort key bound today; worth confirming the check covers the sort key clause and not only the partition value.
  • begins_with(pk, :n) with :n = {"N": "1"} on an N key: Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: begins_with, operand type: N.

#479 conflicts with this branch in crates/engine/src/query.rs (the partition key block); whichever merges second gets rebased, and the resolution keeps both orders above.

LeeroyHannigan added a commit that referenced this pull request Oct 29, 2026
… reach

Closes #440.

A Query ExclusiveStartKey from another partition, or outside the sort key
condition, was accepted and answered an empty page. The service refuses
it, with a sentence chosen by where the key falls. Measured on 2026-10-23
and 2026-10-24, every row repeated with identical answers, page-end rows
ten times each.

After the shape check, the service first asks whether a later key in the
scan direction can still satisfy the sort key condition, for either
partition:

- On a base table a later key must differ from the start key's sort
  value: ">" and "<" at the bound are refused, ">=" at the bound is
  accepted, "<=" at the bound refused, BETWEEN at the upper bound refused
  and at the lower bound accepted, begins_with with a key that does not
  carry the prefix refused; the reverse direction mirrors each.
- On an LSI or GSI a repeat of the start key's sort value counts as a
  later key, because index keys repeat: "<=", BETWEEN at either bound,
  ">=" in reverse, begins_with in reverse at the prefix and "=" with the
  key itself are all accepted; ">" and "<" at the bound are refused.
- The sentence is "The provided starting key does not match the range
  key predicate", with two base-table exceptions in the same partition:
  "=" with the key's own value: "The provided exclusive start key is
  invalid"; begins_with in reverse with the key exactly the prefix: "The
  provided starting key is outside query boundaries based on provided
  conditions".

Then the partition, when the key's partition differs from the condition's
(table, LSI, GSI, legacy KeyConditions, either direction):

- no sort key condition: "The provided starting key is outside query
  boundaries based on provided conditions";
- any sort key condition: "The query can return at most one row and
  cannot be restarted".

A hash-only base table refuses every ExclusiveStartKey with "The provided
exclusive start key is invalid", the queried partition included, and its
pages never carry a key. Partition values compare by value for numbers
(1, 1.0, 1e0, 01, +1 are equal); strings by UTF-8 byte order; binary by
byte order.

Page end: when a base table page ends on the last key that can satisfy
the sort key condition in the scan direction, the service returns no
LastEvaluatedKey (ten of ten for "=", BETWEEN at the upper bound, "<=" at
the bound, reverse ">=" at the bound). ExtendDB now drops the key there,
so a client that feeds every returned key back is never refused. Index
pages are unchanged.

Ordering, measured: filter and projection faults, unused names and
values, ConsistentRead on a GSI, Limit, a missing table or index, the
key size check and the start key shape check (missing or extra
attributes, wrong types) are reported first; the Select checks after.

The checks live in crates/engine/src/start_key.rs, called from
handle_query after the shape check. The sort key predicate is evaluated
with the expression evaluator on the start key's sort value, so every
operator and type follows the same comparison as the condition itself.

Tests: engine unit tests in start_key_tests.rs and start_key_range_tests.rs;
tests/python/test_query_start_key_partition.py, test_query_start_key_range.py
and test_query_start_key_index.py (162 rows, the hash-only page row
ExtendDB only) pass against the service and on SQLite and PostgreSQL, with
test_read_paging.py and the Query wire files. Pagination walks with Limit
1 to 3 in both directions feed every returned key back without a refusal.

Pre-existing, measured, not changed here: a sort key bound of another
type than the sort key answers InternalServerError (the type check in
#429); the service omits the trailing key when the next row exists but
fails the condition ("sk < z" with Limit equal to the matches), which
needs a storage look-ahead and is filed separately.

@robinnsc robinnsc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The classification and ordering look right. On local SQLite and PostgreSQL, a reference model built from the rules in the description matched every page over a few thousand checks: all RANGE attributes, both directions, Limit 1/2/3/7 across full-key ties, LastEvaluatedKey, COUNT, filters, legacy KeyConditions, and random clause orders and aliases. Main failed nearly all of the same checks. MongoDB and Cassandra behaved as documented. Performance is better: SQLite and PostgreSQL now read the ordering index with no sort, and hash-only reverse queries with Limit 10 on a 20k-item partition went from about 17 ms to about 3 ms. Base-table and single-attribute queries are unchanged.

The one thing I'd hold this for is the LeadingKeys interaction in the first inline comment. Authorization still picks the partition clause the old way, and this PR makes the engine serve clause orders it used to refuse.

Smaller notes, not blocking:

  • Cassandra, pre-existing: on a two-HASH index with one RANGE attribute (h1, h2; r), data/query.rs:264 reads the cursor's sort key as query_key_schema[1], which is h2. Paging h1 = :x AND h2 = :y repeats rows after the first page, and with a condition on r the second page answers 500 (Column "sk_n" cannot be restricted by both an equality and an inequality relation). Probably worth its own issue. The new differences row reads as if single-RANGE indexes page fine.
  • Legacy KeyConditions with two or more non-EQ conditions return the RANGE-gap or Query key condition not supported before the count, HASH and non-key rules, e.g. h LT, d GE gets the RANGE message rather than the HASH one. Only the wording differs, and the service is measured for just one shape in that class.
  • Nothing pins the count refusal ahead of the missing-HASH and RANGE-gap refusals. Moving the count check after both still passes all 37 key_condition tests, because every count case has every key attribute. a = :a AND b = :b AND c = :c AND z1 = :z AND z2 = :y (h missing) would pin it.
  • Description: the regression file set gave 309 passed on PostgreSQL here rather than 180.

Comment thread crates/engine/src/query.rs Outdated
// A wrong-typed value is reported after the structural rules and
// before the non-key rule (measured 2026-10-21), so the type check
// runs inside the classifier.
key_condition.resolve_multipart_with(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this needs a matching change in authorization before it goes in. query_leading_keys (crates/server/src/leading_keys.rs:253-262) still finds the LeadingKeys value with parse_key_condition + resolve_pk_sk and then checks pk_path == first HASH attribute. On main that was safe, because the engine ran the same check and refused anything authorization couldn't read. Here multi-attribute schemas skip it and classify by name, so for some 3+ clause orders authorization finds no key while the engine serves the query. Under ForAllValues:StringEquals dynamodb:LeadingKeys an absent key passes.

Reproduced on SQLite and PostgreSQL head, with a principal fenced to ["alice"] on the table and /index/* and every query naming bob:

  • GSI (g1, g2 HASH; gs RANGE): g2 = :g AND g1 = :b AND gs = :x, gs = :x AND g1 = :b AND g2 = :g, g2 = :g AND g1 = :b AND gs > :lo, and the #name variants return bob's items.
  • GSI (h HASH; a, b RANGE): a = :a AND h = :b AND b = :c, b = :c AND h = :b AND a = :a, a = :a AND h = :b AND b > :lo, b > :lo AND a = :a AND h = :b, and begins_with(b, :p) AND a = :a AND h = :b return bob's items.
  • On main all of these are ValidationException. Two-clause orders, the base table, LSIs, single-RANGE GSIs and legacy KeyConditions still bind correctly, and ForAnyValue or a Null guard denies.

Possible fix: when is_multipart_key_schema holds, have query_leading_keys call resolve_multipart(&hash_attrs, &range_attrs, &names) (no type check) instead of resolve_pk_sk. It leaves the first HASH attribute in pk_path, so the existing check and value_of bind the right value. Sharing one "classify for this key schema" function between the engine and authorization would keep them from drifting again. QUERY_ACCEPTED in tests/test_fgac_leading_keys.py only has two-clause orders on a HASH-only index, so adding the shapes above there should fail today and pass with the fix.

.position(|(n, _)| *n == name)
.map(|pos| (pos, all_sks[pos].1))
};
if let Some(sk_cond) = &key_condition.sk_condition

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-existing, but since these lines are rewritten: on a single-attribute schema a condition on a non-key attribute falls through to the first RANGE column. On pk S / sk N, pk = :p AND zz = :v with :v N 4 returns the item whose sk is 4. On a GSI (h; a), h = :h AND pk = :v filters on a. With mismatched types it's a 500. PostgreSQL does the same at query_scan.rs:190. The multi-attribute path now refuses these with Query condition missed key schema element, so the two paths disagree. Could consider applying the same count and non-key rules on the single-attribute path in query.rs too.

use extenddb_core::expression::Expr;
use extenddb_core::types::{AttributeValue, ScalarAttributeType};

let Some(attr) = resolve_path_attr_name(path, &maps.names) else {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

query_key_info.attribute_definitions is the table-wide list for an index query (query.rs:158), so a clause on an attribute that is defined but isn't in the queried index's key schema also gets type-checked here. On GSI (h; a), h = :h AND sk = :s (the base table's N sort key, S value) answers the type sentence, where the stated rules would give Query condition missed key schema element: a. The service isn't measured for that case, so this might be fine, but filtering the definitions to the queried key schema would line it up with the doc comment.

Comment thread crates/engine/src/query.rs Outdated
// value ahead of the missing-key check (measured 2026-10-21: `pk = :n`
// on an S key with a second clause on a non-key attribute reports the
// type, not the missing key).
for_each_key_clause(&key_condition, |path, value| {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the type check now runs before the unused-value check (query.rs:430) and filter parsing. So pk = :p AND sk > :s (S value on an N sort key) plus an unused :u answers the type sentence where main answered Value provided in ExpressionAttributeValues unused, and the same goes for a bad FilterExpression. The #544 paragraph in the description covers where the service puts it, so this is probably known. Just noting it shows up on this branch alone too.

FIRST_RANGE_ONLY_MARK = "applies a key condition to the first RANGE attribute"


@pytest.fixture(scope="module")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

first_range_only decides from the server's reply whether to skip the 22 served-result tests. If SQLite or PostgreSQL ever started answering with the MongoDB refusal, the module would report 39 passed / 22 skipped and stay green. Might be worth taking the branch from EXTENDDB_TEST_BACKEND like tests/test_ttl.py does, and failing when the reply doesn't match the backend.

@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Pushed four commits:

  • LeadingKeys (baa5ea9): authorization now reads the key condition through the engine's classification, KeyCondition::resolve_key_schema_with, which picks the multi-attribute classifier or resolve_pk_sk and which the engine and query_leading_keys both call. Your g1, g2; gs and h; a, b shapes and the #name variants are in QUERY_ACCEPTED. On 2b05987 each returned rows to the principal fenced away from the partition, now each is denied on SQLite and PostgreSQL. g1 = :a on the two-HASH index also answers ValidationException to every principal now, as the service does.
  • Count ordering (aab50ad): your case has five conditions on the five key attributes of h; a, b, c, d, so the missing-HASH rule answers it. The test uses six conditions instead, one set with h missing and one with a RANGE gap, plus your five clauses on h1, h2; r. With the count check moved after both checks it fails, and the other 39 key_condition tests pass.
  • first_range_only (b31bd1d): the backend comes from EXTENDDB_TEST_BACKEND or the config file, as in tests/test_ttl.py, and the fixture fails when the reply doesn't match. With EXTENDDB_TEST_BACKEND=mongodb against SQLite the old file passes and the new one errors on 23 tests.
  • Index type check (46a66b5): on a multi-attribute key schema the type check reads the queried key schema's definitions only. That matches the service: on a GSI with HASH GSI2PK and RANGE GSI2SK, GSI2PK = :h AND PK = :k answers Query condition missed key schema element: GSI2SK with :k an S and with :k an N, and the three new cases in tests/test_gsi_multi_range_query.py pass against the service, with the rest of the file. Your h; a case is on the single-attribute path, which has no non-key rule yet (your query_scan.rs:90 comment). I left the table's definitions there, since without that rule an N value would reach storage and answer 500.
  • Description: 309 passed on both SQLite and PostgreSQL in this run, and the file list names the five files.

Filed separately: the Cassandra two-HASH cursor as #673 and the single-attribute non-key fall-through as #674, with the measurement above in the second. On main page 2 of the cursor repeats page 1 when h2 is N and answers 500 when it's S. A key condition on r plus an ExclusiveStartKey also answered 500 on page 2 of a one-HASH Cassandra GSI, so that part isn't about two HASH attributes.

Not changed: the type check running before the unused-value check, which the #544 paragraph covers, and the legacy KeyConditions order for two or more non-EQ conditions, where only the wording differs and the service is measured for one shape.

@LeeroyHannigan
LeeroyHannigan force-pushed the fix/gsi-multi-range-query branch from 46a66b5 to 3893bf6 Compare October 30, 2026 12:34
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

Rebased onto main to clear a conflict in tests/conftest.py: main already has configured_backend(), so the LeadingKeys commit now uses it instead of adding its own copy. The four review commits are now 4732501 (LeadingKeys), dce457a (count order), 7cfc727 (first_range_only) and 3893bf6 (index type check).

…I the way the service does

On a global secondary index with one HASH attribute and several RANGE attributes, Query ordered results by the first RANGE attribute and then the table key, refused every key condition with three or more clauses as "Query condition missed key schema element: h", and accepted a condition that skipped the first RANGE attribute while returning no items. KeyCondition::resolve_multipart returned early when the schema had one HASH attribute, so the parser's assignment stood: the first equality became the partition key and the rest sat where the engine's HASH-count check refused them.

Measured against the service on 2026-10-21, with the issue's schema (HASH h, RANGE a, b, c, d) and with two HASH attributes:

- Results are ordered over every RANGE attribute in key-schema order, then the base table key; ScanIndexForward = false is the exact mirror. LastEvaluatedKey carries every key attribute.
- A key condition is served when the HASH attributes all have an equality and the RANGE conditions cover a leading run of the RANGE attributes with an equality on every one before the last; the last may use <, <=, >, >=, BETWEEN or begins_with. Clause order in the expression is free.
- Refusals, in the order the service applies them: a second condition on one key attribute ("KeyConditionExpressions must only contain one condition per key"); more conditions than key attributes ("The number of query conditions (6) exceeds the number of key attributes defined in the schema (5)"); a HASH attribute without an equality ("HASH key attributes h1, h2 must have equality conditions specified in the query", every missing one named); a RANGE gap ("RANGE key attributes a must have equality conditions specified in the query because a condition is present on key attribute b"); a value whose type differs from the attribute definition ("One or more parameter values were invalid: Condition parameter type does not match schema type"); a condition on an attribute outside the key schema, named by the first RANGE attribute without a condition ("Query condition missed key schema element: a"). begins_with on a number attribute is "Incorrect operand type for operator or function; operator or function: begins_with, operand type: N". The single-attribute wording "Query condition missed key schema element" stays on single-attribute schemas.

resolve_multipart now classifies every clause by name against the HASH and RANGE attribute lists and applies those rules in that order; the value type check runs inside it through resolve_multipart_with, with the engine supplying the attribute definitions. The engine's single-attribute path gets the same type check ahead of its missing-key check, which turns a 500 on a wrong-typed sort key value into the service's refusal. Legacy KeyConditions on a multi-attribute schema go through the same classifier. The SQLite and PostgreSQL backends apply every RANGE condition to its column and order and page over all RANGE columns; the cursor keeps its shape. The MongoDB and Cassandra backends filter the first RANGE attribute only and now refuse a condition on a later one instead of applying it to the wrong column. On Cassandra every Query on an index with several RANGE attributes answered 500 before this change: the index table clusters on every RANGE column and CQL rejects an ORDER BY that skips one, so the ORDER BY now names every index RANGE column in declared order, and a Query with an ExclusiveStartKey on such an index is refused instead of answering 500, because the cursor compares the first RANGE attribute only. docs/differences-from-dynamodb.md records both backends.

tests/test_gsi_multi_range_query.py pins 60 cases, all measured on the service: order, pages and LastEvaluatedKey, every accepted shape, every refusal and its text, legacy KeyConditions, and the MongoDB and Cassandra refusal. 60 pass on the service and on SQLite and PostgreSQL; on MongoDB 39 pass and the 22 served-result cases skip; on Cassandra the same 22 skip. On main 30 of the 30 then-existing cases failed. Unit tests in core cover the classifier rules; the storage plan and cursor tests cover the ORDER BY and cursor columns.

Closes #381
…fication

On a key schema with several HASH or several RANGE attributes the engine
assigns every key condition clause to its key attribute by name, so it serves
clause orders such as `g2 = :g AND g1 = :v AND gs = :x` and
`b > :lo AND a = :a AND h = :v`. Authorization still read the partition
equality with `resolve_pk_sk`, found no partition key in those orders and left
dynamodb:LeadingKeys absent, so a ForAllValues:StringEquals fence let the
query read any partition of the index.

`KeyCondition::resolve_key_schema_with` holds the choice between the
multi-attribute classifier and `resolve_pk_sk`. The engine calls it, and so
does `equality_pk_value`, which `query_leading_keys` calls for a condition
with an equality on the partition attribute. When a clause compares the first
HASH attribute by equality, authorization binds that attribute's value for
every clause order the engine serves, and a condition the classifier refuses
leaves the key absent. For `g1 = :a` on HASH `g1`, `g2` that gives the
answer the service gives every principal, ValidationException (measured
2026-10-21). A single clause on the partition attribute under an operator
the engine rejects still binds that clause's operand, as it does on main
since #511.

tests/test_fgac_leading_keys.py adds the three-clause orders from the review on
a GSI with HASH `g1`, `g2` and RANGE `gs` and a GSI with HASH `h` and RANGE
`a`, `b`, and expects ValidationException for the missing-g2 shape from the
principal fenced away from the value. That shape was the only entry in the
list of codes that still differed from the service, so the list is removed.
It and tests/test_ttl.py read the backend through `configured_backend()` in
tests/conftest.py, so this file can expect the MongoDB and Cassandra refusal
of a condition on `b`.
LeeroyHannigan added a commit that referenced this pull request Nov 1, 2026
…service does

Closes #427.

A Query whose KeyConditionExpression has no equality clause on the HASH
attribute was refused with a parser sentence of ExtendDB's own. The service
chooses the sentence from the key schema. Measured on 2026-10-23, every row
repeated with identical answers:

- Single HASH attribute, any clause names it (so the clause on it is a
  non-equality): "Query key condition not supported". Rows: pk > :x,
  pk BETWEEN :x AND :y, begins_with(pk, :x), pk > :x AND sk = :y,
  sk = :x AND pk > :y, zz = :x AND pk > :y, and the GSI forms.
- Single HASH attribute, no clause names it: "Query condition missed key
  schema element: <HASH>". Rows: sk > :x, zz > :x, sk > :x AND zz > :y,
  zz = :x AND yy = :y, and the GSI forms naming the index HASH attribute.
- Several key attributes (two HASH attributes, or one HASH with several
  RANGE attributes): "HASH key attributes h1, h2 must have equality
  conditions specified in the query", naming every HASH attribute, for
  every operator and for an N value on the HASH attribute.
- Two conditions on one attribute: "Invalid KeyConditionExpression:
  KeyConditionExpressions must only contain one condition per key".
- An undefined #name or :value in the key condition is refused first, with
  the "Invalid KeyConditionExpression: " prefix. The rows include pk = :x
  with no values.
- Single HASH attribute, a value of the wrong type: pk > :n with an N value
  on an S key answers "One or more parameter values were invalid: Condition
  parameter type does not match schema type", and begins_with(pk, :n) on an
  N key answers "Invalid KeyConditionExpression: Incorrect operand type for
  operator or function; operator or function: begins_with, operand type: N".
- Legacy KeyConditions is desugared with every reference defined and an
  equality clause, or refused there; no change.

Measured on 2026-11-01, two samples each, on a single HASH attribute
schema: two conditions on one attribute answer the one condition per key
sentence whatever their value types (pk > :x AND pk < :n). A wrong-typed
value is reported only in the clause on the HASH attribute:
pk > :n AND sk > :y, sk = :x AND pk > :n and pk BETWEEN :n AND :m answer
the type sentence, and pk > :x AND sk > :n answers "Query key condition not
supported". With no clause on the HASH attribute no value is checked:
sk > :n answers "Query condition missed key schema element: pk", and on an
index with HASH gsi1_pk and RANGE SK, PK > :n (PK the table's HASH
attribute) and SK > :n answer "Query condition missed key schema element:
gsi1_pk".

Ordering, measured: unused values, filter syntax, projection syntax, the
Select conflicts and undefined key references are reported before this
refusal; an ExclusiveStartKey fault and an oversized key value after it.
An unused value and an invalid FilterExpression are also reported before
the type sentence for pk > :n (measured again on 2026-10-31).

The refusal is in crates/core/src/expression/key_condition/no_hash_equality.rs,
with KeyCondition::lacks_hash_equality, refuse_two_conditions_on_one_attribute,
operands_naming and refuse_without_hash_equality, and
KeyCondition::validate_references is in key_condition/references.rs. The
parser now records one or two clauses with no equality instead of refusing
them, so the engine can choose the sentence.

handle_query skips the classification from #429 for a key condition with no
equality clause, and on a single HASH attribute schema for an equality on
another attribute paired with a non-equality on the HASH attribute
(sk = :x AND pk > :y). Every other key condition goes through that
classification as before. After validate_select_projection, handle_query
calls the engine's refuse_without_hash_equality. It checks the references
of every key condition and refuses the ones the classification skipped. It
refuses two conditions on one attribute first. Then, on a single HASH
attribute schema and only when a clause names the HASH attribute, it runs
the type check and the begins_with check from #429 on that clause, against
that attribute's definition. Then it refuses with the key schema's wording.
On a multi-attribute key schema no value is checked, because the service
answers h > :n with the HASH sentence.

LeadingKeys keeps the binding from #511.
query_kce_without_a_partition_key_equality_binds_only_a_partition_operand
asserts the values it binds for the shapes the parser now records, and
the_engine_still_refuses_every_shape_whose_operand_is_now_bound asserts that
the core refusal answers "Query key condition not supported" for each shape
it binds.

Tests: unit tests in no_hash_equality/tests.rs, references.rs and
crates/engine/src/query/no_hash_equality_tests.rs. The wire file
tests/python/test_query_lone_non_equality.py has 81 rows. 67 of them passed
against the service as a file; the other 14 repeat requests measured on
2026-10-23 (427-8c, row 6, and rows 5a and 5b with the N value) and on
2026-11-01 (the ten rows of TestValueTypes, two of them on the file's
single-idx in place of the measured index). All 81 pass on SQLite and
PostgreSQL 16 builds of this commit, and a SQLite build of main at f49c5f8
fails 74 of them.

Related behaviour, measured: "<>", NOT, OR, IN and contains in
a key condition get "Invalid operator used in KeyConditionExpression" on the
service; pk = :x AND z > :x gets "missed key schema element: sk" on the
service and 200 here; the Select ALL_PROJECTED_ATTRIBUTES text lacks the
"1 validation error detected: " prefix here. A key condition with an
equality clause and a HASH attribute without one (sk = :x on a table,
g1 = :x on an index with HASH g1, g2) is refused by the key schema checks
handle_query runs before it parses the FilterExpression. The service
reports an unused value or an invalid FilterExpression first (measured
2026-10-31).
LeeroyHannigan added a commit that referenced this pull request Nov 1, 2026
…service does

Closes #427.

A Query whose KeyConditionExpression has no equality clause on the HASH
attribute was refused with a parser sentence of ExtendDB's own. The service
chooses the sentence from the key schema. Measured on 2026-10-23, every row
repeated with identical answers:

- Single HASH attribute, any clause names it (so the clause on it is a
  non-equality): "Query key condition not supported". Rows: pk > :x,
  pk BETWEEN :x AND :y, begins_with(pk, :x), pk > :x AND sk = :y,
  sk = :x AND pk > :y, zz = :x AND pk > :y, and the GSI forms.
- Single HASH attribute, no clause names it: "Query condition missed key
  schema element: <HASH>". Rows: sk > :x, zz > :x, sk > :x AND zz > :y,
  zz = :x AND yy = :y, and the GSI forms naming the index HASH attribute.
- Several key attributes (two HASH attributes, or one HASH with several
  RANGE attributes): "HASH key attributes h1, h2 must have equality
  conditions specified in the query", naming every HASH attribute, for
  every operator and for an N value on the HASH attribute.
- Two conditions on one attribute: "Invalid KeyConditionExpression:
  KeyConditionExpressions must only contain one condition per key".
- An undefined #name or :value in the key condition is refused first, with
  the "Invalid KeyConditionExpression: " prefix. The rows include pk = :x
  with no values.
- Single HASH attribute, a value of the wrong type: pk > :n with an N value
  on an S key answers "One or more parameter values were invalid: Condition
  parameter type does not match schema type", and begins_with(pk, :n) on an
  N key answers "Invalid KeyConditionExpression: Incorrect operand type for
  operator or function; operator or function: begins_with, operand type: N".
- Legacy KeyConditions is desugared with every reference defined and an
  equality clause, or refused there; no change.

Measured on 2026-11-01, two samples each, on a single HASH attribute
schema: two conditions on one attribute answer the one condition per key
sentence whatever their value types (pk > :x AND pk < :n). A wrong-typed
value is reported only in the clause on the HASH attribute:
pk > :n AND sk > :y, sk = :x AND pk > :n and pk BETWEEN :n AND :m answer
the type sentence, and pk > :x AND sk > :n answers "Query key condition not
supported". With no clause on the HASH attribute no value is checked:
sk > :n answers "Query condition missed key schema element: pk", and on an
index with HASH gsi1_pk and RANGE SK, PK > :n (PK the table's HASH
attribute) and SK > :n answer "Query condition missed key schema element:
gsi1_pk". On a table with HASH pk (N) and RANGE sk (S),
begins_with(pk, :n) AND sk > :x and sk > :x AND begins_with(pk, :n) answer
the begins_with operand type sentence, as begins_with(pk, :n) alone does.

Ordering, measured: unused values, filter syntax, projection syntax, the
Select conflicts and undefined key references are reported before this
refusal; an ExclusiveStartKey fault and an oversized key value after it.
An unused value and an invalid FilterExpression are also reported before
the type sentence for pk > :n (measured again on 2026-10-31).

The refusal is in crates/core/src/expression/key_condition/no_hash_equality.rs,
with KeyCondition::lacks_hash_equality, refuse_two_conditions_on_one_attribute,
operands_naming and refuse_without_hash_equality, and
KeyCondition::validate_references is in key_condition/references.rs. The
parser now records one or two clauses with no equality instead of refusing
them, so the engine can choose the sentence. When only the second of two
such clauses is a begins_with, the parser keeps that clause whole as the
sort key condition, which the begins_with check reads.

handle_query skips the classification from #429 for a key condition with no
equality clause, and on a single HASH attribute schema for an equality on
another attribute paired with a non-equality on the HASH attribute
(sk = :x AND pk > :y). Every other key condition goes through that
classification as before. After validate_select_projection, handle_query
calls the engine's refuse_without_hash_equality. It checks the references
of every key condition and refuses the ones the classification skipped. It
refuses two conditions on one attribute first. Then, on a single HASH
attribute schema and only when a clause names the HASH attribute, it runs
the type check and the begins_with check from #429 on that clause, against
that attribute's definition. Then it refuses with the key schema's wording.
On a multi-attribute key schema no value is checked, because the service
answers h > :n with the HASH sentence.

LeadingKeys keeps the binding from #511.
query_kce_without_a_partition_key_equality_binds_only_a_partition_operand
asserts the values it binds for the shapes the parser now records, and
the_engine_still_refuses_every_shape_whose_operand_is_now_bound asserts that
the core refusal answers "Query key condition not supported" for each shape
it binds.

Tests: unit tests in no_hash_equality/tests.rs, references.rs and
crates/engine/src/query/no_hash_equality_tests.rs. The wire file
tests/python/test_query_lone_non_equality.py has 83 rows. 67 of them passed
against the service as a file; the other 16 repeat requests measured on
2026-10-23 (427-8c, row 6, and rows 5a and 5b with the N value) and on
2026-11-01 (the ten rows of TestValueTypes, two of them on the file's
single-idx in place of the measured index, and the two begins_with rows on
a table with HASH pk (N) and RANGE sk). All 83 pass on SQLite and
PostgreSQL 16 builds of this commit, and a SQLite build of main at f49c5f8
fails 76 of them.

Related behaviour, measured: "<>", NOT, OR, IN and contains in
a key condition get "Invalid operator used in KeyConditionExpression" on the
service; pk = :x AND z > :x gets "missed key schema element: sk" on the
service and 200 here; the Select ALL_PROJECTED_ATTRIBUTES text lacks the
"1 validation error detected: " prefix here. A key condition with an
equality clause and a HASH attribute without one (sk = :x on a table,
g1 = :x on an index with HASH g1, g2) is refused by the key schema checks
handle_query runs before it parses the FilterExpression. The service
reports an unused value or an invalid FilterExpression first (measured
2026-10-31).
LeeroyHannigan added a commit that referenced this pull request Nov 1, 2026
…Lite

DynamoDB returns a Query on a local secondary index ordered by the index
sort key, with the items that share an index sort key value in one
deterministic order, and a reverse Query as the exact mirror of the forward
one (measured 2026-10-21; the order inside such a group differs from
ExtendDB's byte order and is tracked in #425). ExtendDB orders an LSI
partition by the index sort key, then the base table sort key, and pages
through it with a cursor over the same columns.

Every index table whose index has a sort key has an ordering index on
(pk, sk, base_pk, base_sk) on the PostgreSQL and SQLite backends, with one
sk column per RANGE attribute. A GSI Query orders by its RANGE columns in
key-schema order, then base_pk and base_sk, which is that index without the
constant pk, so both databases walk the index and stop at the page limit.
An LSI Query ordered by (sk, base_sk) and its cursor compared the same two
columns. Neither planner can tell that base_pk is constant inside an LSI
partition, so the index served the index sort key only. PostgreSQL planned
an Incremental Sort over the index scan when the key condition left several
index sort key values and a Sort when an equality left one; SQLite used a
temporary B-tree for the last term of the ORDER BY, and seeked a resumed
page on the index sort key alone. On an LSI partition of 50,000 items with
50 items per index sort key value, a PostgreSQL page with Limit 100 read
151 rows and 154 buffers to return 101, and a page resumed inside a group
read 130 rows and 133 buffers.

The LSI ORDER BY and cursor now list base_pk between the index sort key
and the base sort key, the same columns a GSI with one RANGE attribute
uses, so the ORDER BY is the ordering index without pk. Every row of an LSI
partition stores the queried partition key as base_pk. The cursor binds the
queried partition key for it, not the start key's partition key, so base_pk
compares equal on every row and the base sort key orders the rows as
before. The rows, their order, the page boundaries and the LastEvaluatedKey
and ExclusiveStartKey shapes do not change. On SQLite the statement builder
moves out of query_impl into query_statement so the plan tests can explain
the statement a Query sends.

Measured on servers built from this branch and from main, on the same
52,000 items: the LSI pages plan as an Index Scan or Index Scan Backward on
the ordering index with the cursor in the Index Cond and no sort node, in
both directions, in the custom and the generic plan, reading 101 rows and
103 to 105 buffers. SQLite plans SEARCH USING INDEX idx_order_* with no
temporary B-tree and seeks a resumed page on (sk_s, base_pk, base_sk_s).
The GSI plans and buffer counts are unchanged. The items and
LastEvaluatedKey of every measured page are identical before and after on
both backends.

crates/storage-postgres/tests/lsi_query_plan.rs reads the statement the
engine sent from pg_stat_activity and asserts that its generic and custom
plans have no Sort or Incremental Sort node and no Filter under the index
scan, for a first page and a resumed page with the partition alone, with
lsk = :l, and with lsk BETWEEN, in both directions. It also checks the page
rows and that a start key naming another partition returns the same page.
It skips below PostgreSQL 16, which added EXPLAIN (GENERIC_PLAN). CI runs
it in the PostgreSQL storage-level step. The SQLite plan tests
(crates/storage-sqlite/src/data/query_scan/plan_tests.rs) assert no
temporary B-tree for the same LSI shapes and for GSI pages, and page
through an LSI in both directions. The cursor unit tests on both backends
assert the new LSI fragment and bind.

A GSI with several RANGE attributes orders by every RANGE column (#429).
crates/storage-postgres/tests/lsi_query_plan/multi_range_gsi.rs, a module of
the lsi_query_plan test, and a fourth SQLite plan_tests case run such a GSI
with RANGE attributes a, b and c for the partition alone, an equality on a,
an equality on a with b BETWEEN, and equalities on all three, first and
resumed pages in both directions, and assert the same index walk; both
also check the rows of the pages. Their plan checks pass on main. With the
ORDER BY cut to the first RANGE column, the SQLite case sorts in a
temporary B-tree and the PostgreSQL case returns the first page out of
order. With a condition applied to the first RANGE column instead of the
one it names, the SQLite case returns no rows for a = :a AND b BETWEEN.

With base_pk removed from the LSI ORDER BY, the PostgreSQL plan test and
the SQLite LSI plan test fail on the sort node; the SQLite GSI plan test
and paging test pass, as the rows do not change. With base_pk removed from
the LSI cursor comparison, the PostgreSQL plan test fails on the Filter
under the index scan and the SQLite cursor unit tests fail on the
fragment; the paging tests pass. With the start key's partition key bound
instead of the queried one, the PostgreSQL other-partition page check and
the SQLite bind test fail. tests/test_query_scan.py and
tests/test_multipart_gsi.py pass on both backends.
docs/design/04-component-storage.md describes the LSI cursor and ORDER BY
and the sort step they avoid.

Closes #366
@navareamol navareamol added the v1 Needed for the 1.0 release label Nov 3, 2026
@navareamol navareamol added this to the 1.0 milestone Nov 3, 2026
LeeroyHannigan added a commit that referenced this pull request Nov 5, 2026
crates/storage-cassandra/src/data/query.rs: main carries the
string_upper_bound helper from the start key change (#483), which
appends U+10FFFF to a begins_with prefix. This branch removes the helper
because the bound is now the next prefix from
extenddb_storage::util::string_prefix_upper_bound. The merged file has
no string_upper_bound; nothing else in the tree calls it.

crates/storage-cassandra/src/data/sk_range.rs: main added this file
with #483, using string_upper_bound for the begins_with upper bound and
pinning that bound in two tests. This branch rewrote the same places to
use string_prefix_upper_bound, with no bound for a prefix of only
U+10FFFF, and added the test that checks the range against the keys
measured on the service. The merged file keeps this branch's version of
every conflicting region; main's structure outside them is unchanged.

crates/storage-postgres/src/data/query_scan.rs: main (#429) selects the
sort key column with sk_column_n(pos, sk_type) from the RANGE attribute
the condition names and keeps the bound type in sk_cond_type. This
branch passes the expression maps to build_sk_sql and propagates its
Result. The merged call is build_sk_sql(sk_cond, &sk_column_n(pos,
sk_type), maps, &mut param_idx)? with main's surrounding code.
LeeroyHannigan added a commit that referenced this pull request Nov 5, 2026
Since #429, the MongoDB and Cassandra backends refuse a key condition on
a later RANGE attribute of a multi-attribute index with a
ValidationException. Two rows of TestGsiQueryKeySize expect such a Query
to be served, and they failed on MongoDB. They now skip when a probe
gets that refusal, as the multi-range tests on main do. The refusal rows
still run on those backends, because the size check answers first.
Dodothereal pushed a commit to Dodothereal/extenddb that referenced this pull request Nov 6, 2026
… reach (ExtendDB#483)

* fix(query): refuse a Query ExclusiveStartKey the key condition cannot reach

Closes ExtendDB#440.

A Query ExclusiveStartKey from another partition, or outside the sort key
condition, was accepted and answered an empty page. The service refuses
it, with a sentence chosen by where the key falls. Measured on 2026-10-23
and 2026-10-24, every row repeated with identical answers, page-end rows
ten times each.

After the shape check, the service first asks whether a later key in the
scan direction can still satisfy the sort key condition, for either
partition:

- On a base table a later key must differ from the start key's sort
  value: ">" and "<" at the bound are refused, ">=" at the bound is
  accepted, "<=" at the bound refused, BETWEEN at the upper bound refused
  and at the lower bound accepted, begins_with with a key that does not
  carry the prefix refused; the reverse direction mirrors each.
- On an LSI or GSI a repeat of the start key's sort value counts as a
  later key, because index keys repeat: "<=", BETWEEN at either bound,
  ">=" in reverse, begins_with in reverse at the prefix and "=" with the
  key itself are all accepted; ">" and "<" at the bound are refused.
- The sentence is "The provided starting key does not match the range
  key predicate", with two base-table exceptions in the same partition:
  "=" with the key's own value: "The provided exclusive start key is
  invalid"; begins_with in reverse with the key exactly the prefix: "The
  provided starting key is outside query boundaries based on provided
  conditions".

Then the partition, when the key's partition differs from the condition's
(table, LSI, GSI, legacy KeyConditions, either direction):

- no sort key condition: "The provided starting key is outside query
  boundaries based on provided conditions";
- any sort key condition: "The query can return at most one row and
  cannot be restarted".

A hash-only base table refuses every ExclusiveStartKey with "The provided
exclusive start key is invalid", the queried partition included, and its
pages never carry a key. Partition values compare by value for numbers
(1, 1.0, 1e0, 01, +1 are equal); strings by UTF-8 byte order; binary by
byte order.

Page end: when a base table page ends on the last key that can satisfy
the sort key condition in the scan direction, the service returns no
LastEvaluatedKey (ten of ten for "=", BETWEEN at the upper bound, "<=" at
the bound, reverse ">=" at the bound). ExtendDB now drops the key there,
so a client that feeds every returned key back is never refused. Index
pages are unchanged.

Ordering, measured: filter and projection faults, unused names and
values, ConsistentRead on a GSI, Limit, a missing table or index, the
key size check and the start key shape check (missing or extra
attributes, wrong types) are reported first; the Select checks after.

The checks live in crates/engine/src/start_key.rs, called from
handle_query after the shape check. The sort key predicate is evaluated
with the expression evaluator on the start key's sort value, so every
operator and type follows the same comparison as the condition itself.

Tests: engine unit tests in start_key_tests.rs and start_key_range_tests.rs;
tests/python/test_query_start_key_partition.py, test_query_start_key_range.py
and test_query_start_key_index.py (162 rows, the hash-only page row
ExtendDB only) pass against the service and on SQLite and PostgreSQL, with
test_read_paging.py and the Query wire files. Pagination walks with Limit
1 to 3 in both directions feed every returned key back without a refusal.

Pre-existing, measured, not changed here: a sort key bound of another
type than the sort key answers InternalServerError (the type check in
ExtendDB#429); the service omits the trailing key when the next row exists but
fails the condition ("sk < z" with Limit equal to the matches), which
needs a storage look-ahead and is filed separately.

* fix(cassandra): pass the bare index name in IndexNotFound so the Query sentence matches the other backends

(cherry picked from commit 0294106)

* fix(cassandra): fold a Query start key into the key condition's sort key bound

A Query with a sort key condition and an ExclusiveStartKey on the same
partition produced two restrictions on the same side of the clustering
column (`sk_s >= ? AND sk_s > ?`), which Cassandra refuses with "More than
one restriction was found for the start bound on sk_s" (end bound in
reverse; "cannot be restricted by both an equality and an inequality
relation" on the index same-sort-value sub-query). The server answered
InternalServerError. The defect exists on main for every such request.

The Cassandra Query path now builds the sort key range as at most one lower
and one upper bound (SkRange), replaces the bound on the near side of the
scan direction with a strict bound at the start key when the start key is
at or past it, and renders the range once per CQL statement. The index
two-query path runs its same-sort-value sub-query only when the start key's
sort value lies inside the condition's range, and renders the merged range
for the advance sub-query. Binds follow the rendered clauses in order.

Unit tests pin the merge for a lower bound, a bound equal to the start key,
a start key short of the bound, BETWEEN in both directions, equality,
begins_with in reverse, strict and inclusive containment, and numeric
ordering. The three Query start key wire files pass on Cassandra (162
rows), as do test_query_scan, test_composite_keys, test_gsi,
test_scan_edge_cases and the storage direct_integration suite.

* test(cassandra): pin the sort key range each key condition operator produces

Equality renders as one clause, BETWEEN as two inclusive bounds, and
begins_with as an inclusive prefix with an exclusive upper bound: the
prefix plus U+10FFFF for strings, the incremented last byte below 0xFF
for binary, and no upper bound for an all-0xFF prefix.
LeeroyHannigan added a commit that referenced this pull request Nov 6, 2026
Main changes resolve_multipart to take the HASH and the RANGE attribute
names (#429). The multi-attribute HASH test now gives r as the RANGE
attribute, as its attribute definitions do.
LeeroyHannigan added a commit that referenced this pull request Nov 20, 2026
…x Scan cursor

Section 7 of docs/design/04-component-storage.md now names the index
that serves each cursor shape and the tables it holds on. The no-sort
statement applies to tables created with the collated key columns. The
Scan on an index with more than one RANGE attribute still sorts. On
older PostgreSQL tables the indexes do not serve a COLLATE "C"
predicate. The statements put COLLATE "C" on base_pk and on every
string sort key column. Where the first cursor column other than pk is
one of these, PostgreSQL reads the rows through the pk prefix of the
key index. It sorts them on every page (technical debt C-11). A
hash-only index has no ordering index, so its page comes from the
primary key or from the base-key index.

The LSI paragraph now says that the database applies the cursor while
it reads the index. It then sorts the rows that share an index sort key
value and applies the LIMIT. EXPLAIN (ANALYZE) on PostgreSQL 16.15
shows the row comparison in the Index Cond under an Incremental Sort
with Presorted Key sk_s. EXPLAIN QUERY PLAN on SQLite shows SEARCH
(pk=? AND sk_s>?) and then a temporary B-tree for the last ORDER BY
term.

The section gains three blocks. The cursor of a GSI with more than one
RANGE attribute, which #429 added to main. The index Scan cursor
(pk, sk, base_pk, base_sk) with its ORDER BY. The hash-only base table
cases: the Scan cursor is pk > $last_pk, and a Query with an
ExclusiveStartKey returns no items without a statement. The intro names
the PostgreSQL and SQLite backends, because MongoDB and Cassandra do not
translate the cursor to SQL.

Each plan statement comes from EXPLAIN on tables the server created and
on copies whose key columns keep the database collation. The SQLite
plans come from EXPLAIN QUERY PLAN on the database the server created.
LeeroyHannigan added a commit that referenced this pull request Nov 23, 2026
…comment on ExtendDB's check

The comment on test_key_condition_count_precedes_the_key_grammar said ExtendDB has no one-condition-per-key check. The check exists since the rebase on #429, for the key attributes. The rows the comment cited are now tests, measured 2026-11-23 in us-east-1, twice each, with the same answers:

- a60: `pk = :v AND` 150 `#v = :v` joined by AND answers `Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301`, on the service and on ExtendDB. The count comes ahead of the one-condition-per-key check on both.
- b05: the same shape with 10 terms answers `Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key` on the service, before the table lookup. ExtendDB serves it with no items. It accepts a key condition clause on an attribute outside the key schema, and its check covers the key attributes only. The row is marked as an expected failure on ExtendDB, strict, so it fails when the clause is refused.

The module docstring adds the measurement date.
amrith pushed a commit to amrith/extenddb that referenced this pull request Nov 24, 2026
…Lite (ExtendDB#432)

* fix(storage): plan an LSI query as an index walk on PostgreSQL and SQLite

DynamoDB returns a Query on a local secondary index ordered by the index
sort key, with the items that share an index sort key value in one
deterministic order, and a reverse Query as the exact mirror of the forward
one (measured 2026-10-21; the order inside such a group differs from
ExtendDB's byte order and is tracked in ExtendDB#425). ExtendDB orders an LSI
partition by the index sort key, then the base table sort key, and pages
through it with a cursor over the same columns.

Every index table whose index has a sort key has an ordering index on
(pk, sk, base_pk, base_sk) on the PostgreSQL and SQLite backends, with one
sk column per RANGE attribute. A GSI Query orders by its RANGE columns in
key-schema order, then base_pk and base_sk, which is that index without the
constant pk, so both databases walk the index and stop at the page limit.
An LSI Query ordered by (sk, base_sk) and its cursor compared the same two
columns. Neither planner can tell that base_pk is constant inside an LSI
partition, so the index served the index sort key only. PostgreSQL planned
an Incremental Sort over the index scan when the key condition left several
index sort key values and a Sort when an equality left one; SQLite used a
temporary B-tree for the last term of the ORDER BY, and seeked a resumed
page on the index sort key alone. On an LSI partition of 50,000 items with
50 items per index sort key value, a PostgreSQL page with Limit 100 read
151 rows and 154 buffers to return 101, and a page resumed inside a group
read 130 rows and 133 buffers.

The LSI ORDER BY and cursor now list base_pk between the index sort key
and the base sort key, the same columns a GSI with one RANGE attribute
uses, so the ORDER BY is the ordering index without pk. Every row of an LSI
partition stores the queried partition key as base_pk. The cursor binds the
queried partition key for it, not the start key's partition key, so base_pk
compares equal on every row and the base sort key orders the rows as
before. The rows, their order, the page boundaries and the LastEvaluatedKey
and ExclusiveStartKey shapes do not change. On SQLite the statement builder
moves out of query_impl into query_statement so the plan tests can explain
the statement a Query sends.

Measured on servers built from this branch and from main, on the same
52,000 items: the LSI pages plan as an Index Scan or Index Scan Backward on
the ordering index with the cursor in the Index Cond and no sort node, in
both directions, in the custom and the generic plan, reading 101 rows and
103 to 105 buffers. SQLite plans SEARCH USING INDEX idx_order_* with no
temporary B-tree and seeks a resumed page on (sk_s, base_pk, base_sk_s).
The GSI plans and buffer counts are unchanged. The items and
LastEvaluatedKey of every measured page are identical before and after on
both backends.

crates/storage-postgres/tests/lsi_query_plan.rs reads the statement the
engine sent from pg_stat_activity and asserts that its generic and custom
plans have no Sort or Incremental Sort node and no Filter under the index
scan, for a first page and a resumed page with the partition alone, with
lsk = :l, and with lsk BETWEEN, in both directions. It also checks the page
rows and that a start key naming another partition returns the same page.
It skips below PostgreSQL 16, which added EXPLAIN (GENERIC_PLAN). CI runs
it in the PostgreSQL storage-level step. The SQLite plan tests
(crates/storage-sqlite/src/data/query_scan/plan_tests.rs) assert no
temporary B-tree for the same LSI shapes and for GSI pages, and page
through an LSI in both directions. The cursor unit tests on both backends
assert the new LSI fragment and bind.

A GSI with several RANGE attributes orders by every RANGE column (ExtendDB#429).
crates/storage-postgres/tests/lsi_query_plan/multi_range_gsi.rs, a module of
the lsi_query_plan test, and a fourth SQLite plan_tests case run such a GSI
with RANGE attributes a, b and c for the partition alone, an equality on a,
an equality on a with b BETWEEN, and equalities on all three, first and
resumed pages in both directions, and assert the same index walk; both
also check the rows of the pages. Their plan checks pass on main. With the
ORDER BY cut to the first RANGE column, the SQLite case sorts in a
temporary B-tree and the PostgreSQL case returns the first page out of
order. With a condition applied to the first RANGE column instead of the
one it names, the SQLite case returns no rows for a = :a AND b BETWEEN.

With base_pk removed from the LSI ORDER BY, the PostgreSQL plan test and
the SQLite LSI plan test fail on the sort node; the SQLite GSI plan test
and paging test pass, as the rows do not change. With base_pk removed from
the LSI cursor comparison, the PostgreSQL plan test fails on the Filter
under the index scan and the SQLite cursor unit tests fail on the
fragment; the paging tests pass. With the start key's partition key bound
instead of the queried one, the PostgreSQL other-partition page check and
the SQLite bind test fail. tests/test_query_scan.py and
tests/test_multipart_gsi.py pass on both backends.
docs/design/04-component-storage.md describes the LSI cursor and ORDER BY
and the sort step they avoid.

Closes ExtendDB#366

* test(storage-postgres): upsert the control-plane delay setting

Main's migrations no longer seed the control_plane_delay_seconds row in
settings, so the UPDATE that set it to zero in these tests changed no
row. The engine kept its default delay, CreateTable left the table
CREATING, and table_key_info then returned TableNotFound. The tests now
insert the row or update it, as main's own tests do.

* test(storage-sqlite): add the license header to plan_tests.rs

The other files this change adds start with the copyright line and the
SPDX license identifier. plan_tests.rs had neither.

* docs(design): state the direction of the LSI cursor

The LSI paragraph said the cursor runs in the same order and direction as
the GSI cursor above it. The reverse GSI paragraph above describes an
expanded OR form with the base key ascending. The code emits one row
comparison, with every column in the direction of ScanIndexForward. The
LSI paragraph now states that rule itself: `>` and ASC forward, `<` and
DESC in reverse. Its long sentences are split, with no change to what
they say.

* refactor(storage): bind the start key's partition key in an LSI cursor

The LSI cursor bound the queried partition key as base_pk, so that a start
key from another partition resumed inside the queried one. No request
reaches storage with such a key: handle_query runs
validate_query_start_key_bounds before the read, and it refuses the key
with a ValidationException. Measured on DynamoDB on 2026-11-20, twice per
shape, the service answers the same way:

- the partition alone, either direction: "The provided starting key is
  outside query boundaries based on provided conditions".
- lsk = :l or lsk BETWEEN: "The query can return at most one row and
  cannot be restarted".

Both backends now bind the start key's base partition key for every
index, as a GSI does. On an LSI that is the queried partition key. The
change removes is_lsi from the PostgreSQL query_impl, from the SQLite
query_statement and from append_query_pagination. It also removes the
partition key argument of append_query_pagination and the SQLite bind
test for a start key from another partition. The PostgreSQL plan test no
longer checks such a key.

* test(storage-postgres): honour EXTENDDB_TEST_PG_REQUIRED in the plan tests

The two plan tests reported a skip and passed with
EXTENDDB_TEST_PG_REQUIRED set, both with no connection string and on a
server older than PostgreSQL 16. Both cases now fail under that variable,
as in gsi_stale_writer.rs. One helper, which both tests call, holds the
two checks.

A failing test kept its scratch database on the server. A guard now drops
the database when the test ends, a failed assertion included.

A resumed page's plan must now hold the cursor as one index condition over
the ORDER BY columns. A cursor without base_pk is still an index
condition, ROW(sk_s, base_sk_s), so the plan checks passed on it. The test
failed only because the custom plan got four values for a statement with
three parameters. With 20,000 items that share one lsk value, that cursor
read 180 buffers for a page near the end of the group. The cursor over
(sk_s, base_pk, base_sk_s) read 4. The LSI and multi-RANGE tests now share
one assert_index_walk.

* test(storage-postgres): move the plan tests' scratch database into a module

lsi_query_plan.rs grew to 677 lines with the database guard and the
EXTENDDB_TEST_PG_REQUIRED checks. The scratch database code (Scratch, its
guard, the connection string and version checks, and the migrations) moves
unchanged to lsi_query_plan/scratch.rs. Only the visibility of Scratch, its
fields and scratch_or_skip changes, so that the test files can use them.
lsi_query_plan.rs is now 500 lines.

* test(storage): bound the LSI page walk and drop a repeated REQUIRED check

The SQLite walk over LSI pages had no page limit, so a cursor that
repeats a page kept the test running until the job's timeout. It now
fails when the walk needs more pages than there are items. With the
base_pk bind emptied, the test fails in place of hanging.

base_conn asserted EXTENDDB_TEST_PG_REQUIRED before it returned None.
Its one caller then calls skip, which asserts the same setting with the
test's name, so base_conn now returns None only. The comment above the
PostgreSQL index cursor binds points to the PaginationBinds::BasePkAndSk
doc in place of a copy of it.
rlunar pushed a commit to rlunar/extenddb that referenced this pull request Nov 25, 2026
…e emits (ExtendDB#428)

* docs(design): describe the query cursor as the row comparison the code emits

The reverse GSI cursor example in docs/design/04-component-storage.md showed an expanded OR with an ascending base-key tiebreaker under a descending sort key. The PostgreSQL and SQLite query builders emit one row comparison for every cursor shape, with every column, tiebreaker included, following ScanIndexForward, so a reverse page is the exact mirror of the forward one as it is on the service. The base table Scan examples in the same section showed an OR form too; the Scan cursor is the row comparison (pk, sk) > ($pk, $sk) and Scan has no reverse direction.

Section 7 states the rule (cursor columns equal the ORDER BY columns, same order, same direction, > forward and < reverse, a plain comparison when the cursor has one column), shows the Scan, base table Query, forward GSI and reverse GSI statements with their ORDER BY, and describes the LSI shape (index sort key then base sort key, which the ordering index does not serve without a sort step because it carries base_pk between them), the hash-only index shape, and the forms on a base table without a sort key. The section 5.1 sentence on collation now limits the one-seek claim to GSI cursors.

Closes ExtendDB#370

* docs(design): qualify the cursor plans by collation and show the index Scan cursor

Section 7 of docs/design/04-component-storage.md now names the index
that serves each cursor shape and the tables it holds on. The no-sort
statement applies to tables created with the collated key columns. The
Scan on an index with more than one RANGE attribute still sorts. On
older PostgreSQL tables the indexes do not serve a COLLATE "C"
predicate. The statements put COLLATE "C" on base_pk and on every
string sort key column. Where the first cursor column other than pk is
one of these, PostgreSQL reads the rows through the pk prefix of the
key index. It sorts them on every page (technical debt C-11). A
hash-only index has no ordering index, so its page comes from the
primary key or from the base-key index.

The LSI paragraph now says that the database applies the cursor while
it reads the index. It then sorts the rows that share an index sort key
value and applies the LIMIT. EXPLAIN (ANALYZE) on PostgreSQL 16.15
shows the row comparison in the Index Cond under an Incremental Sort
with Presorted Key sk_s. EXPLAIN QUERY PLAN on SQLite shows SEARCH
(pk=? AND sk_s>?) and then a temporary B-tree for the last ORDER BY
term.

The section gains three blocks. The cursor of a GSI with more than one
RANGE attribute, which ExtendDB#429 added to main. The index Scan cursor
(pk, sk, base_pk, base_sk) with its ORDER BY. The hash-only base table
cases: the Scan cursor is pk > $last_pk, and a Query with an
ExclusiveStartKey returns no items without a statement. The intro names
the PostgreSQL and SQLite backends, because MongoDB and Cassandra do not
translate the cursor to SQL.

Each plan statement comes from EXPLAIN on tables the server created and
on copies whose key columns keep the database collation. The SQLite
plans come from EXPLAIN QUERY PLAN on the database the server created.

* docs(storage-sqlite): describe the pagination cursor as the row comparison the code emits

The README listed OR-expansion for pagination as a difference from the
PostgreSQL backend, because SQLite lacked row-value comparison. The
SQLite builder emits the same row comparison as PostgreSQL, with ?
placeholders and no COLLATE, in scan_impl and append_query_pagination of
crates/storage-sqlite/src/data/query_scan.rs. The line now says so.

* docs(design): limit the cursor plan statements to the statements shown

Section 7 said the primary key serves "the Scan", which covered index
Scans. The ordering index serves a GSI or LSI Scan. It now says the base
table Scan and Query. The plan statements hold for the statements shown,
which carry no sort key condition. A paragraph after the intro says what
PostgreSQL and SQLite plan with one. PostgreSQL planned a Sort on every
page with an equality on the index sort key, and SQLite seeks on the
condition's terms. The legacy-table text gains the case where a later
cursor column carries the collation (an Incremental Sort). The reverse
GSI paragraph states the rule for the tiebreaker in place of the history
of a fixed defect.

Section 5.1 named four collated columns and said the ordering index
serves every GSI cursor in one seek. A hash-only GSI has no ordering
index, and the numbered sort key columns carry the collation too. The
sentence now names the text key columns and both indexes.

* docs(design): say that a Query resuming on a table without a sort key is refused

Section 7 said that a Query with an ExclusiveStartKey on a table without a
sort key returns no items and runs no statement. The engine refuses it
before storage: start_key.rs answers ValidationException with The provided
exclusive start key is invalid. The sentence now says so.

* docs(design): describe the LSI cursor main has since ExtendDB#432

ExtendDB#432 added base_pk to the LSI Query cursor and to its ORDER BY on
PostgreSQL and SQLite. Three passages of this branch still described
the cursor without it.

- Section 5.1 names the LSI Query cursor beside the GSI one. Section 7
  keeps the Scan cases.
- The section 7 introduction says that a key index serves every shape
  below, and that for a GSI or LSI it is the ordering index.
- The plan paragraph gives the LSI plans of the plan test that ExtendDB#432
  added. Both plans of each page with an equality are an Index Scan at
  Limit 10. At Limit 101 the custom plan of the first page is a Sort
  over a Bitmap Heap Scan.
rlunar pushed a commit to rlunar/extenddb that referenced this pull request Nov 25, 2026
…rules (ExtendDB#544)

* fix(query): check Query values against the key schema and the number rules

A Query with a KeyConditionExpression did not check a key condition value's
type against the key attribute's AttributeDefinitions type, and did not check
that an N value in ExpressionAttributeValues is a number. The storage layer
compared the value's inner text with the stored key and ignored the type tag,
so {"N": "bob"} on an S partition key read the bob partition while
authorization bound no dynamodb:LeadingKeys value to it, and a sort key value
of another type answered InternalServerError on SQLite.

Add the two checks the service applies before it reads a row, on the
expression path (crates/engine/src/query_key_values.rs):

- an N value in ExpressionAttributeValues that is not a number answers
  "The parameter cannot be converted to a numeric value: <value>" (the
  overflow and 38-digit texts for those cases; an empty value answers the
  message with the colon). The check covers the whole map, including NS
  members and values nested in L and M, whether the key condition, the
  filter or nothing reads them, with the walk PutItem and UpdateItem already
  use. It runs at request time after the Limit and expression parameter mix
  checks and before the table lookup, which moves those two checks ahead of
  the table lookup as well. The server runs the same request-time checks
  ahead of the IAM decision, so a principal under any LeadingKeys fence form
  gets ValidationException and no items;
- a key condition value whose type is not the key attribute's type answers
  "One or more parameter values were invalid: Condition parameter type does
  not match schema type", for the partition key, the sort key under every
  comparison operator, both BETWEEN bounds, the begins_with prefix and
  multi-attribute index keys, after the key schema, filter, projection,
  unused value and Select checks and before the ExclusiveStartKey check. When
  a compared placeholder is undefined the check returns without a verdict and
  the undefined placeholder is reported.

Measured on the service on 2026-10-24 (113 requests, each sent twice). The
legacy KeyConditions path is unchanged; its checks land with ExtendDB#507. Scan is
unchanged. Unit tests at the checks and a dual-target wire test file,
tests/test_query_key_value_types.py, which fails on main.

* fix(query): run the request-time checks on the raw body, enums in the service's order

The server ran its pre-IAM checks only when the body deserialized as
QueryInput, and the engine checked the ReturnConsumedCapacity and Select
enums before them, so a Query carrying an invalid Select and an N value
that is not a number answered the Select message, or AccessDeniedException
for a principal whose LeadingKeys fence needs a value. The checks now read
the raw body in the service's order, measured 2026-10-24: Limit, the
expression and non-expression parameter mix, ReturnConsumedCapacity, every
number in ExpressionAttributeValues, then Select. The engine and the server
run the same function.

* docs(query): name the request-time function in the comments that point at it

* fix(cassandra): pass the bare index name in IndexNotFound so the Query sentence matches the other backends

* fix(query): accept Unicode decimal digits in the number check and report a shape fault ahead of the request-time checks

The request-time number check refused an N value written with a Unicode
decimal digit (fullwidth, Arabic-Indic, Devanagari) that the service accepts
as the digit it stands for, so a Query that returns rows on the service
answered ValidationException here. The check now folds every general
category Nd digit to ASCII before the number rules run and echoes the value
as the request wrote it when the rules refuse it; the Nd zero code points of
Unicode 15.0 live in a module of their own. The fold applies to the check
only: the handler and the server's key binding read the value as written.
The write paths are unchanged.

The checks run on the raw body before deserialization, so a field of the
wrong JSON type elsewhere in the body (a string ExpressionAttributeValues
beside a Limit of 0, a string ExpressionAttributeNames beside a malformed N,
a numeric Select) answered the check's ValidationException where the service
and the previous release answered SerializationException. When a check fails,
the body is now deserialized as the typed input and a SerializationException
from that is returned instead; a ValidationException the deserializer raises
does not preempt the check, and a body that passes every check is not
deserialized twice. The server's call before dispatch goes through the same
function.

Measured against the service on 2026-10-25 (11:31 UTC) on tables with S/N
and S/S keys, each request twice. Unit tests cover the digit table, the
folded check and the shape-fault order; the wire file gains the measured
rows for both.

* fix(query): leave an unknown type descriptor to the request-time checks, and assert only acceptance for Unicode digits

The shape-fault pass returned the deserializer's SerializationException for an
AttributeValue with an unknown type descriptor, so Limit 0 beside {"X": "1"}
changed class. The service answers the Limit ValidationException for that
body (measured 2026-10-25), and the check's answer is returned again.

The Unicode digit tests asserted that a key condition or filter written with
a Unicode digit reads the item stored with the ASCII digit. This change makes
the request-time check accept such a value; it does not change how the
handler reads it, so the tests assert only that the value is accepted. A new
test checks that a partition key value written with Unicode digits returns no
item of a partition a ForAllValues LeadingKeys fence keeps the caller from.

* test(query): say which Limit text the service uses beside an unknown type descriptor

* test(query): pass the RANGE attributes to resolve_multipart

Main changes resolve_multipart to take the HASH and the RANGE attribute
names (ExtendDB#429). The multi-attribute HASH test now gives r as the RANGE
attribute, as its attribute definitions do.

* fix(query): order the key value type check and the begins_with refusal as the service does

On a single-attribute key schema, the later check of this branch now reports a
wrong type in a key condition expression, as the service does. The early check
from main still runs there for legacy KeyConditions, which the later check
skips. The begins_with refusal now reads the type of the value instead of the
type of the sort key.

* test(query): pin begins_with on a non-key attribute and correct the order comments

Two new rows send begins_with with an N value on an attribute that is not in
the key schema. One row uses a table with an S sort key and the other uses a
table with an N sort key. The service refuses both requests with the
begins_with operand type message.

The comments in handle_query now say that the classifier checks the values of
legacy KeyConditions. They also say which attribute definitions it uses for
each kind of key schema. The doc of resolve_key_schema_with now says where the
service reports a wrong type on a single-attribute key schema (measured
2026-11-06).

* fix(query): check each value on its own and answer in the service's order

- Report an invalid ReturnConsumedCapacity ahead of the expression and
  non-expression parameter mix.
- Check the numbers in each ExpressionAttributeValues entry on its own. A
  value that does not deserialize no longer turns the check off for the
  others, in the handler and before authorization.
- Beside a value the service cannot read as one type, answer in the
  service's order. Such a value is a null, or holds no known type
  descriptor, more than one, or an unknown one beside a known one. Select,
  ReturnConsumedCapacity and Limit come together, with the Limit text that
  names the value. The parameter mix comes next, then the first value with
  a fault and its placeholder. A value the service cannot read comes ahead
  of a number fault in another value.
- In the shape fault check, replace only the parts of such a value that the
  service cannot read. A field of the wrong JSON type in the rest of the
  value still answers SerializationException.
- Count a decimal digit only below U+10000, as the service does. The check
  refuses a digit from U+104A0 up.
- Echo a refused number with each decimal digit folded to ASCII.
- Add rows for legacy KeyConditions and for a multi-attribute key schema
  beside a non-key clause. Skip the second type check where the classifier
  checked the values.
- Delete the LeadingKeys test tables when a call raises.
- Give the checks for values the service cannot read their own module and
  tests. Move the request order unit tests and the shape fault and
  LeadingKeys Python tests to files of their own.

* fix(query): share the key value type check and update three comments

The comment above the Query request checks in authorize_request said
that they run for every principal. They run after the cross-account
refusal, so a table ARN in another account gets AccessDeniedException
without them. The service runs them first for a body it can read. Main
has the same order for every Query check, and the call does not move.
The comment now states this.

The comment above the key value type gate in handle_query now states
the service's order for legacy KeyConditions. For a legacy value of the
wrong type on a single-attribute key schema, the service reports the
projection, Select, filter, QueryFilter and unused-value checks first.
The classifier's check answers ahead of them, as on main.

The doc comment of the Query number check is about the
ExpressionAttributeValues contains invalid value wrapper. It said that on
Query the service adds the wrapper only for a value it cannot read as one
type. The service also adds it beside a Limit above 2147483647 (measured
2026-11-12), and the comment now says so.

validate_key_condition_types now calls check_key_value_type for each
value it compares. This removes type_matches and resolve_attr_name,
which repeated check_key_value_type and resolve_path_attr_name.
check_key_value_type returns KEY_CONDITION_TYPE_MISMATCH in place of a
second copy of the text. No answer changes.

validate_attribute_number in the core validation module is private
again. An earlier commit of this branch made it public, and nothing
outside that file calls it.

* fix(query): read each payload of a value with several types first

first_fault returned the more than one datatypes text as soon as a value
held two type descriptors. It did not read their payloads. The service
reads every payload first. On Query, the service gives one answer for
:v set to {"N": "bob", "S": "x"} and for {"S": "x", "N": "bob"}. The
answer is "ExpressionAttributeValues contains invalid value: The
parameter cannot be converted to a numeric value: bob for key :v".
{"N": "1", "S": "x"} answers the more than one datatypes text. The
service names a null or an empty value inside an L beside an S in the
same way. It reads N ahead of NS, and NS and M ahead of L, in either
member order (each request measured twice on 2026-11-19).

first_fault now reads the payloads in the order of TYPE_DESCRIPTORS,
which agrees with those pairs. It returns the more than one datatypes
text only when no payload has a fault.

The doc comment of the Query number check said that the service adds
the wrapper on UpdateItem. On the service, :v set to {"N": "bob"} in
UpdateItem gets no wrapper, in SET a = :v and in a ConditionExpression
that reads :v. The answer is "1 validation error detected: The
parameter cannot be converted to a numeric value: bob". The comment no
longer names UpdateItem.

* fix(query): check ExpressionAttributeNames ahead of the numbers

The request-time Query checks had no ExpressionAttributeNames step, so an
invalid names key beside {"N": "bob"} answered the numeric text. The
service and main answer `ExpressionAttributeNames contains invalid key:
Syntax error; key: "a"`.

validate_names runs the ExpressionAttributeNames deserializer on the raw
body and returns its ValidationException. Both paths of the checks call it
after the parameter mix and ahead of the values.

The service checks in the same order: it reports a Limit of 0, an invalid
ReturnConsumedCapacity and the mix ahead of an invalid key. The key comes
ahead of an N value that is not a number and of a duplicate NS. It also
comes ahead of an invalid Select and of a value the service cannot read as
one type. With KeyConditions and no KeyConditionExpression, the service
still reports the key. Each request went to the service twice on
2026-11-19, with the names map first and last in the body.

* fix(query): read a null payload as no payload

On Query, {"S": null} beside an invalid Select answered
`SerializationException: S value must be a string`. The request checks
read {"S": null} as an S, so the Select check failed. The shape fault check
then read the S payload as a JSON type fault. Main answers the Select text,
as the service does.

The service reads a type descriptor with a null payload as absent. To the
service, {"S": null} is a value it cannot read as one type, and the request
takes that order of checks. Beside an invalid Select it answers the Select
text. Beside a Limit of 0 it answers the Limit text that names the value.
Alone it answers `ExpressionAttributeValues contains invalid value:
Supplied AttributeValue is empty, must contain exactly one of the supported
datatypes for key :v`. The service accepts {"S": null, "N": "1"} in a
FilterExpression. Each request went to the service twice on 2026-11-19.

unreadable counts a type descriptor with a null payload as a part the
service cannot read, while first_fault and make_readable skip it.

* fix(query): report an empty name after a value the service cannot read

On Query, an empty name in ExpressionAttributeNames beside a value the
service cannot read as one type answered the empty name text. The service
answers the value's text. For {"#a": ""} beside {"X": "1"} it answers
`ExpressionAttributeValues contains invalid value: Supplied AttributeValue
is empty, must contain exactly one of the supported datatypes for key :x`.
Beside {}, {"N": "1", "S": "x"}, a null and {"S": null}, the same names map
answers that value's text. Beside {"X": "1"}, {"#a": "", "b": "c"} answers
`ExpressionAttributeNames contains invalid key: Syntax error; key: "b"`.
Beside {"S": "a", "X": "1"}, which has no fault of its own, {"#a": ""}
answers the empty name text. Each body went to the service twice, with the
names map first and last, on 2026-11-19.

On that path the service checks the keys of the names map ahead of the
values. Those checks refuse an invalid key, a key over 255 bytes and an
empty map. The service makes the empty name check after the values.
unreadable_value_checks now runs the key checks ahead of the values. It
runs them through the same deserializer, with each name replaced. The whole
names check runs after the values.

The unit tests share one set of message texts, and the names tests are one
table of rows. The handler and pre-IAM comments point to
validate_query_request_body, whose doc lists the order of the checks.

* docs(query): scope four comments on the names checks

The doc of validate_query_request_body said that the service makes the
request-time checks first on a Query that names a table ARN in another
account. The measurement covers a body the service can read, and the
doc now says so.

The doc of validate_names now lists the check on a key over 255 bytes,
which the deserializer makes and which validate_name_keys names. Step 5
of the unreadable_value_checks doc is three sentences. The first list in
the docstring of TestExpressionAttributeNamesOrder now covers readable
values only. The docstring also gives the place of the key checks beside
a value the service cannot read. No code or test row changes.

* refactor(query): take three message texts from core

query_key_values.rs kept private copies of three texts that core already
defines: NOT_A_NUMBER of the number check, and EMPTY_ATTRIBUTE_VALUE and
MULTI_ATTRIBUTE_VALUE of the AttributeValue deserializer. Core now makes
the three public, and the Query check imports them. The texts do not
change.

NULL_VALUE and TYPE_DESCRIPTORS stay in query_key_values.rs. Core's only
copies are private constants of its partiql module. A build without the
partiql feature leaves that module out, and the engine builds without the
feature.

* docs(query): give the M member order of the MongoDB build

The doc of first_fault said that it visits M members in key order,
because serde_json keeps the members of an object sorted by key. The
MongoDB build turns on the preserve_order feature of serde_json through
bson, so that build visits the members in document order. The docs of
first_fault and Fault, and step 4 of the unreadable_value_checks doc, now
give the iteration order of the map. No code changes.

* test(query): give the service's text for each shape fault row

TestShapeFaultsAreReportedFirst asserts the error type only, because the
SerializationException texts of the service differ from those of
ExtendDB (ExtendDB#1012). Each row of SHAPE_FAULTS now has a comment with the
message of the service, from the measurements of 2026-10-25 and
2026-11-11. No row changes.

* docs: list three Query differences from DynamoDB

docs/differences-from-dynamodb.md gets a Query section. Its rows give the
order of the cross-account refusal and the request checks (ExtendDB#974), and N
values written with Unicode decimal digits (ExtendDB#565). A third row gives the
wrapper that the service adds beside a Limit above 2147483647 (ExtendDB#976).

* fix(query): find a shape fault in any member and value

When a request-time check fails, validate_query_request_body looks for a
member of the wrong JSON type, because the service reports one ahead of
the checks. It deserialized the whole body once, and serde stops at the
first member that fails, in map order. An empty NS in
ExpressionAttributeValues stopped it, so Select: 5 beside a Limit of 0
answered the Limit text, where the service answers SerializationException.
shape_fault_first now reads each member on its own, beside TableName, and
each ExpressionAttributeValues value on its own.

The check also counted two kinds of member as shape faults that the
service reads. One is a string in ConsistentRead or ScanIndexForward that
the service reads as a boolean, such as "true", "T" or "0". The other is
a number in Limit. Beside Select: "NOPE", each answered
SerializationException here, where the service and main answer the
Select text. The check now skips them. A string such as "on" stays a
shape fault, as on the service. The handler's deserializer still refuses
every string in these members.

I measured the service answers on 2026-11-23, each body twice. On
e2d90f1, 7 of the 11 new unit rows fail, and 7 of the 11 new rows in
tests/test_query_value_shapes.py fail.

* fix(query): leave the check's answer beside a null member or name

When a request-time check fails, shape_fault_first deserializes each
member on its own. It reports a member of the wrong JSON type ahead of
the check, as the service does. It counted two nulls as such a member.
ScanIndexForward: null beside Select: "NOPE" answered
SerializationException here, where the service and main answer the
Select text. ExpressionAttributeNames: {"#a": null} beside an invalid
Select or ReturnConsumedCapacity did the same.

The service reads a null member as an absent one and a null name as an
empty name, which it reports after these checks. shape_fault_first now
skips a null member, with the rule present() already applies to the
parameter mix, and reads ExpressionAttributeNames without its null
names. The handler's deserializer still refuses both nulls.

I measured the service answers on 2026-11-24, each body twice. On
d7e6ff3, the 3 new unit rows fail, and the 3 new rows in
tests/test_query_value_shapes.py fail.

* fix(query): name a set fault beside a second type descriptor

For an ExpressionAttributeValues value with two type descriptors,
first_fault reads each payload and names the first fault ahead of the
more than one datatypes text. It read the numbers only. The service
also refuses an empty set and a set with a duplicate member there.
{"SS": ["a", "a"], "N": "1"} answered the more than one datatypes text
here, where the service answers "Input collection [a, a] contains
duplicates." for :z, and {"NS": ["1", "1"], "S": "x"} answers "Input
collection contains duplicates".

first_fault now takes these set faults too, on this path only. It reads
SS ahead of the numbers, so {"SS": ["a", "a"], "N": "bob"} answers the
duplicate text. It reads NS after its own numbers, so {"NS": ["1", "1"],
"N": "bob"} answers the numeric text. The SS and BS texts come from the
AttributeValue deserializer. The NS text and its check move from core's
partiql module to validation::number, so a build without the partiql
feature has them. The deserializer still reports a set with a duplicate
member and no second descriptor, as before.

I measured the service answers on 2026-11-24, each body twice. On
0e0f078, 12 of the 15 new unit rows fail, and 12 of the 15 new rows
in tests/test_query_value_shapes.py fail. The 3 rows that answer the
numeric text pass there and pin what does not change.
rlunar pushed a commit to rlunar/extenddb that referenced this pull request Nov 25, 2026
…ExtendDB#588)

* fix(query): refuse a Query ExclusiveStartKey the key condition cannot reach

Closes ExtendDB#440.

A Query ExclusiveStartKey from another partition, or outside the sort key
condition, was accepted and answered an empty page. The service refuses
it, with a sentence chosen by where the key falls. Measured on 2026-10-23
and 2026-10-24, every row repeated with identical answers, page-end rows
ten times each.

After the shape check, the service first asks whether a later key in the
scan direction can still satisfy the sort key condition, for either
partition:

- On a base table a later key must differ from the start key's sort
  value: ">" and "<" at the bound are refused, ">=" at the bound is
  accepted, "<=" at the bound refused, BETWEEN at the upper bound refused
  and at the lower bound accepted, begins_with with a key that does not
  carry the prefix refused; the reverse direction mirrors each.
- On an LSI or GSI a repeat of the start key's sort value counts as a
  later key, because index keys repeat: "<=", BETWEEN at either bound,
  ">=" in reverse, begins_with in reverse at the prefix and "=" with the
  key itself are all accepted; ">" and "<" at the bound are refused.
- The sentence is "The provided starting key does not match the range
  key predicate", with two base-table exceptions in the same partition:
  "=" with the key's own value: "The provided exclusive start key is
  invalid"; begins_with in reverse with the key exactly the prefix: "The
  provided starting key is outside query boundaries based on provided
  conditions".

Then the partition, when the key's partition differs from the condition's
(table, LSI, GSI, legacy KeyConditions, either direction):

- no sort key condition: "The provided starting key is outside query
  boundaries based on provided conditions";
- any sort key condition: "The query can return at most one row and
  cannot be restarted".

A hash-only base table refuses every ExclusiveStartKey with "The provided
exclusive start key is invalid", the queried partition included, and its
pages never carry a key. Partition values compare by value for numbers
(1, 1.0, 1e0, 01, +1 are equal); strings by UTF-8 byte order; binary by
byte order.

Page end: when a base table page ends on the last key that can satisfy
the sort key condition in the scan direction, the service returns no
LastEvaluatedKey (ten of ten for "=", BETWEEN at the upper bound, "<=" at
the bound, reverse ">=" at the bound). ExtendDB now drops the key there,
so a client that feeds every returned key back is never refused. Index
pages are unchanged.

Ordering, measured: filter and projection faults, unused names and
values, ConsistentRead on a GSI, Limit, a missing table or index, the
key size check and the start key shape check (missing or extra
attributes, wrong types) are reported first; the Select checks after.

The checks live in crates/engine/src/start_key.rs, called from
handle_query after the shape check. The sort key predicate is evaluated
with the expression evaluator on the start key's sort value, so every
operator and type follows the same comparison as the condition itself.

Tests: engine unit tests in start_key_tests.rs and start_key_range_tests.rs;
tests/python/test_query_start_key_partition.py, test_query_start_key_range.py
and test_query_start_key_index.py (162 rows, the hash-only page row
ExtendDB only) pass against the service and on SQLite and PostgreSQL, with
test_read_paging.py and the Query wire files. Pagination walks with Limit
1 to 3 in both directions feed every returned key back without a refusal.

Pre-existing, measured, not changed here: a sort key bound of another
type than the sort key answers InternalServerError (the type check in
ExtendDB#429); the service omits the trailing key when the next row exists but
fails the condition ("sk < z" with Limit equal to the matches), which
needs a storage look-ahead and is filed separately.

* fix(cassandra): pass the bare index name in IndexNotFound so the Query sentence matches the other backends

(cherry picked from commit 0294106)

* fix(cassandra): fold a Query start key into the key condition's sort key bound

A Query with a sort key condition and an ExclusiveStartKey on the same
partition produced two restrictions on the same side of the clustering
column (`sk_s >= ? AND sk_s > ?`), which Cassandra refuses with "More than
one restriction was found for the start bound on sk_s" (end bound in
reverse; "cannot be restricted by both an equality and an inequality
relation" on the index same-sort-value sub-query). The server answered
InternalServerError. The defect exists on main for every such request.

The Cassandra Query path now builds the sort key range as at most one lower
and one upper bound (SkRange), replaces the bound on the near side of the
scan direction with a strict bound at the start key when the start key is
at or past it, and renders the range once per CQL statement. The index
two-query path runs its same-sort-value sub-query only when the start key's
sort value lies inside the condition's range, and renders the merged range
for the advance sub-query. Binds follow the rendered clauses in order.

Unit tests pin the merge for a lower bound, a bound equal to the start key,
a start key short of the bound, BETWEEN in both directions, equality,
begins_with in reverse, strict and inclusive containment, and numeric
ordering. The three Query start key wire files pass on Cassandra (162
rows), as do test_query_scan, test_composite_keys, test_gsi,
test_scan_edge_cases and the storage direct_integration suite.

* test(cassandra): pin the sort key range each key condition operator produces

Equality renders as one clause, BETWEEN as two inclusive bounds, and
begins_with as an inclusive prefix with an exclusive upper bound: the
prefix plus U+10FFFF for strings, the incremented last byte below 0xFF
for binary, and no upper bound for an all-0xFF prefix.

* fix(query): bound begins_with on a string sort key by the next prefix

Query with begins_with(sk, :p) on a string sort key read the range
sk >= p AND sk < p + U+10FFFF on Cassandra, SQLite and PostgreSQL. A key that
starts with p followed by U+10FFFF (p + U+10FFFF, p + U+10FFFF + "b") sorts
at or above that bound and was left out. Amazon DynamoDB returns those keys
on base tables, GSIs and LSIs (measured 2026-10-25 at 22:31, 22:35 and 23:20
UTC, each request twice), ordered by their UTF-8 bytes, which is how the
three backends compare string sort keys.

The new extenddb_storage::util::string_prefix_upper_bound returns the prefix
with its last character replaced by the next scalar value: trailing U+10FFFF
characters are dropped first, and U+D7FF is followed by U+E000. A prefix that
is empty or all U+10FFFF has no upper bound, and the three backends then read
from the prefix up. MongoDB already computed the same bound in its own
next_string_prefix and is unchanged.

On PostgreSQL the bound is now a bound parameter instead of `$p || chr(1114111)`,
so build_sk_sql takes the expression maps to know whether the placeholder
exists, and bind_sk_condition binds the bound it computes from the same
function. A numeric prefix on a numeric sort key is refused in build_sk_sql
before any SQL is built, so the placeholder and bind counts cannot disagree;
it answered InternalServerError before and still does. On Cassandra the old
string_upper_bound leaves query.rs.

* test(query): begins_with on sort keys that continue with U+10FFFF

Dual-target wire tests from measurements on 2026-10-25 at 22:31 and 22:35
UTC: begins_with with prefixes ending in a, U+10FFFF, U+D7FF and U+FFFF,
forward and reverse; Limit 1 pages over the prefixes a, a + U+10FFFF and
U+10FFFF; and two BETWEEN ranges whose bounds sit next to U+10FFFF. The
service returns every key that starts with the prefix, in UTF-8 byte order.
parsnips pushed a commit to parsnips/extenddb that referenced this pull request Dec 4, 2026
…endDB#481)

* fix(query): refuse key condition values over the key size limits

Closes ExtendDB#435.

The service refuses a Query whose key condition values exceed the key
size limits before it reads anything; ExtendDB ran the Query. Measured on
2026-10-23, every row repeated with identical answers:

- A HASH value over 2048 bytes: "One or more parameter values were
  invalid: Size of hashkey has exceeded the maximum size limit of2048
  bytes" (no space after "of", as the service writes it). 2048 bytes is
  accepted.
- HASH values that each fit but add up to more than 2048 bytes (an index
  with two HASH attributes): "One or more parameter values were invalid:
  Aggregated size of all hash keys has exceeded the size limit of 2048
  bytes". A sum of exactly 2048 is accepted. A single oversized value
  gets the single sentence even when the sum is also over.
- RANGE values adding up to more than 1024 bytes, one clause or several:
  "One or more parameter values were invalid: Aggregated size of all
  range keys has exceeded the size limit of 1024 bytes". 1024 is
  accepted. Every operator is sized (=, <, <=, >, >=, begins_with);
  BETWEEN contributes its larger bound, not the sum of both.
- The HASH checks are reported before the RANGE check.
- Strings are sized by UTF-8 bytes (683 U+20AC characters, 2049 bytes,
  refused; 682 plus "xx", 2048 bytes, accepted) and binary values by
  byte length. Base tables, LSIs, GSIs and legacy KeyConditions behave
  the same.
- An undefined #name or :value in the key condition is reported before
  the size check.

Ordering, measured with a 2049-byte value: filter syntax, unused names
and values, index name, ConsistentRead on a GSI, missing table, Limit,
projection syntax and overlap, the Select conflicts and the filter
operand type are all reported first; the ExclusiveStartKey checks after.

The check is crates/core/src/validation/key_size.rs, called from
handle_query after the expression validations and before the start key
checks. The limits come from the configuration and the sentences name
them.

Tests: unit tests in validation/key_size/tests.rs and the engine;
tests/python/test_query_key_size.py, test_query_key_size_values.py and
test_query_key_size_order.py (64 rows) pass against the service. On
ExtendDB alone, five rows with two or more RANGE clauses on one index
skip until the multi-attribute range change in ExtendDB#429 merges (the handler
refuses the shape earlier today); they pass on the merged tree. The
undefined-name row stays unit level because the undefined-name refusal
for a sort key clause arrives with ExtendDB#479.

Pre-existing, measured, not changed here: a BETWEEN with the lower bound
above the upper bound is refused by the service with a bound-order
sentence; two conditions on one key are refused with "KeyConditionExpressions
must only contain one condition per key"; a Number with 39 or more digits
is refused with "Attempting to store more than 38 significant digits in a
Number"; a FilterExpression on a key attribute is refused with "Filter
Expression can only contain non-primary key attributes". ExtendDB accepts
all four.

* fix(cassandra): pass the bare index name in IndexNotFound so the Query sentence matches the other backends

* test(query): skip the idx accept rows on a backend that cannot read a multi-RANGE index

The Cassandra backend answers InternalServerError to any Query on an index
with several RANGE attributes: its ORDER BY lists sk_* then base_pk and skips
the sk2_* to skN_* clustering columns, which Cassandra refuses with
"Order by currently only supports the ordering of columns following their
declared order in the PRIMARY KEY". require_multi_range now also skips on
InternalServerError, so test_one_600_byte_range_value_is_accepted carries the
probe like the other idx rows.

* test(query): skip later-RANGE accept rows on first-RANGE-only backends

Since ExtendDB#429, the MongoDB and Cassandra backends refuse a key condition on
a later RANGE attribute of a multi-attribute index with a
ValidationException. Two rows of TestGsiQueryKeySize expect such a Query
to be served, and they failed on MongoDB. They now skip when a probe
gets that refusal, as the multi-range tests on main do. The refusal rows
still run on those backends, because the size check answers first.

* fix(core): read the key byte size through the key_size module in restorable_item

Main added validation/restorable_item.rs, which sizes a backup item's key with key_value_byte_size from the validation module. This branch moved that function into validation/key_size.rs. The call now names the new module, as check_key_size does.

* fix(core): check the number rules before sizing a Query key value

Query sized an N value in a key condition by its digit string, so an invalid
number got the key size sentence. The service checks the number first.
Measured 2026-11-20 in us-east-1 on a GSI with HASH n (N), each shape twice:

- 2049 or 39 digits answer "Attempting to store more than 38 significant
  digits in a Number", in KeyConditionExpression and in KeyConditions.
- 1 followed by 2100 zeros answers "Number overflow. Attempting to store a
  number with magnitude larger than supported range".
- The service serves 2100 zeros followed by 1.

validate_query_key_sizes now passes each N value it reads to
validate_and_normalize_number and sizes the normalized digits. Query served
a 39-digit value before and refuses it now, as the service does.

The doc comment of validate_query_key_sizes no longer lists two shapes as
not measured. The wire tests assert both, a HASH sum of exactly 2048 bytes
and the aggregated hash sentence over an oversized RANGE value. Both pass
against the service.

The comment also names a request that ExtendDB serves and the service
refuses. The request has an undefined #name in a second clause, on a key
schema with one HASH attribute and at most one RANGE attribute.

* fix(query): check Select against the GSI projection after the key size

With no ExclusiveStartKey, Query checked Select=ALL_ATTRIBUTES against the
index projection before the other request checks. The service makes that
check after the key size check. With a start key, it also comes after the
start key checks. Measured 2026-11-20 in us-east-1 on a KEYS_ONLY GSI with
Select=ALL_ATTRIBUTES, each shape twice:

- A 2049-byte key value answers the size sentence, with and without an
  ExclusiveStartKey.
- A 1-byte value answers the Select sentence.
- Without a start key, Limit 0 and a parameter mix each answer their own
  refusal ahead of the Select sentence. So do an empty or invalid
  KeyConditionExpression, a missed key schema element, a wrong-typed key
  value and a filter or projection fault. ProjectionExpression with
  ALL_ATTRIBUTES and an unused name or value also come first. ExtendDB
  answered the Select sentence for all of them.

The check now runs once, after the size and start key checks. The comment
above the size check no longer says that the type check is still to come.
The type check runs above it, in resolve_key_schema_with. The engine test
comments cite the measurement dates and region, not local files.

* test(query): add the number and Select rows and keep refusal rows visible

- test_query_key_size_values.py: rows on a GSI with HASH n (N) for 2049
  digits, 39 digits, 1 followed by 2100 zeros and 2100 zeros followed by 1.
  Each row runs in KeyConditionExpression and in KeyConditions.
- test_query_key_size_order.py: rows on a KEYS_ONLY GSI for
  Select=ALL_ATTRIBUTES with a 2049-byte and a 1-byte value, with and
  without an ExclusiveStartKey. The Limit 0 row uses the raw_client fixture
  from conftest.py in place of its own copy.
- This commit removes require_multi_range. Neither of its skips fires on any
  backend at this head. On a refusal row, a 500 or a classifier change
  turned the row into a skip.
- The BETWEEN row is two tests. The refusal half reports its result on
  MongoDB and Cassandra, where the accept half skips.
- The docstrings cite the measurement dates and region, not local files.

* docs(core): cite ExtendDB#1214 for the undefined name that Query serves

The doc comment of validate_query_key_sizes names one request that ExtendDB
serves and the service refuses: an undefined #name in a second key
condition clause. ExtendDB#1214 tracks that request.

* docs(query): split the long sentences in four new comments

Four new comments now use shorter sentences. They are the number rules in
sized_clause and its unit test, the undefined #name in
validate_query_key_sizes and the Select check in handle_query. They state
the same measurements.

* fix(core): size a Query key number the validator does not read by its text

001fe29 sized each N value of a key condition after
validate_and_normalize_number, so a number written in other Unicode
decimal digits got a 400. DynamoDB reads U+FF11 and U+0967 U+0968 as
digits. It serves `n = :v` and the KeyConditions form with those values
(200, Count 0, measured 2026-11-20 in us-east-1, twice each), and so did
the previous head.

The size check now calls normalize_number and refuses only the digit
count and magnitude faults. A value the validator does not read as a
number is sized by its text again, as before 001fe29. The unit table
and TestNumberKeyValues gain the two values, in both syntaxes.

The Select test uses the shared refused helper. Its 1-byte row without a
start key goes, because test_query_start_key_partition.py sends the same
request. Two comments are shorter.

* fix(core): do not size a Query key N value that is not a number

31159a2 sized an N value that normalize_number does not read as a
number by its text. So 2049 `x` or 2049 U+FF11 in a key condition got
the hash size sentence. DynamoDB refuses such a value with a number
sentence before it looks up the table (measured 2026-11-24 in us-east-1,
twice each). 2049 `x` gets `The parameter cannot be converted to a
numeric value: ` and the value, in KeyConditionExpression and in
KeyConditions. 39 U+FF11 get `Attempting to store more than 38
significant digits in a Number`.

Such a value now adds nothing to the size, and ExtendDB serves the Query
as main does. The number check of key condition values is ExtendDB#544's. The
unit table gains a 2049 `x` row and a 2049 U+FF11 row.

* test(query): fold the key size rows into two tables

query_key_size_tests.rs had 19 tests that sent rows of the core tests
through the expression parser. The wire files send the same rows end to
end. The file keeps the two tests that add a path: the clause order in
the expression, and the KeyConditions desugaring. The comments of two
deleted index tests named a gate that b116a46 took out.

In the core tests, one table holds the equality rows on the base table,
on `idx` and on `two-hash`. A second table holds the six
undefined-reference rows. Each row keeps its measurement comment. Two
rows have measurements from 2026-11-20 on `two-hash`, and their comments
no longer say "Not measured". They are a HASH sum of exactly 2048 bytes, and
the aggregated hash sentence with a 1025-byte RANGE value. Two tests
checked the end of a sentence that a table row asserts in full, and they
are gone.

* fix(core): count each key attribute once in the Query key size

The size check added every clause into the HASH or RANGE total,
including a second clause on one key attribute. `pk = :a AND pk = :b`
with 1025 bytes in each value got the aggregated hash sentence.
`pk = :p AND sk = :a AND sk = :b` with 600 bytes in each got the range
sentence. Main serves both. DynamoDB refuses both with `Invalid
KeyConditionExpression: KeyConditionExpressions must only contain one
condition per key`. The `pk` shape is from a measurement on 2026-11-24
in us-east-1 (sent twice), and ExtendDB#489 records the `sk` shape.

Each key attribute now contributes its largest value once, and the
single hash check reads that value. The one-condition-per-key refusal is
ExtendDB#484's. Two rows join the equality table.

* style(core): clear the clippy warnings in the Query key size code

The pedantic clippy run flagged `ExtendDB` without backticks in the doc
comment of validate_query_key_sizes (doc_markdown). The two tables of
762d4a8 tripped type_complexity, a default lint that CI's
`-D warnings` refuses. Each table now names its row type. After this
commit, clippy with `-W clippy::pedantic` and `--all-targets` on
extenddb-core and extenddb-engine reports no warning on a line this PR
adds.

* test(query): rename the isrefused tests and reuse assert_validation

Nine test names in test_query_key_size.py read `isrefused`, and they now
read `is_refused`. `refused` in query_key_size_support.py repeated the
three asserts of helpers.assert_validation. It now calls that helper and
takes its `code` argument. In test_query_key_size_order.py, `_first` and
five tests made the same three asserts after `_error`, and they now call
`refused`. `_error` stays for the two syntax error tests, which check
the start of the message.

* docs(query): count one sort key value per attribute in the limits table

482bf8a counts the largest value of each key attribute once. The sort
key row of docs/dynamodb-limits.md said that the Query check adds up
every sort key clause. It now says that the check adds up the sort key
values of the key condition, one per attribute.

* fix(core): refuse a Query key N value that is not a number

a3f733d sized an N value that normalize_number does not read as a
number as 0 bytes, so the Query went on to storage. On SQLite at
1e5f4bc, `abc`, 2049 `x`, `" 1"` and the empty value answered HTTP
200 with Count 0. That was the answer on a GSI keyed on an N attribute,
in KeyConditions and on the base table's N partition key. On the base
table's N sort key they answered InternalServerError, and the server
log shows `invalid numeric sort key: invalid digit found in string`.

DynamoDB refuses each of these values with `The parameter cannot be
converted to a numeric value: ` followed by the value as sent. The
empty value gets the colon too (measured 2026-11-24 in us-east-1, twice
each, in KeyConditionExpression and in KeyConditions). sized_clause now
refuses such a value with that text when the value holds ASCII
characters only. NumberFault::Empty has no colon, so the refusal uses
the text of NumberFault::Malformed.

A value with a character outside ASCII still adds nothing to the size.
The service reads Unicode decimal digits as digits, and the number rules
do not (ExtendDB#565). A refusal here would refuse one U+FF11, which the service
reads as the number 1.

The unit table now expects the sentence for 2049 `x`. It gains rows for
`abc`, `" 1"`, the empty value, and `1e-131` as a partition key value
and as a sort key value.

* test(query): pin the number sentences in each Query key position

test_query_key_size_values.py gains a table for N values that the
service refuses as numbers: `abc`, 2049 `x`, `" 1"`, the empty value and
`1e-131`. Each row runs in four forms. Two are on a GSI keyed on an N
attribute, in KeyConditionExpression and in KeyConditions. The other two
use the N partition key and the N sort key of a new `number_table`
fixture. Each row asserts status, code and message by equality. The
service gives these answers before the table lookup (measured
2026-11-24 in us-east-1, twice each, on a table that does not exist).

Two more rows, 39 and 683 U+FF11, assert the service's 38-digit
sentence. They are expected failures on ExtendDB, because the number
rules do not read U+FF11 as a digit (ExtendDB#565). The mark is not strict, so
a check that reads these digits makes the rows of its form pass.

The existing number test now builds its Query with the same helper.

On a server built from 1e5f4bc, the 16 rows for `abc`, 2049 `x`,
`" 1"` and the empty value fail. 12 of them get HTTP 200, and the 4 on
the sort key get InternalServerError. The 4 underflow rows pass there
too. With 1fe3f0c, the three wire files pass on SQLite: 99 passed and
8 expected failures.

* test(query): leave the U+FF11 rows to ExtendDB#565

The files in tests/python hold no expected failures (tests/python/README.md,
Design Principles). The rows for 39 and 683 U+FF11 assert the service's
38-digit sentence. ExtendDB gives that sentence only once its number rules
read Unicode decimal digits, which is ExtendDB#565, so the rows and their mark go.
The measurements of 2026-11-24 are on ExtendDB#565.

* test(query): pin the Select order on a KEYS_ONLY GSI without a start key

On a KEYS_ONLY GSI with Select ALL_ATTRIBUTES and no ExclusiveStartKey,
DynamoDB answers each of these refusals before the Select sentence:

- Limit 0
- a key condition on the base table's partition key
- an N value on the S key
- an unused expression value
- an empty KeyConditionExpression
- FilterExpression `#`

A reviewer measured each shape twice on 2026-11-24.

These shapes are now rows of
test_select_all_attributes_on_a_keys_only_gsi_is_reported_after. Each
row asserts status, code and message by equality, except the `#` row.
ExtendDB words that syntax error in its own way (ExtendDB#1419), so the row
checks the `Invalid FilterExpression: ` label. The table now sends its
requests through raw_client, because the SDK refuses Limit 0.
FILTER_LABEL, LIMIT_MESSAGE and MISSED_G_MESSAGE hold the three texts
that a new row shares with an existing test.

With the Select check moved above the Limit check, the six new rows
fail. The two 2049-byte rows of the table and two start key rows in
test_query_start_key_partition.py fail too. On SQLite, the three wire
files and test_query_start_key_partition.py give 136 passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1 Needed for the 1.0 release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Query on a GSI with one HASH and several RANGE attributes: wrong sort order, and three or more key conditions are rejected

3 participants