Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
e670127
fix(query): refuse key condition values over the key size limits
LeeroyHannigan Oct 24, 2026
0294106
fix(cassandra): pass the bare index name in IndexNotFound so the Quer…
LeeroyHannigan Oct 24, 2026
5c09198
test(query): skip the idx accept rows on a backend that cannot read a…
LeeroyHannigan Oct 24, 2026
247d63c
Merge origin/main into fix/435-query-key-size
LeeroyHannigan Nov 5, 2026
e05477b
test(query): skip later-RANGE accept rows on first-RANGE-only backends
LeeroyHannigan Nov 5, 2026
c76b2a1
Merge origin/main into fix/435-query-key-size
LeeroyHannigan Nov 14, 2026
d259b6f
fix(core): read the key byte size through the key_size module in rest…
LeeroyHannigan Nov 14, 2026
001fe29
fix(core): check the number rules before sizing a Query key value
LeeroyHannigan Nov 20, 2026
9061b23
fix(query): check Select against the GSI projection after the key size
LeeroyHannigan Nov 20, 2026
b116a46
test(query): add the number and Select rows and keep refusal rows vis…
LeeroyHannigan Nov 20, 2026
aa30100
docs(core): cite #1214 for the undefined name that Query serves
LeeroyHannigan Nov 20, 2026
ac99d0a
docs(query): split the long sentences in four new comments
LeeroyHannigan Nov 20, 2026
31159a2
fix(core): size a Query key number the validator does not read by its…
LeeroyHannigan Nov 20, 2026
77eebe6
Merge origin/main into fix/435-query-key-size
LeeroyHannigan Nov 24, 2026
a3f733d
fix(core): do not size a Query key N value that is not a number
LeeroyHannigan Nov 24, 2026
762d4a8
test(query): fold the key size rows into two tables
LeeroyHannigan Nov 24, 2026
482bf8a
fix(core): count each key attribute once in the Query key size
LeeroyHannigan Nov 24, 2026
5d10fd0
style(core): clear the clippy warnings in the Query key size code
LeeroyHannigan Nov 24, 2026
6a89a56
test(query): rename the isrefused tests and reuse assert_validation
LeeroyHannigan Nov 24, 2026
1e5f4bc
docs(query): count one sort key value per attribute in the limits table
LeeroyHannigan Nov 24, 2026
1fe3f0c
fix(core): refuse a Query key N value that is not a number
LeeroyHannigan Nov 24, 2026
b255fe5
test(query): pin the number sentences in each Query key position
LeeroyHannigan Nov 24, 2026
ee58827
test(query): leave the U+FF11 rows to #565
LeeroyHannigan Nov 24, 2026
f8a6251
Merge origin/main into fix/435-query-key-size
LeeroyHannigan Nov 25, 2026
66b82ec
test(query): pin the Select order on a KEYS_ONLY GSI without a start key
LeeroyHannigan Nov 25, 2026
8de48e2
Merge origin/main into fix/435-query-key-size
LeeroyHannigan Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
281 changes: 281 additions & 0 deletions crates/core/src/validation/key_size.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
// Copyright 2026 ExtendDB contributors
// SPDX-License-Identifier: Apache-2.0

//! Key value size limits.
//!
//! The write path checks the key values of an item against these limits (see
//! `validate_key_sizes`). `Query` applies the same limits to the values in its
//! key condition: a partition key value may not exceed
//! `max_partition_key_size_bytes` (2048), the partition key values of an index
//! with several HASH attributes may not exceed it together, and the values of
//! all range key attributes together may not exceed `max_sort_key_size_bytes`
//! (1024). All limits are inclusive. The three sentences are the service's
//! own; the single hash sentence has no space between `of` and the number.

use crate::error::DynamoDbError;
use crate::expression::{
Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, resolve_element_name,
};
use crate::limits::LimitsConfig;
use crate::types::{AttributeValue, KeySchemaElement, KeyType};
use crate::validation::number::{NumberFault, normalize_number};

/// Byte size of a key attribute value.
///
/// `S` is sized by its UTF-8 bytes, `B` by its decoded bytes and `N` by its
/// digit string. A number that passes the number rules is normalized when the
/// request is read. The Query path sizes an `N` value in `sized_clause` and
/// does not call this function for it.
pub(super) fn key_value_byte_size(value: &AttributeValue) -> usize {
match value {
AttributeValue::S(s) => s.len(),
AttributeValue::N(n) => n.len(),

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.

A valid Number is normalized before it gets here, so only an invalid one can exceed the limit, and that one gets the size sentence. On a GSI with HASH n (N), n = :v with :v set to 2049 1 digits: the service answers Attempting to store more than 38 significant digits in a Number (two samples). This branch answers Size of hashkey has exceeded the maximum size limit of2048 bytes. 1 followed by 2100 zeros gets Number overflow... from the service and the size sentence here. Validating each N value with validation::number before sizing fixes both. It also fixes 39 digits, which the service refuses and ExtendDB serves today.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 001fe29 and 31159a2. The size check now reads each N value with normalize_number and sizes the normalized digits. 2049 digits and 39 digits get Attempting to store more than 38 significant digits in a Number, and 1 followed by 2100 zeros gets the overflow sentence, in the expression and in KeyConditions. The rows are in TestNumberKeyValues in test_query_key_size_values.py. A value the validator does not read as a number, such as one written in U+FF11, is sized by its text. DynamoDB serves such a value (HTTP 200, Count 0, measured 2026-11-20).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

A correction to my reply above. 001fe29 and 31159a2 fixed this for ASCII digit counts and magnitudes only. At 31159a2 the check sized a value the validator does not read as a number by its text. So 2049 x or 2049 U+FF11 got the hash size sentence.

DynamoDB refuses these values before it looks up the table. Measured 2026-11-24 in us-east-1, twice each, on a table that does not exist:

  • abc and 2049 x answer The parameter cannot be converted to a numeric value: followed by the value, in KeyConditionExpression and in KeyConditions.
  • 39 and 2049 U+FF11 answer Attempting to store more than 38 significant digits in a Number. So my sentence that DynamoDB serves a value written in U+FF11 holds for a single U+FF11 (measured 2026-11-20), not for 39 or more.

a3f733d adds nothing to the size for a value the validator does not read as a number, so ExtendDB serves these Queries, as main does. The number check of these values is #544's for ExpressionAttributeValues and #507's for KeyConditions. number_values_get_the_number_rules_before_any_size gains a 2049 x row and a 2049 U+FF11 row. Both fail with the old n.len() arm.

AttributeValue::B(b) => b.len(),
_ => 0,
}
}

/// The refusal for a partition key value over `max` bytes.
pub(super) fn hash_key_too_large(max: usize) -> DynamoDbError {
DynamoDbError::ValidationException(format!(
"One or more parameter values were invalid: \
Size of hashkey has exceeded the maximum size limit of{max} bytes"
))
}

/// The refusal for partition key values that are each within `max` bytes but
/// add up to more than `max`. Measured 2026-10-23 on an index with HASH `h1`
/// and `h2`.
pub(super) fn hash_keys_too_large_in_total(max: usize) -> DynamoDbError {
DynamoDbError::ValidationException(format!(
"One or more parameter values were invalid: \
Aggregated size of all hash keys has exceeded the size limit of {max} bytes"
))
}

/// The refusal for range key values over `max` bytes in total.
pub(super) fn range_keys_too_large(max: usize) -> DynamoDbError {
DynamoDbError::ValidationException(format!(
"One or more parameter values were invalid: \
Aggregated size of all range keys has exceeded the size limit of {max} bytes"
))
}

/// One clause of a key condition: the attribute path and the value
/// expressions it carries (one for every form but `BETWEEN`, which has two).
type Clause<'a> = (&'a [PathElement], Vec<&'a Expr>);

/// Every clause of `kc`, whichever field the parser or the schema classifier
/// left it in. A clause is assigned to HASH or RANGE by its attribute name
/// against the key schema, not by its field, so the result does not depend on
/// how a multi-attribute key condition was arranged.
fn clauses(kc: &KeyCondition) -> Vec<Clause<'_>> {
let mut clauses: Vec<Clause<'_>> = Vec::new();
clauses.push((kc.pk_path.as_slice(), vec![&kc.pk_value]));
for (path, value) in &kc.extra_pk_conditions {
clauses.push((path.as_slice(), vec![value]));
}
match &kc.sk_condition {
Some(SortKeyCondition::Compare { path, value, .. }) => {
clauses.push((path.as_slice(), vec![value]));
}
Some(SortKeyCondition::Between { path, low, high }) => {
clauses.push((path.as_slice(), vec![low, high]));
}
Some(SortKeyCondition::BeginsWith { path, prefix }) => {
clauses.push((path.as_slice(), vec![prefix]));
}
None => {}
}
for (path, value) in &kc.extra_sk_conditions {
clauses.push((path.as_slice(), vec![value]));
}
clauses
}

/// What one clause contributes to the size check.
enum ClauseSize {
/// A `#name` or `:value` of the clause is not defined. The request keeps
/// the undefined-reference refusal it gets downstream, ahead of any size.
Unresolved,
/// The clause names an attribute outside the key schema, or is not a
/// placeholder, and adds nothing.
Skipped,
/// The position of the clause's attribute in the key schema and the bytes
/// the clause contributes.
Bytes(usize, usize),
}

/// Size one clause. A clause with two values (`BETWEEN`) contributes the
/// larger of the two. Measured 2026-10-23: bounds of 600 and 600 bytes pass (a
/// sum would be 1200), bounds of 1 and 1025 bytes are refused.
///
/// An `N` value is checked against the number rules first. One with more than
/// 38 significant digits or a magnitude out of range is refused with the
/// number's own sentence and is not sized. One that passes is sized by its
/// normalized digit string. Measured 2026-11-20 in us-east-1 on a GSI with
/// HASH `n` (N). In `KeyConditionExpression` and in `KeyConditions`, 2049 or
/// 39 digits answer `Attempting to store more than 38 significant digits in a
/// Number`. `1` followed by 2100 zeros answers `Number overflow. ...`, and the
/// service serves 2100 zeros followed by `1`. `1e-131` answers `Number
/// underflow. ...` as a partition and as a sort key value (measured
/// 2026-11-24).
///
/// An ASCII value that `normalize_number` does not read as a number is refused
/// with `The parameter cannot be converted to a numeric value: ` followed by
/// the value as sent. Measured 2026-11-24 in us-east-1, in
/// `KeyConditionExpression` and in `KeyConditions`: `abc`, 2049 `x`, ` 1`
/// and the empty value. An empty value keeps the colon, which the text of
/// `NumberFault::Empty` does not have.
///
/// A value that is not a number to these rules and holds a character outside
/// ASCII adds nothing to the size. The service reads Unicode decimal digits as
/// digits and these rules do not (#565). It serves a Query with one U+FF11,
/// read as the number 1, and answers the 38-digit sentence for 39, 683 or
/// 2049 of them. Refusing such a value here would refuse the one U+FF11.
///
/// # Errors
///
/// Returns the number's `ValidationException` for an `N` value that is not a
/// number and holds ASCII characters only, has more than 38 significant
/// digits or has a magnitude out of range.
fn sized_clause(
clause: &Clause<'_>,
key_schema: &[KeySchemaElement],
maps: &ExpressionMaps,
) -> Result<ClauseSize, DynamoDbError> {
let (path, values) = clause;
let Some(first) = path.first() else {
return Ok(ClauseSize::Skipped);
};
let Ok(name) = resolve_element_name(first, maps) else {
return Ok(ClauseSize::Unresolved);
};
let mut size = 0;
let mut placeholders = true;
for value in values {
let Expr::Placeholder(placeholder) = value else {
placeholders = false;
continue;
};
let Ok(value) = maps.resolve_value(placeholder) else {
return Ok(ClauseSize::Unresolved);
};
let bytes = match value {
AttributeValue::N(n) => match normalize_number(n) {
Ok(digits) => digits.len(),
Err(fault) if fault.is_not_a_number() && !n.is_ascii() => 0,
Err(fault) if fault.is_not_a_number() => {
return Err(NumberFault::Malformed.error(n));
}
Err(fault) => return Err(fault.error(n)),
},
other => key_value_byte_size(other),
};
size = size.max(bytes);
}
let Some(key) = key_schema.iter().position(|ks| ks.attribute_name == name) else {
return Ok(ClauseSize::Skipped);
};
if !placeholders {
return Ok(ClauseSize::Skipped);
}
Ok(ClauseSize::Bytes(key, size))
}

/// Refuse a `Query` whose key condition carries a key value over the key size
/// limits.
///
/// - If any single HASH value is over `max_partition_key_size_bytes` (2048),
/// the single hash sentence. Otherwise, if the values of the HASH
/// attributes add up to more than that, the aggregated hash sentence (only
/// an index with several HASH attributes can reach it).
/// - Every RANGE attribute contributes the size of its clause's value,
/// whatever the operator (`=`, `<`, `<=`, `>`, `>=`, `begins_with`); a
/// `BETWEEN` contributes the larger of its two bounds. The contributions are
/// added up, and a total over `max_sort_key_size_bytes` (1024) is refused
/// with the range sentence.
/// - A key attribute with more than one clause contributes its largest value
/// once, so a second clause on `pk` does not reach the aggregated hash
/// sentence. The service refuses that key condition with `Invalid
/// KeyConditionExpression: KeyConditionExpressions must only contain one
/// condition per key` (measured 2026-11-24 with 1025 bytes in each `pk`
/// value). This check does not make that refusal.
/// - The HASH checks run before the RANGE check, so the hash sentence wins when
/// both limits are exceeded.
/// - An `N` value that is not a number, has more than 38 significant digits or
/// has a magnitude out of range is refused with the number's sentence and is
/// not sized. A value that is not a number and holds a character outside
/// ASCII adds nothing (see `sized_clause`).
/// - If a `#name` or `:value` of any key clause is not defined, the check
/// returns `Ok`, because the service reports the undefined reference ahead
/// of the size. `ExtendDB` refuses most such requests later on. On a key
/// schema with one HASH and at most one RANGE attribute it serves
/// `pk = :h AND #u > :r` with `#u` undefined, which the service refuses
/// (#1214).
///

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.

On a single-attribute schema, pk = :h AND #u > :r with #u undefined is served with Count 0 today. The service refuses it. Returning Ok here is fine, but the sentence about the refusal it already has does not hold for that shape.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This difference predates the PR. The size check returns Ok for that shape, and main serves the same request with Count 0. 001fe29 and aa30100 rewrite the doc sentence to say that ExtendDB serves the request and DynamoDB refuses it. The sentence cites #1214, which tracks an undefined name in a second key condition clause.

/// All limits are inclusive. `key_schema` is the key schema being queried: the
/// index's for an index query, the table's otherwise.
///
/// Measured on the service in us-east-1 2026-10-21 to 2026-10-23: the limits
/// and the sentences on a base table, an LSI and a GSI; string and binary
/// values sized by byte length; every operator above at 1025 bytes refused;
/// `BETWEEN` as described; the hash sentence when both limits are exceeded; on
/// an index with HASH `h1`, `h2`: `h1` of 2049 bytes and `h2` of 1 byte gives
/// the single sentence, 1025 and 1024 bytes (sum 2049) and 2048 and 2048 bytes
/// give the aggregated sentence; on an index with HASH `h` and RANGE `a`, `b`,
/// `c`, `d`: `a` of 600 and `c` of 600 bytes (with `b` of 1) refused, 512 and
/// 512 passes, 512 and 513 refused, `b > 1025` refused, `a` of 600 with `b
/// BETWEEN` 1 and 600 refused and with 1 and 424 passes. Measured 2026-11-20 on
/// the `h1`, `h2` index: 1024 and 1024 bytes (sum 2048) pass, and 1025 and 1024
/// bytes with a 1025-byte RANGE value give the aggregated hash sentence.
///
/// A clause that names an attribute outside the key schema, or that is not a
/// placeholder, adds nothing, so the refusal it already gets stays unchanged.
///
/// # Errors
///
/// Returns `ValidationException` with the service's sentence when a limit is
/// exceeded or an `N` value breaks the number rules.
pub fn validate_query_key_sizes(
key_condition: &KeyCondition,
key_schema: &[KeySchemaElement],
maps: &ExpressionMaps,
limits: &LimitsConfig,
) -> Result<(), DynamoDbError> {
let mut sizes = vec![0; key_schema.len()];
for clause in clauses(key_condition) {
match sized_clause(&clause, key_schema, maps)? {
ClauseSize::Unresolved => return Ok(()),
ClauseSize::Skipped => {}
ClauseSize::Bytes(key, size) => sizes[key] = sizes[key].max(size),
}
}
let mut hash_over = false;
let mut hash_total: usize = 0;
let mut range_total: usize = 0;
for (key, size) in key_schema.iter().zip(sizes) {
match key.key_type {
KeyType::Hash => {
hash_over |= size > limits.max_partition_key_size_bytes;
hash_total = hash_total.saturating_add(size);
}
KeyType::Range => range_total = range_total.saturating_add(size),
}
}
if hash_over {
return Err(hash_key_too_large(limits.max_partition_key_size_bytes));
}
if hash_total > limits.max_partition_key_size_bytes {
return Err(hash_keys_too_large_in_total(
limits.max_partition_key_size_bytes,
));
}
if range_total > limits.max_sort_key_size_bytes {
return Err(range_keys_too_large(limits.max_sort_key_size_bytes));
}
Ok(())
}

#[cfg(test)]
mod tests;
Loading
Loading