diff --git a/crates/core/src/error/mod.rs b/crates/core/src/error/mod.rs index f135a99e9..e41802281 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -31,10 +31,20 @@ pub struct ThrottlingReason { /// capacity and one hot-key write) and 2026-10-24 (1,538 read throttles on /// the table's own capacity, 648 index reads and 162 writes in a second /// Region, all carrying this text; the 104 index-write bodies of that run -/// carry a different message naming global secondary indexes, which the -/// server does not model). Trailing period. +/// carry a different message naming global secondary indexes, +/// [`INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE`]). Trailing period. pub const PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE: &str = "The level of configured provisioned throughput for the table was exceeded. Consider increasing your provisioning level with the UpdateTable API."; +/// The `ProvisionedThroughputExceededException` message the service sends +/// when a write to the base table is held back by a provisioned global +/// secondary index's write capacity. Measured 2026-10-24 (104 +/// `BatchWriteItem`) and 2026-10-25 (5,876 bodies: 2,376 `PutItem`, 2,000 +/// `UpdateItem` and 1,500 single-item `TransactWriteItems`), every body +/// carrying this text with the reason +/// `IndexWriteProvisionedThroughputExceeded` and the index ARN. No trailing +/// period. An index read past its read capacity carries the table message. +pub const INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE: &str = "The level of configured provisioned throughput for one or more global secondary indexes of the table was exceeded. Consider increasing your provisioning level for the under-provisioned global secondary indexes with the UpdateTable API"; + /// The `ThrottlingException` message the service sends on an on-demand table /// whose partition is hot. Measured 2026-10-20 (11 of 11) and 2026-10-24 /// (7,070 of 7,070, two Regions). No trailing period. diff --git a/crates/core/src/error/throttle_tests.rs b/crates/core/src/error/throttle_tests.rs index cd59e5ef4..b90895d1d 100644 --- a/crates/core/src/error/throttle_tests.rs +++ b/crates/core/src/error/throttle_tests.rs @@ -90,7 +90,7 @@ fn throttling_reason_serializes_with_the_measured_field_names() { /// The error document of each throttle class: the namespace, the reasons /// field and its casing (`ThrottlingReasons` on the provisioned class and /// `RequestLimitExceeded`, `throttlingReasons` on `ThrottlingException`), the -/// list omitted when empty, and the message. The three measured messages are +/// list omitted when empty, and the message. The four measured messages are /// written out here, so a change to a message constant fails this test. #[test] fn throttle_error_documents_match_the_service() { @@ -103,6 +103,7 @@ fn throttle_error_documents_match_the_service() { let measured_hot_key = "Throughput exceeds the current capacity of your table or index. DynamoDB is automatically scaling your table or index so please try again shortly. If exceptions persist, check if you have a hot key: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html"; let measured_caps = "Throughput exceeds the maximum OnDemandThroughput configured on table or index"; + let measured_index_write = "The level of configured provisioned throughput for one or more global secondary indexes of the table was exceeded. Consider increasing your provisioning level for the under-provisioned global secondary indexes with the UpdateTable API"; let cases = [ ( DynamoDbError::provisioned_throughput_exceeded( @@ -115,6 +116,17 @@ fn throttle_error_documents_match_the_service() { "ThrottlingReasons": listed("TableWriteProvisionedThroughputExceeded"), }), ), + ( + DynamoDbError::provisioned_throughput_exceeded( + INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + one("IndexWriteProvisionedThroughputExceeded"), + ), + serde_json::json!({ + "__type": provisioned, + "message": measured_index_write, + "ThrottlingReasons": listed("IndexWriteProvisionedThroughputExceeded"), + }), + ), ( DynamoDbError::throttling( THROTTLING_EXCEPTION_MESSAGE, diff --git a/crates/core/src/throttle.rs b/crates/core/src/throttle.rs index 61538493b..aa44a4c26 100755 --- a/crates/core/src/throttle.rs +++ b/crates/core/src/throttle.rs @@ -15,8 +15,11 @@ use std::sync::RwLock; use std::sync::atomic::{AtomicBool, Ordering}; use web_time::Instant; -/// Default burst window: 300 seconds of accumulated capacity. -const BURST_SECONDS: f64 = 300.0; +mod bucket; +mod index; + +use bucket::TokenBucket; +pub use index::IndexThroughput; /// Default on-demand read capacity ceiling per table. const ON_DEMAND_DEFAULT_RCU: f64 = 12_000.0; @@ -30,84 +33,6 @@ const PARTITION_RCU_LIMIT: f64 = 3_000.0; /// Per-partition write capacity limit (1000 WCU/s). const PARTITION_WCU_LIMIT: f64 = 1_000.0; -/// A single token bucket that refills at a constant rate. -#[derive(Debug)] -struct TokenBucket { - /// Current token count (can go negative after a large operation). - tokens: f64, - /// Maximum tokens (burst capacity). - max_tokens: f64, - /// Tokens added per second (= provisioned CU/s). - refill_rate: f64, - /// Last time tokens were refilled. `None` until the first operation, - /// preventing burst accumulation during idle time between bucket - /// creation and first use. - last_refill: Option, -} - -impl TokenBucket { - fn new(refill_rate: f64) -> Self { - let max_tokens = refill_rate * BURST_SECONDS; - // Start with 1 second of capacity rather than the full burst window. - // Burst accumulates over time as unused capacity builds up, matching - // real DynamoDB's "unused capacity" burst model. Starting full would - // make throttling untestable for newly created tables. - // - // `last_refill` starts as `None` — the refill clock only begins on - // the first `has_capacity` or `consume` call. This prevents idle - // time between table creation and first data operation from - // accumulating burst tokens. - Self { - tokens: refill_rate, - max_tokens, - refill_rate, - last_refill: None, - } - } - - /// Refill tokens based on elapsed time since the last operation. - /// On the first call, starts the refill clock without adding tokens. - fn refill(&mut self, now: Instant) { - if let Some(last) = self.last_refill { - let elapsed = now.duration_since(last).as_secs_f64(); - if elapsed > 0.0 { - self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.max_tokens); - } - } - self.last_refill = Some(now); - } - - /// Check if the bucket has any tokens available (pre-dispatch check). - fn has_capacity(&mut self, now: Instant) -> bool { - self.refill(now); - self.tokens > 0.0 - } - - /// Consume tokens after a successful operation. - fn consume(&mut self, amount: f64, now: Instant) { - self.refill(now); - self.tokens -= amount; - } - - /// Update the refill rate (e.g., after `UpdateTable` changes throughput). - fn update_rate(&mut self, new_rate: f64) { - let old_max = self.max_tokens; - self.max_tokens = new_rate * BURST_SECONDS; - self.refill_rate = new_rate; - if old_max > 0.0 { - // A positive balance keeps its share of the burst window. A debt - // (the balance below zero that an operation larger than the - // balance leaves) keeps its token count and is repaid at the new - // rate. - if self.tokens > 0.0 { - self.tokens = (self.tokens / old_max * self.max_tokens).min(self.max_tokens); - } - } else { - self.tokens = self.max_tokens; - } - } -} - /// Throughput configuration for a table, used to create/update buckets. #[derive(Debug, Clone, Copy)] pub struct TableThroughput { @@ -212,7 +137,7 @@ struct AccountBuckets { } /// Result of a throttle check. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum ThrottleResult { /// Request may proceed. Allowed, @@ -225,10 +150,10 @@ pub enum ThrottleResult { impl ThrottleResult { /// The bucket that refused, or `None` when the request was allowed. #[must_use] - pub fn cause(&self) -> Option { + pub fn cause(&self) -> Option<&ThrottleCause> { match self { Self::Allowed => None, - Self::ThrottledRead(c) | Self::ThrottledWrite(c) => Some(*c), + Self::ThrottledRead(c) | Self::ThrottledWrite(c) => Some(c), } } } @@ -236,7 +161,7 @@ impl ThrottleResult { /// Which bucket refused a request. The service names the throttled resource /// and the limit on a throttle error (`ThrottlingReasons`); the server maps /// this cause and the table's billing mode onto that vocabulary. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum ThrottleCause { /// The table's own bucket: its provisioned capacity, the default ceiling /// of an on-demand table, or an `OnDemandThroughput` cap set on one. @@ -252,10 +177,29 @@ pub enum ThrottleCause { /// Whether the table is billed on demand. on_demand: bool, }, + /// A provisioned global secondary index's bucket: its read bucket for a + /// `Query` or `Scan` that names the index, its write bucket for a write to + /// the base table. Only provisioned indexes have buckets, so the cause + /// carries no billing mode. + Index { + /// The index whose bucket refused. + index_name: String, + }, /// The per-account aggregate bucket. Account, } +impl ThrottleCause { + /// The index whose bucket refused, for an [`ThrottleCause::Index`] cause. + #[must_use] + pub fn index_name(&self) -> Option<&str> { + match self { + Self::Index { index_name } => Some(index_name), + _ => None, + } + } +} + /// Thread-safe throttle manager holding all token buckets. /// /// Uses `RwLock` for the maps. The write lock is held briefly for bucket @@ -264,6 +208,10 @@ pub enum ThrottleCause { /// for `TokenBucket`, we use the write lock for all operations). pub struct ThrottleManager { tables: RwLock>, + /// Each table's provisioned global secondary indexes, in the order the + /// table's description lists them. No lock is taken while another of + /// these maps' locks is held. + indexes: RwLock>>, partitions: RwLock>, accounts: RwLock>, account_rcu_limit: f64, @@ -282,6 +230,7 @@ impl ThrottleManager { pub fn new(account_rcu_limit: u64, account_wcu_limit: u64, enabled: bool) -> Self { Self { tables: RwLock::new(HashMap::new()), + indexes: RwLock::new(HashMap::new()), partitions: RwLock::new(HashMap::new()), accounts: RwLock::new(HashMap::new()), account_rcu_limit: account_rcu_limit as f64, @@ -328,7 +277,36 @@ impl ThrottleManager { } } - /// Remove a table's buckets (called on `DeleteTable`). + /// Replace a table's set of provisioned global secondary indexes. + /// + /// Called with the table's registration, from its description. An index + /// already registered keeps its balance and takes the new rates, as a + /// table does on `UpdateTable`; a new one starts with one second of its + /// rates; one absent from `indexes` loses its buckets, so an `UpdateTable` + /// that deleted it stops holding back writes. The order of `indexes` is + /// kept, so a write refused by several indexes names the first in + /// `DescribeTable` order. + pub fn register_indexes( + &self, + account_id: &str, + table_name: &str, + indexes: Vec, + ) { + let key = TableKey { + account_id: account_id.to_owned(), + table_name: table_name.to_owned(), + }; + let Ok(mut map) = self.indexes.write() else { + return; + }; + let previous = map.remove(&key).unwrap_or_default(); + let set = index::replace(previous, indexes); + if !set.is_empty() { + map.insert(key, set); + } + } + + /// Remove a table's buckets and its indexes' (called on `DeleteTable`). pub fn remove_table(&self, account_id: &str, table_name: &str) { let key = TableKey { account_id: account_id.to_owned(), @@ -337,6 +315,9 @@ impl ThrottleManager { if let Ok(mut tables) = self.tables.write() { tables.remove(&key); } + if let Ok(mut indexes) = self.indexes.write() { + indexes.remove(&key); + } } /// Check if a table has registered throttle buckets. @@ -355,7 +336,9 @@ impl ThrottleManager { /// /// Checks per-partition, per-table, and per-account buckets in order. /// Returns `Allowed` if all have capacity, or the appropriate throttle - /// result if any is exhausted. + /// result if any is exhausted. A write is also checked against the + /// table's provisioned global secondary indexes; see + /// [`Self::check_capacity_with_partition`]. /// /// `partition_value` is the partition key value for item-level operations. /// When provided, per-partition limits (1000 WCU/s, 3000 RCU/s) are enforced. @@ -366,10 +349,19 @@ impl ThrottleManager { is_read: bool, is_write: bool, ) -> ThrottleResult { - self.check_capacity_with_partition(account_id, table_name, is_read, is_write, None) + self.check_capacity_with_partition(account_id, table_name, is_read, is_write, None, None) } /// Check capacity with optional per-partition throttling. + /// + /// `index_name` is the index a `Query` or `Scan` names. When it names a + /// provisioned global secondary index registered for the table, the read + /// is checked against the index's read bucket in place of the table's; a + /// local secondary index shares the table's capacity, so it and a name no + /// registered index has read from the table's buckets. A write is checked + /// against the table's write bucket and then each registered index's write + /// bucket in order; the first that is empty refuses with + /// [`ThrottleCause::Index`]. pub fn check_capacity_with_partition( &self, account_id: &str, @@ -377,6 +369,7 @@ impl ThrottleManager { is_read: bool, is_write: bool, partition_value: Option<&str>, + index_name: Option<&str>, ) -> ThrottleResult { if !self.enabled.load(Ordering::Relaxed) { return ThrottleResult::Allowed; @@ -384,30 +377,59 @@ impl ThrottleManager { let now = Instant::now(); let mut on_demand = false; + let key = TableKey { + account_id: account_id.to_owned(), + table_name: table_name.to_owned(), + }; + + // A read naming a provisioned global secondary index is served from + // the index's read bucket and does not consult the table's. + let mut index_read = false; + if is_read + && let Some(name) = index_name + && let Ok(mut indexes) = self.indexes.write() + && let Some(set) = indexes.get_mut(&key) + && let Some(allowed) = index::read_allowed(set, name, now) + { + index_read = true; + if !allowed { + return ThrottleResult::ThrottledRead(ThrottleCause::Index { + index_name: name.to_owned(), + }); + } + } // Check per-table bucket. - if let Ok(mut tables) = self.tables.write() { - let key = TableKey { - account_id: account_id.to_owned(), - table_name: table_name.to_owned(), - }; - if let Some(buckets) = tables.get_mut(&key) { - on_demand = buckets.on_demand; - if is_read && !buckets.read.has_capacity(now) { - return ThrottleResult::ThrottledRead(ThrottleCause::Table { - on_demand, - capped: buckets.read_capped, - }); - } - if is_write && !buckets.write.has_capacity(now) { - return ThrottleResult::ThrottledWrite(ThrottleCause::Table { - on_demand, - capped: buckets.write_capped, - }); - } + if let Ok(mut tables) = self.tables.write() + && let Some(buckets) = tables.get_mut(&key) + { + on_demand = buckets.on_demand; + if is_read && !index_read && !buckets.read.has_capacity(now) { + return ThrottleResult::ThrottledRead(ThrottleCause::Table { + on_demand, + capped: buckets.read_capped, + }); + } + if is_write && !buckets.write.has_capacity(now) { + return ThrottleResult::ThrottledWrite(ThrottleCause::Table { + on_demand, + capped: buckets.write_capped, + }); } } + // A write the table's bucket allowed is held back by the first index, + // in the order registered, whose write bucket is empty. + if is_write + && let Ok(mut indexes) = self.indexes.write() + && let Some(set) = indexes.get_mut(&key) + && let Some(exhausted) = index::first_write_exhausted(set, now) + { + return ThrottleResult::ThrottledWrite(ThrottleCause::Index { + index_name: exhausted.to_owned(), + }); + } + // Check per-partition bucket (1000 WCU/s, 3000 RCU/s per partition). if let Some(pv) = partition_value && let Ok(mut partitions) = self.partitions.write() @@ -454,12 +476,19 @@ impl ThrottleManager { /// Consume capacity after a successful operation. /// - /// Deducts tokens from per-table and per-account buckets. + /// Deducts tokens from per-table and per-account buckets. A write's charge + /// to the table's provisioned global secondary indexes is + /// [`Self::consume_index_writes`]. pub fn consume(&self, account_id: &str, table_name: &str, read_units: f64, write_units: f64) { - self.consume_with_partition(account_id, table_name, read_units, write_units, None); + self.consume_with_partition(account_id, table_name, read_units, write_units, None, None); } /// Consume capacity with optional per-partition tracking. + /// + /// A read whose `index_name` names a registered provisioned global + /// secondary index is charged to the index's read bucket, not the table's. + /// A write is charged to the table's write bucket here and to the indexes + /// it touched by [`Self::consume_index_writes`]. pub fn consume_with_partition( &self, account_id: &str, @@ -467,25 +496,35 @@ impl ThrottleManager { read_units: f64, write_units: f64, partition_value: Option<&str>, + index_name: Option<&str>, ) { if !self.enabled.load(Ordering::Relaxed) { return; } let now = Instant::now(); + let key = TableKey { + account_id: account_id.to_owned(), + table_name: table_name.to_owned(), + }; - if let Ok(mut tables) = self.tables.write() { - let key = TableKey { - account_id: account_id.to_owned(), - table_name: table_name.to_owned(), - }; - if let Some(buckets) = tables.get_mut(&key) { - if read_units > 0.0 { - buckets.read.consume(read_units, now); - } - if write_units > 0.0 { - buckets.write.consume(write_units, now); - } + let mut index_read = false; + if read_units > 0.0 + && index_name.is_some() + && let Ok(mut indexes) = self.indexes.write() + && let Some(set) = indexes.get_mut(&key) + { + index_read = index::charge_read(set, index_name, read_units, now); + } + + if let Ok(mut tables) = self.tables.write() + && let Some(buckets) = tables.get_mut(&key) + { + if read_units > 0.0 && !index_read { + buckets.read.consume(read_units, now); + } + if write_units > 0.0 { + buckets.write.consume(write_units, now); } } @@ -530,6 +569,31 @@ impl ThrottleManager { } } } + + /// Charge a served write to the table's provisioned global secondary + /// indexes: each registered index that `index_writes` names, by its + /// units. The service charges an index only for a write whose old or new + /// item carries the index's key attributes, so an index the write did + /// not touch is not named and keeps its capacity. + pub fn consume_index_writes( + &self, + account_id: &str, + table_name: &str, + index_writes: &HashMap, + ) { + if index_writes.is_empty() || !self.enabled.load(Ordering::Relaxed) { + return; + } + let key = TableKey { + account_id: account_id.to_owned(), + table_name: table_name.to_owned(), + }; + if let Ok(mut indexes) = self.indexes.write() + && let Some(set) = indexes.get_mut(&key) + { + index::charge_writes(set, index_writes, Instant::now()); + } + } } impl Default for ThrottleManager { @@ -539,136 +603,10 @@ impl Default for ThrottleManager { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn token_bucket_starts_with_one_second_capacity() { - let bucket = TokenBucket::new(100.0); - assert_eq!(bucket.max_tokens, 100.0 * BURST_SECONDS); - assert_eq!(bucket.tokens, 100.0); // 1 second of capacity - assert!(bucket.last_refill.is_none()); // lazy — clock not started - } - - #[test] - fn token_bucket_consume_and_refill() { - let now = Instant::now(); - let mut bucket = TokenBucket::new(100.0); - // First consume starts the refill clock, then deducts tokens. - bucket.consume(100.0, now); - assert!(bucket.tokens <= 0.0); - assert!(!bucket.has_capacity(now)); - } - - #[test] - fn token_bucket_no_burst_accumulation_before_first_use() { - let mut bucket = TokenBucket::new(5.0); - // Simulate idle time: create bucket, wait, then check capacity. - // With lazy refill, the bucket should still have only 5 tokens - // (1 second of capacity) regardless of wall-clock delay. - let later = Instant::now(); - // First call starts the clock — no tokens added. - assert!(bucket.has_capacity(later)); - assert_eq!(bucket.tokens, 5.0); // unchanged from initial - } - - #[test] - fn throttle_manager_allows_when_disabled() { - let mgr = ThrottleManager::new(100, 100, false); - mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); - assert_eq!( - mgr.check_capacity("acct", "tbl", true, false), - ThrottleResult::Allowed - ); - } - - #[test] - fn throttle_manager_allows_unregistered_table() { - let mgr = ThrottleManager::new(100, 100, true); - assert_eq!( - mgr.check_capacity("acct", "unknown", true, false), - ThrottleResult::Allowed - ); - } - - #[test] - fn throttle_manager_throttles_exhausted_table() { - let mgr = ThrottleManager::new(100_000, 100_000, true); - mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); - // Drain the table bucket (starts with 1 token = 1 second of 1 CU/s). - mgr.consume("acct", "tbl", 2.0, 0.0); - assert_eq!( - mgr.check_capacity("acct", "tbl", true, false), - ThrottleResult::ThrottledRead(ThrottleCause::Table { - on_demand: false, - capped: false, - }) - ); - } - - #[test] - fn throttle_manager_throttles_exhausted_writes() { - let mgr = ThrottleManager::new(100_000, 100_000, true); - mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); - mgr.consume("acct", "tbl", 0.0, 2.0); - assert_eq!( - mgr.check_capacity("acct", "tbl", false, true), - ThrottleResult::ThrottledWrite(ThrottleCause::Table { - on_demand: false, - capped: false, - }) - ); - } - - #[test] - fn throttle_manager_remove_table() { - let mgr = ThrottleManager::new(100_000, 100_000, true); - mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); - mgr.remove_table("acct", "tbl"); - // After removal, unregistered table is allowed. - assert_eq!( - mgr.check_capacity("acct", "tbl", true, true), - ThrottleResult::Allowed - ); - } - - #[test] - fn throttle_manager_account_level_throttle() { - let mgr = ThrottleManager::new(1, 1, true); - mgr.register_table( - "acct", - "tbl", - TableThroughput::provisioned(100_000, 100_000), - ); - // Table has plenty of capacity, but account limit is 1 CU/s. - // Drain account bucket (starts with 1 token). - mgr.consume("acct", "tbl", 2.0, 0.0); - assert_eq!( - mgr.check_capacity("acct", "tbl", true, false), - ThrottleResult::ThrottledRead(ThrottleCause::Account) - ); - } - - #[test] - fn on_demand_table_uses_default_ceilings() { - let mgr = ThrottleManager::new(100_000, 100_000, true); - mgr.register_table("acct", "tbl", TableThroughput::on_demand()); - // Should allow normal operations. - assert_eq!( - mgr.check_capacity("acct", "tbl", true, true), - ThrottleResult::Allowed - ); - } - - #[test] - fn update_rate_adjusts_bucket() { - let mut bucket = TokenBucket::new(100.0); - assert_eq!(bucket.max_tokens, 100.0 * BURST_SECONDS); - bucket.update_rate(200.0); - assert_eq!(bucket.max_tokens, 200.0 * BURST_SECONDS); - assert_eq!(bucket.refill_rate, 200.0); - } -} +mod manager_tests; #[cfg(test)] mod cause_tests; + +#[cfg(test)] +mod index_tests; diff --git a/crates/core/src/throttle/bucket.rs b/crates/core/src/throttle/bucket.rs new file mode 100644 index 000000000..d33f76bd5 --- /dev/null +++ b/crates/core/src/throttle/bucket.rs @@ -0,0 +1,131 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The token bucket every throttle limit is built from. + +use web_time::Instant; + +/// Default burst window: 300 seconds of accumulated capacity. +const BURST_SECONDS: f64 = 300.0; + +/// A single token bucket that refills at a constant rate. +#[derive(Debug)] +pub(super) struct TokenBucket { + /// Current token count (can go negative after a large operation). + tokens: f64, + /// Maximum tokens (burst capacity). + max_tokens: f64, + /// Tokens added per second (= provisioned CU/s). + refill_rate: f64, + /// Last time tokens were refilled. `None` until the first operation, + /// preventing burst accumulation during idle time between bucket + /// creation and first use. + last_refill: Option, +} + +impl TokenBucket { + pub(super) fn new(refill_rate: f64) -> Self { + let max_tokens = refill_rate * BURST_SECONDS; + // Start with 1 second of capacity rather than the full burst window. + // Burst accumulates over time as unused capacity builds up, matching + // real DynamoDB's "unused capacity" burst model. Starting full would + // make throttling untestable for newly created tables. + // + // `last_refill` starts as `None` — the refill clock only begins on + // the first `has_capacity` or `consume` call. This prevents idle + // time between table creation and first data operation from + // accumulating burst tokens. + Self { + tokens: refill_rate, + max_tokens, + refill_rate, + last_refill: None, + } + } + + /// Refill tokens based on elapsed time since the last operation. + /// On the first call, starts the refill clock without adding tokens. + fn refill(&mut self, now: Instant) { + if let Some(last) = self.last_refill { + let elapsed = now.duration_since(last).as_secs_f64(); + if elapsed > 0.0 { + self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.max_tokens); + } + } + self.last_refill = Some(now); + } + + /// Check if the bucket has any tokens available (pre-dispatch check). + pub(super) fn has_capacity(&mut self, now: Instant) -> bool { + self.refill(now); + self.tokens > 0.0 + } + + /// Consume tokens after a successful operation. + pub(super) fn consume(&mut self, amount: f64, now: Instant) { + self.refill(now); + self.tokens -= amount; + } + + /// Update the refill rate (e.g., after `UpdateTable` changes throughput). + pub(super) fn update_rate(&mut self, new_rate: f64) { + let old_max = self.max_tokens; + self.max_tokens = new_rate * BURST_SECONDS; + self.refill_rate = new_rate; + if old_max > 0.0 { + // A positive balance keeps its share of the burst window. A debt + // (the balance below zero that an operation larger than the + // balance leaves) keeps its token count and is repaid at the new + // rate. + if self.tokens > 0.0 { + self.tokens = (self.tokens / old_max * self.max_tokens).min(self.max_tokens); + } + } else { + self.tokens = self.max_tokens; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_bucket_starts_with_one_second_capacity() { + let bucket = TokenBucket::new(100.0); + assert_eq!(bucket.max_tokens, 100.0 * BURST_SECONDS); + assert_eq!(bucket.tokens, 100.0); // 1 second of capacity + assert!(bucket.last_refill.is_none()); // lazy — clock not started + } + + #[test] + fn token_bucket_consume_and_refill() { + let now = Instant::now(); + let mut bucket = TokenBucket::new(100.0); + // First consume starts the refill clock, then deducts tokens. + bucket.consume(100.0, now); + assert!(bucket.tokens <= 0.0); + assert!(!bucket.has_capacity(now)); + } + + #[test] + fn token_bucket_no_burst_accumulation_before_first_use() { + let mut bucket = TokenBucket::new(5.0); + // Simulate idle time: create bucket, wait, then check capacity. + // With lazy refill, the bucket should still have only 5 tokens + // (1 second of capacity) regardless of wall-clock delay. + let later = Instant::now(); + // First call starts the clock — no tokens added. + assert!(bucket.has_capacity(later)); + assert_eq!(bucket.tokens, 5.0); // unchanged from initial + } + + #[test] + fn update_rate_adjusts_bucket() { + let mut bucket = TokenBucket::new(100.0); + assert_eq!(bucket.max_tokens, 100.0 * BURST_SECONDS); + bucket.update_rate(200.0); + assert_eq!(bucket.max_tokens, 200.0 * BURST_SECONDS); + assert_eq!(bucket.refill_rate, 200.0); + } +} diff --git a/crates/core/src/throttle/cause_tests.rs b/crates/core/src/throttle/cause_tests.rs index 8d5d843ae..9e374b183 100644 --- a/crates/core/src/throttle/cause_tests.rs +++ b/crates/core/src/throttle/cause_tests.rs @@ -15,10 +15,10 @@ fn partition_throttle_carries_the_billing_mode() { let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); // Drain the partition bucket before the table is registered, so the // table bucket starts full. - mgr.consume_with_partition("acct", "tbl", 0.0, 1.0e9, Some("k")); + mgr.consume_with_partition("acct", "tbl", 0.0, 1.0e9, Some("k"), None); mgr.register_table("acct", "tbl", throughput); assert_eq!( - mgr.check_capacity_with_partition("acct", "tbl", false, true, Some("k")), + mgr.check_capacity_with_partition("acct", "tbl", false, true, Some("k"), None), ThrottleResult::ThrottledWrite(ThrottleCause::Partition { on_demand }), "on_demand={on_demand}" ); @@ -57,7 +57,7 @@ fn on_demand_caps_size_the_table_bucket() { ); assert_eq!( mgr.check_capacity("acct", "tbl", false, true).cause(), - Some(ThrottleCause::Table { + Some(&ThrottleCause::Table { on_demand: true, capped: true, }) diff --git a/crates/core/src/throttle/index.rs b/crates/core/src/throttle/index.rs new file mode 100644 index 000000000..12ee17aba --- /dev/null +++ b/crates/core/src/throttle/index.rs @@ -0,0 +1,123 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The buckets of a table's provisioned global secondary indexes. +//! +//! A provisioned global secondary index has its own read and write capacity. +//! The service refuses a `Query` or `Scan` that names the index when the +//! index's read capacity is exhausted, and a base-table write when an index's +//! write capacity is (measured against Amazon DynamoDB on 2026-10-24 and +//! 2026-10-25). A local secondary index shares the table's capacity and has +//! no buckets here. + +use std::collections::HashMap; + +use web_time::Instant; + +use super::bucket::TokenBucket; + +/// Throughput of one provisioned global secondary index, used to create or +/// update its buckets. +#[derive(Debug, Clone, PartialEq)] +pub struct IndexThroughput { + /// The index name, as `DescribeTable` lists it. + pub index_name: String, + /// Read capacity units per second. + pub rcu: f64, + /// Write capacity units per second. + pub wcu: f64, +} + +impl IndexThroughput { + /// Throughput of a provisioned index. + #[must_use] + #[allow(clippy::cast_precision_loss)] // CU values are small enough for f64 + pub fn provisioned(index_name: impl Into, rcu: i64, wcu: i64) -> Self { + Self { + index_name: index_name.into(), + rcu: rcu as f64, + wcu: wcu as f64, + } + } +} + +/// One index's bucket pair. +pub(super) struct IndexBuckets { + pub(super) index_name: String, + pub(super) read: TokenBucket, + pub(super) write: TokenBucket, +} + +/// The index set `throughputs` describes, built from `previous`: an index +/// already in `previous` keeps its balance and takes the new rates, a new one +/// starts with one second of its rates as a new table's buckets do, and one +/// absent from `throughputs` is dropped. The result is in the order of +/// `throughputs`. +pub(super) fn replace( + mut previous: Vec, + throughputs: Vec, +) -> Vec { + throughputs + .into_iter() + .map( + |t| match previous.iter().position(|b| b.index_name == t.index_name) { + Some(i) => { + let mut kept = previous.swap_remove(i); + kept.read.update_rate(t.rcu); + kept.write.update_rate(t.wcu); + kept + } + None => IndexBuckets { + index_name: t.index_name, + read: TokenBucket::new(t.rcu), + write: TokenBucket::new(t.wcu), + }, + }, + ) + .collect() +} + +/// Whether the index named `name` has read capacity at `now`: `None` when no +/// index in `set` has that name (the read is the table's), `Some(false)` when +/// the index refuses. +pub(super) fn read_allowed(set: &mut [IndexBuckets], name: &str, now: Instant) -> Option { + set.iter_mut() + .find(|b| b.index_name == name) + .map(|b| b.read.has_capacity(now)) +} + +/// The first index in `set`, in registration order, whose write bucket is +/// empty at `now`. +pub(super) fn first_write_exhausted(set: &mut [IndexBuckets], now: Instant) -> Option<&str> { + for buckets in set.iter_mut() { + if !buckets.write.has_capacity(now) { + return Some(buckets.index_name.as_str()); + } + } + None +} + +/// Charge a served read to the read bucket of the index `index_name` names, +/// when it is in `set`. Returns whether it was charged, in which case the +/// table's read bucket is not charged. +pub(super) fn charge_read( + set: &mut [IndexBuckets], + index_name: Option<&str>, + read_units: f64, + now: Instant, +) -> bool { + set.iter_mut() + .find(|b| index_name == Some(b.index_name.as_str())) + .map(|b| b.read.consume(read_units, now)) + .is_some() +} + +/// Charge a served write to the write bucket of each index in `set` that +/// `writes` names, by its units. +pub(super) fn charge_writes(set: &mut [IndexBuckets], writes: &HashMap, now: Instant) { + for buckets in set.iter_mut() { + if let Some(units) = writes.get(&buckets.index_name) { + buckets.write.consume(*units, now); + } + } +} diff --git a/crates/core/src/throttle/index_tests.rs b/crates/core/src/throttle/index_tests.rs new file mode 100644 index 000000000..5bafc6058 --- /dev/null +++ b/crates/core/src/throttle/index_tests.rs @@ -0,0 +1,293 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The buckets of a table's provisioned global secondary indexes: the set a +//! registration replaces, the read a named index serves, the write every index +//! holds back, the write charged to the indexes it touched, and their removal +//! with the table. + +use super::*; + +fn index(name: &str, rcu: i64, wcu: i64) -> IndexThroughput { + IndexThroughput::provisioned(name, rcu, wcu) +} + +fn index_read(name: &str) -> ThrottleResult { + ThrottleResult::ThrottledRead(ThrottleCause::Index { + index_name: name.to_owned(), + }) +} + +fn index_write(name: &str) -> ThrottleResult { + ThrottleResult::ThrottledWrite(ThrottleCause::Index { + index_name: name.to_owned(), + }) +} + +/// The refusal of a provisioned table's own bucket. +fn table_cause() -> ThrottleCause { + ThrottleCause::Table { + on_demand: false, + capped: false, + } +} + +/// A manager with one provisioned table "tbl" and its `indexes`. +fn manager(table_rcu: i64, table_wcu: i64, indexes: Vec) -> ThrottleManager { + let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); + mgr.register_table( + "acct", + "tbl", + TableThroughput::provisioned(table_rcu, table_wcu), + ); + mgr.register_indexes("acct", "tbl", indexes); + mgr +} + +fn read(mgr: &ThrottleManager, index_name: Option<&str>) -> ThrottleResult { + mgr.check_capacity_with_partition("acct", "tbl", true, false, None, index_name) +} + +fn write(mgr: &ThrottleManager) -> ThrottleResult { + mgr.check_capacity("acct", "tbl", false, true) +} + +fn consume_read(mgr: &ThrottleManager, units: f64, index_name: Option<&str>) { + mgr.consume_with_partition("acct", "tbl", units, 0.0, None, index_name); +} + +fn consume_index_writes(mgr: &ThrottleManager, writes: &[(&str, f64)]) { + let writes = writes.iter().map(|(n, u)| ((*n).to_owned(), *u)).collect(); + mgr.consume_index_writes("acct", "tbl", &writes); +} + +/// A read naming a registered index is refused by the index's read bucket, +/// with the index's name, while the table's read bucket is full, and +/// consuming it charges the index and not the table. +#[test] +fn a_read_naming_an_index_is_charged_to_and_refused_by_the_index() { + let mgr = manager(1, 1, vec![index("gsi", 1, 1)]); + consume_read(&mgr, 2.0, Some("gsi")); + let refused = read(&mgr, Some("gsi")); + assert_eq!(refused, index_read("gsi")); + assert_eq!( + refused.cause().and_then(ThrottleCause::index_name), + Some("gsi") + ); + // The table's read bucket still holds its first second. + assert_eq!(read(&mgr, None), ThrottleResult::Allowed); +} + +/// A read naming a registered index does not consult the table's read +/// bucket: with the table's drained, the index read is allowed. +#[test] +fn a_read_naming_an_index_does_not_consult_the_table_read_bucket() { + let mgr = manager(1, 1, vec![index("gsi", 1, 1)]); + consume_read(&mgr, 2.0, None); + assert_eq!( + read(&mgr, None), + ThrottleResult::ThrottledRead(table_cause()) + ); + assert_eq!(read(&mgr, Some("gsi")), ThrottleResult::Allowed); +} + +/// A name no registered index has (a local secondary index, or no index at +/// all) is served from the table's buckets, for the check and the charge. +#[test] +fn a_read_naming_no_registered_index_uses_the_table_buckets() { + let mgr = manager(1, 1, vec![index("gsi", 1, 1)]); + consume_read(&mgr, 2.0, Some("lsi")); + assert_eq!( + read(&mgr, Some("lsi")), + ThrottleResult::ThrottledRead(table_cause()) + ); + assert_eq!(read(&mgr, Some("gsi")), ThrottleResult::Allowed); + assert_eq!(read(&mgr, None).cause(), Some(&table_cause())); +} + +/// A write the table's bucket allows is refused by the first exhausted index +/// in the order registered, naming it. +#[test] +fn a_write_is_refused_by_the_first_exhausted_index_in_order() { + let mgr = manager( + 1_000, + 1_000, + vec![ + index("roomy", 1, 1_000), + index("second", 1, 1), + index("third", 1, 1), + ], + ); + // Each index is charged two units here: "second" and "third" go below + // zero, "roomy" and the table stay positive. + mgr.consume("acct", "tbl", 0.0, 2.0); + consume_index_writes(&mgr, &[("roomy", 2.0), ("second", 2.0), ("third", 2.0)]); + assert_eq!(write(&mgr), index_write("second")); +} + +/// With the table's write bucket and an index's both empty, the table's +/// refuses: it is checked first. +#[test] +fn the_table_write_bucket_refuses_before_the_indexes() { + let mgr = manager(1, 1, vec![index("gsi", 1, 1)]); + mgr.consume("acct", "tbl", 0.0, 2.0); + consume_index_writes(&mgr, &[("gsi", 2.0)]); + assert_eq!(write(&mgr), ThrottleResult::ThrottledWrite(table_cause())); +} + +/// A write charges the write bucket of each index it names, by its units, +/// and no other index: a table write that names none leaves every index +/// full, and after "b" is charged two units and "c" half of one, "b" refuses +/// while "a" and "c" do not, in either order. +#[test] +fn a_write_charges_only_the_indexes_it_names() { + let mgr = manager( + 1_000, + 1_000, + vec![index("a", 1, 1), index("b", 1, 1), index("c", 1, 1)], + ); + mgr.consume("acct", "tbl", 0.0, 2.0); + assert_eq!(write(&mgr), ThrottleResult::Allowed); + consume_index_writes(&mgr, &[("b", 2.0), ("c", 0.5)]); + assert_eq!(write(&mgr), index_write("b")); + mgr.register_indexes( + "acct", + "tbl", + vec![index("c", 1, 1), index("a", 1, 1), index("b", 1, 1)], + ); + assert_eq!(write(&mgr), index_write("b")); +} + +/// Registration replaces the set: a kept name keeps its balance, a dropped +/// name is gone and a read naming it is served from the table, and a new name +/// has buckets of its own. +#[test] +fn register_indexes_replaces_the_set() { + let mgr = manager(1, 1, vec![index("kept", 1, 1), index("dropped", 1, 1)]); + consume_read(&mgr, 2.0, Some("kept")); + consume_read(&mgr, 2.0, Some("dropped")); + assert_eq!(read(&mgr, Some("kept")), index_read("kept")); + assert_eq!(read(&mgr, Some("dropped")), index_read("dropped")); + + mgr.register_indexes( + "acct", + "tbl", + vec![index("kept", 1, 1), index("added", 1, 1)], + ); + assert_eq!(read(&mgr, Some("kept")), index_read("kept")); + assert_eq!(read(&mgr, Some("dropped")), ThrottleResult::Allowed); + // The dropped name now reads from the table: draining the table refuses + // it with the table's cause. + consume_read(&mgr, 2.0, None); + assert_eq!( + read(&mgr, Some("dropped")), + ThrottleResult::ThrottledRead(table_cause()) + ); + assert_eq!(read(&mgr, Some("added")), ThrottleResult::Allowed); + consume_read(&mgr, 2.0, Some("added")); + assert_eq!(read(&mgr, Some("added")), index_read("added")); + + // An empty set removes every index. + mgr.register_indexes("acct", "tbl", Vec::new()); + assert_eq!( + read(&mgr, Some("kept")), + ThrottleResult::ThrottledRead(table_cause()) + ); +} + +/// A kept index takes the new rates. Its balance keeps the same fraction of +/// the burst window, so one second of 1 RCU (one token) becomes one second of +/// 1,000 RCU: a 500-unit read leaves it positive, where at the old rate it +/// would refuse. +#[test] +fn a_kept_index_takes_the_new_rate() { + let mgr = manager(1_000, 1_000, vec![index("gsi", 1, 1)]); + mgr.register_indexes("acct", "tbl", vec![index("gsi", 1_000, 1_000)]); + consume_read(&mgr, 500.0, Some("gsi")); + assert_eq!(read(&mgr, Some("gsi")), ThrottleResult::Allowed); + consume_index_writes(&mgr, &[("gsi", 500.0)]); + assert_eq!(write(&mgr), ThrottleResult::Allowed); +} + +/// `remove_table` drops the index buckets with the table's, so a table +/// created again under the name starts with none. +#[test] +fn remove_table_drops_the_index_buckets() { + let mgr = manager(1_000, 1_000, vec![index("gsi", 1, 1)]); + consume_index_writes(&mgr, &[("gsi", 2.0)]); + assert_eq!(write(&mgr), index_write("gsi")); + mgr.remove_table("acct", "tbl"); + mgr.register_table("acct", "tbl", TableThroughput::provisioned(1_000, 1_000)); + assert_eq!(write(&mgr), ThrottleResult::Allowed); +} + +/// A disabled manager allows every request and charges nothing: enabled +/// again, the buckets still hold their first second. +#[test] +fn a_disabled_manager_allows_and_charges_nothing() { + let mgr = manager(1, 1, vec![index("gsi", 1, 1)]); + mgr.set_enabled(false); + mgr.consume_with_partition("acct", "tbl", 2.0, 2.0, None, Some("gsi")); + consume_index_writes(&mgr, &[("gsi", 2.0)]); + assert_eq!(read(&mgr, Some("gsi")), ThrottleResult::Allowed); + assert_eq!(write(&mgr), ThrottleResult::Allowed); + mgr.set_enabled(true); + assert_eq!(read(&mgr, Some("gsi")), ThrottleResult::Allowed); + assert_eq!(write(&mgr), ThrottleResult::Allowed); +} + +/// Only an index cause names an index. +#[test] +fn only_an_index_cause_names_an_index() { + assert_eq!(table_cause().index_name(), None); + assert_eq!(ThrottleCause::Account.index_name(), None); + assert_eq!( + ThrottleCause::Partition { on_demand: true }.index_name(), + None + ); +} + +/// An index read skips only the table's read bucket: the account aggregate +/// is still checked and still charged. With a 1 RCU account limit, an index +/// read that drains it is refused by the account on the next check. +#[test] +fn an_index_read_is_checked_against_and_charged_to_the_account_bucket() { + let mgr = ThrottleManager::new(1, 1_000_000, true); + mgr.register_table( + "acct", + "tbl", + TableThroughput::provisioned(1_000_000, 1_000_000), + ); + mgr.register_indexes("acct", "tbl", vec![index("gsi", 1_000_000, 1_000_000)]); + assert_eq!(read(&mgr, Some("gsi")), ThrottleResult::Allowed); + consume_read(&mgr, 2.0, Some("gsi")); + assert_eq!( + read(&mgr, Some("gsi")), + ThrottleResult::ThrottledRead(ThrottleCause::Account) + ); +} + +/// The same for the partition bucket when a partition value is known. +#[test] +fn an_index_read_is_checked_against_and_charged_to_the_partition_bucket() { + // The table at 1 RCU: a 6,000 unit charge that reached its read bucket + // would refuse the final read. + let mgr = manager(1, 1_000_000, vec![index("gsi", 1_000_000, 1_000_000)]); + let check = + || mgr.check_capacity_with_partition("acct", "tbl", true, false, Some("k"), Some("gsi")); + assert_eq!(check(), ThrottleResult::Allowed); + mgr.consume_with_partition( + "acct", + "tbl", + PARTITION_RCU_LIMIT * 2.0, + 0.0, + Some("k"), + Some("gsi"), + ); + assert_eq!( + check(), + ThrottleResult::ThrottledRead(ThrottleCause::Partition { on_demand: false }) + ); + // The table's read bucket took none of it. + assert_eq!(read(&mgr, None), ThrottleResult::Allowed); + assert_eq!(read(&mgr, Some("gsi")), ThrottleResult::Allowed); +} diff --git a/crates/core/src/throttle/manager_tests.rs b/crates/core/src/throttle/manager_tests.rs new file mode 100644 index 000000000..56abd05ad --- /dev/null +++ b/crates/core/src/throttle/manager_tests.rs @@ -0,0 +1,94 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The manager's table and account buckets: the enabled switch, registration, +//! removal and the refusal each bucket gives. + +use super::*; + +#[test] +fn throttle_manager_allows_when_disabled() { + let mgr = ThrottleManager::new(100, 100, false); + mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); + assert_eq!( + mgr.check_capacity("acct", "tbl", true, false), + ThrottleResult::Allowed + ); +} + +#[test] +fn throttle_manager_allows_unregistered_table() { + let mgr = ThrottleManager::new(100, 100, true); + assert_eq!( + mgr.check_capacity("acct", "unknown", true, false), + ThrottleResult::Allowed + ); +} + +#[test] +fn throttle_manager_throttles_exhausted_table() { + let mgr = ThrottleManager::new(100_000, 100_000, true); + mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); + // Drain the table bucket (starts with 1 token = 1 second of 1 CU/s). + mgr.consume("acct", "tbl", 2.0, 0.0); + assert_eq!( + mgr.check_capacity("acct", "tbl", true, false), + ThrottleResult::ThrottledRead(ThrottleCause::Table { + on_demand: false, + capped: false, + }) + ); +} + +#[test] +fn throttle_manager_throttles_exhausted_writes() { + let mgr = ThrottleManager::new(100_000, 100_000, true); + mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); + mgr.consume("acct", "tbl", 0.0, 2.0); + assert_eq!( + mgr.check_capacity("acct", "tbl", false, true), + ThrottleResult::ThrottledWrite(ThrottleCause::Table { + on_demand: false, + capped: false, + }) + ); +} + +#[test] +fn throttle_manager_remove_table() { + let mgr = ThrottleManager::new(100_000, 100_000, true); + mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); + mgr.remove_table("acct", "tbl"); + // After removal, unregistered table is allowed. + assert_eq!( + mgr.check_capacity("acct", "tbl", true, true), + ThrottleResult::Allowed + ); +} + +#[test] +fn throttle_manager_account_level_throttle() { + let mgr = ThrottleManager::new(1, 1, true); + mgr.register_table( + "acct", + "tbl", + TableThroughput::provisioned(100_000, 100_000), + ); + // Table has plenty of capacity, but account limit is 1 CU/s. + // Drain account bucket (starts with 1 token). + mgr.consume("acct", "tbl", 2.0, 0.0); + assert_eq!( + mgr.check_capacity("acct", "tbl", true, false), + ThrottleResult::ThrottledRead(ThrottleCause::Account) + ); +} + +#[test] +fn on_demand_table_uses_default_ceilings() { + let mgr = ThrottleManager::new(100_000, 100_000, true); + mgr.register_table("acct", "tbl", TableThroughput::on_demand()); + // Should allow normal operations. + assert_eq!( + mgr.check_capacity("acct", "tbl", true, true), + ThrottleResult::Allowed + ); +} diff --git a/crates/core/src/types/table.rs b/crates/core/src/types/table.rs index 14aaf0d83..81fa4611c 100755 --- a/crates/core/src/types/table.rs +++ b/crates/core/src/types/table.rs @@ -1153,11 +1153,12 @@ pub struct DeleteGsiAction { /// Update an existing GSI. /// /// `WarmThroughput` is stored and reported (see [`super::WarmThroughputRecord`]). -/// `ProvisionedThroughput` and `OnDemandThroughput` are recognized by the -/// deserializer but an update of either is not yet implemented: they are read -/// as opaque values only so that the engine refuses an `Update` carrying -/// either, with or without `WarmThroughput`, instead of accepting it and -/// dropping the member. +/// `ProvisionedThroughput` is stored as the index's throughput on a table +/// that is PROVISIONED before and after the request. Both throughput members +/// are read as opaque values, so that the engine answers a malformed one +/// with the service's member-path sentence and refuses an `Update` carrying +/// `OnDemandThroughput`, with or without `WarmThroughput`, instead of +/// accepting it and dropping the member. #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct UpdateGsiAction { #[serde(rename = "IndexName")] @@ -1172,11 +1173,19 @@ pub struct UpdateGsiAction { impl UpdateGsiAction { /// Whether the action carries `ProvisionedThroughput` or - /// `OnDemandThroughput`, which ExtendDB does not apply to an index. + /// `OnDemandThroughput`. #[must_use] pub fn carries_throughput(&self) -> bool { self.provisioned_throughput.is_some() || self.on_demand_throughput.is_some() } + + /// The action's `ProvisionedThroughput`, or `None` when it carries none or + /// one that is not a throughput (which the engine refuses before a backend + /// sees the request). + #[must_use] + pub fn provisioned_throughput_units(&self) -> Option { + serde_json::from_value(self.provisioned_throughput.clone()?).ok() + } } /// `UpdateTable` request body. diff --git a/crates/engine/src/delete_item.rs b/crates/engine/src/delete_item.rs index 87948198d..92b5f7101 100755 --- a/crates/engine/src/delete_item.rs +++ b/crates/engine/src/delete_item.rs @@ -168,9 +168,12 @@ pub async fn handle_delete_item( let need_old_for_stream = stream.is_some(); // Consumed capacity — when requested, the total includes base + affected // GSIs; INDEXES additionally returns the per-index breakdown. The deleted - // (old) item is needed to determine which indexes the delete propagated to. - let need_old_for_capacity = - input.return_consumed_capacity != extenddb_core::types::ReturnConsumedCapacity::None; + // (old) item is needed to determine which indexes the delete propagated + // to, and so is it for the server's charge to each global secondary index + // the delete touched. + let need_old_for_capacity = input.return_consumed_capacity + != extenddb_core::types::ReturnConsumedCapacity::None + || !key_info.global_secondary_indexes.is_empty(); let old_item = ctx .storage @@ -214,6 +217,8 @@ pub async fn handle_delete_item( capacity_helpers::write_capacity(input.return_consumed_capacity, &input.table_name, wcu) } }; + let index_write_units = + capacity_helpers::index_write_units(old_item.as_ref(), None, false, &key_info).0; let output = DeleteItemOutput { attributes: if return_old { old_item } else { None }, @@ -230,6 +235,7 @@ pub async fn handle_delete_item( body, metrics: DispatchMetrics { write_capacity_units: wcu, + index_write_units, ..Default::default() }, }) diff --git a/crates/engine/src/gsi_updates.rs b/crates/engine/src/gsi_updates.rs index a89e39f52..075d66700 100644 --- a/crates/engine/src/gsi_updates.rs +++ b/crates/engine/src/gsi_updates.rs @@ -26,11 +26,22 @@ //! at all: "The only Updates for index: when TableThroughputMode is //! PAY_PER_REQUEST can be to OnDemandThroughput, WarmThroughput" (T3d, //! T3e). The stored billing mode is known only once the table is read, so -//! [`refuse_bare_updates`] runs after the read. ExtendDB does not change an -//! index's throughput, so every other `Update` without `WarmThroughput` (one -//! carrying only `OnDemandThroughput`, any on a provisioned table, the -//! index update of a switch to PROVISIONED) is refused as not yet -//! supported, as before this rule existed. +//! [`refuse_bare_updates`] runs after the read. An `Update` carrying +//! `ProvisionedThroughput` and no `OnDemandThroughput` on a table that is +//! PROVISIONED before and after the request is applied: the backend stores +//! it as the index's throughput, and the server's index buckets take the +//! new rate from the response. Every other `Update` without +//! `WarmThroughput` (one carrying `OnDemandThroughput` on a provisioned +//! table, the index update of a switch to PROVISIONED) is refused as not +//! yet supported, as before this rule existed. +//! - The units of an `Update`'s `ProvisionedThroughput` (measured 2026-11-25 +//! on a table name that does not exist, each request twice): a missing or +//! null unit is `Value null at '' failed to satisfy constraint: Member +//! must not be null`, a unit below 1 is `Value '' at '' failed to +//! satisfy constraint: Member must have value greater than or equal to 1`, +//! with `` +//! `globalSecondaryIndexUpdates..member.update.provisionedThroughput.`, +//! the write units listed before the read units, ahead of the table read. //! //! A `Create` has a valid name, a key schema of defined attributes, and (when //! given) a throughput of at least 1 unit each; a `Delete` has a valid name. @@ -71,9 +82,8 @@ pub fn index_warm_throughput_only_operation(name: &str) -> String { } /// Whether any `Update` element carries no `WarmThroughput`: nothing but its -/// index name, or a throughput ExtendDB does not apply to an index. Such an -/// element needs the table's billing mode for its sentence, so the caller -/// reads the table first. +/// index name, or a throughput. Such an element needs the table's billing +/// mode for its answer, so the caller reads the table first. #[must_use] pub(crate) fn has_bare_update(input: &UpdateTableInput) -> bool { input @@ -87,15 +97,18 @@ pub(crate) fn has_bare_update(input: &UpdateTableInput) -> bool { }) } -/// Refuse every `Update` element that carries no `WarmThroughput`. -/// `pay_per_request` is the billing mode the table has after the request: the -/// request's `BillingMode` when it carries one, the stored mode otherwise. +/// Refuse every `Update` element that carries no `WarmThroughput`, except one +/// carrying `ProvisionedThroughput` and no `OnDemandThroughput` on a table +/// that `stays_provisioned` (PROVISIONED before and after the request), which +/// the backend stores. `pay_per_request` is the billing mode the table has +/// after the request: the request's `BillingMode` when it carries one, the +/// stored mode otherwise. /// /// Under PAY_PER_REQUEST an element carrying `ProvisionedThroughput` or /// nothing at all answers the measured sentence (rows T3d, T3e). Every other -/// such element (only `OnDemandThroughput`, which that sentence names as -/// allowed, or any element under PROVISIONED, where the service changes the -/// index's throughput) answers ExtendDB's own "not yet supported". +/// refused element (only `OnDemandThroughput`, which that sentence names as +/// allowed, or any other element under PROVISIONED) answers ExtendDB's own +/// "not yet supported". /// /// # Errors /// @@ -103,13 +116,19 @@ pub(crate) fn has_bare_update(input: &UpdateTableInput) -> bool { pub(crate) fn refuse_bare_updates( input: &UpdateTableInput, pay_per_request: bool, + stays_provisioned: bool, ) -> Result<(), DynamoDbError> { if let Some(upd) = input .global_secondary_index_updates .iter() .flatten() .filter_map(|u| u.update.as_ref()) - .find(|a| a.warm_throughput.is_none()) + .find(|a| { + let stored = stays_provisioned + && a.provisioned_throughput.is_some() + && a.on_demand_throughput.is_none(); + a.warm_throughput.is_none() && !stored + }) { let on_demand_rule = upd.provisioned_throughput.is_some() || upd.on_demand_throughput.is_none(); @@ -163,6 +182,50 @@ fn validate_update_index_name( } } +/// The units of the `ProvisionedThroughput` of the `Update` at `position` +/// (0-based): each one present, as an integer of at least 1, answered with +/// the measured member-path clauses, the write units first (module doc). A +/// member that is not an object or a unit that is not an integer is answered +/// as the request's deserializer answers a malformed throughput. +fn validate_update_throughput( + throughput: &serde_json::Value, + position: usize, +) -> Result<(), DynamoDbError> { + let mut clauses = Vec::new(); + if throughput.is_object() { + for (key, member) in [ + ("WriteCapacityUnits", "writeCapacityUnits"), + ("ReadCapacityUnits", "readCapacityUnits"), + ] { + let path = format!( + "globalSecondaryIndexUpdates.{}.member.update.provisionedThroughput.{member}", + position + 1 + ); + match throughput.get(key) { + None | Some(serde_json::Value::Null) => clauses.push(format!( + "Value null at '{path}' failed to satisfy constraint: Member must not be null" + )), + Some(units) => { + if let Some(n) = units.as_i64().filter(|n| *n < 1) { + clauses.push(format!( + "Value '{n}' at '{path}' failed to satisfy constraint: Member must \ + have value greater than or equal to 1" + )); + } + } + } + } + } + if !clauses.is_empty() { + return Err(DynamoDbError::ValidationException( + extenddb_core::error::validation_errors_detected(&clauses), + )); + } + serde_json::from_value::(throughput.clone()) + .map(drop) + .map_err(crate::deserialize_error) +} + /// Apply the element rules to `input`. /// /// # Errors @@ -224,6 +287,9 @@ pub(crate) fn validate_gsi_updates(input: &UpdateTableInput) -> Result<(), Dynam index_warm_throughput_only_operation(&upd.index_name), )); } + if let Some(throughput) = &upd.provisioned_throughput { + validate_update_throughput(throughput, position)?; + } } // Create and Delete names are validated the way CreateTable does, // except that the pattern clause carries the member's path (measured @@ -290,6 +356,11 @@ mod tests { } } + /// The `ValidationException` text of a refusal, `None` when accepted. + fn refusal(result: Result<(), DynamoDbError>) -> Option { + result.is_err().then(|| message(result)) + } + fn create(name: &str) -> Value { json!({ "Create": { "IndexName": name, @@ -397,9 +468,10 @@ mod tests { /// An Update without WarmThroughput: on an on-demand table one carrying /// ProvisionedThroughput or nothing answers the measured sentence (rows - /// T3d, T3e); one carrying only OnDemandThroughput, and every one on a - /// provisioned table (the index update of a switch to PROVISIONED - /// included), answers ExtendDB's "not yet supported". + /// T3d, T3e); on a provisioned table one carrying ProvisionedThroughput + /// alone is accepted (`None`), and one carrying only OnDemandThroughput + /// or nothing answers ExtendDB's "not yet supported", as does any on an + /// on-demand table carrying only OnDemandThroughput. #[test] fn an_update_without_warm_throughput_answers_by_the_billing_mode_after_the_request() { let provisioned = json!({ "ReadCapacityUnits": 3, "WriteCapacityUnits": 3 }); @@ -407,7 +479,8 @@ mod tests { let on_demand_sentence = "One or more parameter values were invalid: The only Updates \ for index: gsi when TableThroughputMode is PAY_PER_REQUEST can be to \ OnDemandThroughput, WarmThroughput"; - let not_yet = "UpdateGlobalSecondaryIndex is not yet supported"; + let not_yet = Some("UpdateGlobalSecondaryIndex is not yet supported"); + let on_demand_sentence = Some(on_demand_sentence); for (update, pay_per_request, expected) in [ (json!({ "IndexName": "gsi" }), true, on_demand_sentence), ( @@ -429,6 +502,11 @@ mod tests { ( json!({ "IndexName": "gsi", "ProvisionedThroughput": provisioned }), false, + None, + ), + ( + json!({ "IndexName": "gsi", "ProvisionedThroughput": provisioned, "OnDemandThroughput": on_demand }), + false, not_yet, ), ( @@ -441,13 +519,89 @@ mod tests { validate_gsi_updates(&request).expect("the element rules pass; the mode decides"); assert!(has_bare_update(&request)); assert_eq!( - message(refuse_bare_updates(&request, pay_per_request)), - expected, + refusal(refuse_bare_updates( + &request, + pay_per_request, + !pay_per_request + )), + expected.map(str::to_owned), "{update} pay_per_request={pay_per_request}" ); } } + /// The units of an Update's ProvisionedThroughput, measured 2026-11-25 on + /// a table name that does not exist (each request twice): each row the + /// throughput sent and the answer, or `None` for none (the service then + /// answered ResourceNotFoundException). + #[test] + fn an_update_throughput_is_checked_with_the_measured_member_sentences() { + let at = |unit: &str| { + format!("'globalSecondaryIndexUpdates.1.member.update.provisionedThroughput.{unit}'") + }; + let below = |n: i64, unit: &str| { + format!( + "1 validation error detected: Value '{n}' at {} failed to satisfy constraint: \ + Member must have value greater than or equal to 1", + at(unit) + ) + }; + let null = |unit: &str| { + format!( + "Value null at {} failed to satisfy constraint: Member must not be null", + at(unit) + ) + }; + let rows = [ + ( + json!({ "ReadCapacityUnits": 5, "WriteCapacityUnits": 5 }), + None, + ), + ( + json!({ "ReadCapacityUnits": 1_000_000_000, "WriteCapacityUnits": 5 }), + None, + ), + ( + json!({ "ReadCapacityUnits": 0, "WriteCapacityUnits": 5 }), + Some(below(0, "readCapacityUnits")), + ), + ( + json!({ "ReadCapacityUnits": 5, "WriteCapacityUnits": 0 }), + Some(below(0, "writeCapacityUnits")), + ), + ( + json!({ "ReadCapacityUnits": -1, "WriteCapacityUnits": 5 }), + Some(below(-1, "readCapacityUnits")), + ), + ( + json!({ "ReadCapacityUnits": 5 }), + Some(format!( + "1 validation error detected: {}", + null("writeCapacityUnits") + )), + ), + ( + json!({}), + Some(format!( + "2 validation errors detected: {}; {}", + null("writeCapacityUnits"), + null("readCapacityUnits") + )), + ), + ]; + for (throughput, expected) in rows { + let request = input(json!([{ "Update": { + "IndexName": "gsi", + "ProvisionedThroughput": throughput, + }}])); + assert_eq!( + refusal(validate_gsi_updates(&request)), + expected, + "{throughput}" + ); + } + } + /// The mode an Update without WarmThroughput is answered by is the one the /// table has after the request. On a PAY_PER_REQUEST table the switch to /// PROVISIONED that the service requires (BillingMode PROVISIONED, the @@ -475,7 +629,8 @@ mod tests { assert_eq!( message(refuse_bare_updates( &switch, - pay_per_request_after(&switch, Some(&stored)) + pay_per_request_after(&switch, Some(&stored)), + false )), "UpdateGlobalSecondaryIndex is not yet supported" ); @@ -484,7 +639,8 @@ mod tests { assert_eq!( message(refuse_bare_updates( &stay, - pay_per_request_after(&stay, Some(&stored)) + pay_per_request_after(&stay, Some(&stored)), + false )), "One or more parameter values were invalid: The only Updates for index: gsi when \ TableThroughputMode is PAY_PER_REQUEST can be to OnDemandThroughput, WarmThroughput" @@ -502,12 +658,12 @@ mod tests { assert!(has_bare_update(&bare)); assert!(!has_bare_update(&input(json!([warm_update("gsi")])))); assert_eq!( - message(refuse_bare_updates(&bare, true)), + message(refuse_bare_updates(&bare, true, false)), "One or more parameter values were invalid: The only Updates for index: gsi when \ TableThroughputMode is PAY_PER_REQUEST can be to OnDemandThroughput, WarmThroughput" ); - assert!(message(refuse_bare_updates(&bare, false)).contains("not yet supported")); - refuse_bare_updates(&input(json!([warm_update("gsi")])), true).expect("warm update"); + assert!(message(refuse_bare_updates(&bare, false, true)).contains("not yet supported")); + refuse_bare_updates(&input(json!([warm_update("gsi")])), true, false).expect("warm update"); } #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ad3367116..ec93d8973 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -384,6 +384,12 @@ pub struct DispatchMetrics { /// GSI/LSI name when the operation targets a secondary index. /// Used to attribute metrics to the specific index. pub index_name: Option, + /// The write units each global secondary index of the table consumed, by + /// index name: only an index the old or the new item projects into, as + /// `capacity_helpers::index_write_units` counts them. Filled by + /// `PutItem`, `UpdateItem` and `DeleteItem`, the writes the server's + /// throttle buckets see; empty for any other operation. + pub index_write_units: std::collections::HashMap, /// The requests or keys a backend throttled in a batch that answered 200, /// counted per table by its catalog name. The server records each count /// as read or write throttle events: its own bucket never saw them. diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index 39b708ea0..c26c4ee2c 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -224,10 +224,13 @@ pub async fn handle_put_item( let return_old = input.return_values == ReturnValues::AllOld; let capacity_requested = input.return_consumed_capacity != extenddb_core::types::ReturnConsumedCapacity::None; - let needs_index_capacity = capacity_requested - && (!key_info.global_secondary_indexes.is_empty() - || !key_info.local_secondary_indexes.is_empty() - || !key_info.vector_indexes.is_empty()); + // The server charges a write to each global secondary index the write + // touched, so a table with one needs the old and the new item. + let has_gsi = !key_info.global_secondary_indexes.is_empty(); + let needs_index_capacity = has_gsi + || (capacity_requested + && (!key_info.local_secondary_indexes.is_empty() + || !key_info.vector_indexes.is_empty())); // Preserve the new item only when per-index accounting needs to compare it // with the replaced item after storage takes ownership. @@ -254,7 +257,7 @@ pub async fn handle_put_item( // deleted by an overwrite, so request the old item whenever capacity is // requested. Indexed writes already read it inside the storage transaction. let need_old_for_stream = stream.is_some(); - let need_old_for_capacity = capacity_requested; + let need_old_for_capacity = capacity_requested || has_gsi; let old_item = ctx .storage @@ -294,6 +297,13 @@ pub async fn handle_put_item( capacity_helpers::write_capacity(input.return_consumed_capacity, &input.table_name, wcu) } }; + let index_write_units = capacity_helpers::index_write_units( + old_item.as_ref(), + new_item_for_capacity.as_ref(), + false, + &key_info, + ) + .0; let output = PutItemOutput { attributes: if return_old { old_item } else { None }, @@ -305,6 +315,7 @@ pub async fn handle_put_item( body, metrics: DispatchMetrics { write_capacity_units: wcu, + index_write_units, ..Default::default() }, }) diff --git a/crates/engine/src/update_item.rs b/crates/engine/src/update_item.rs index 3014a3d52..6e0eec59b 100755 --- a/crates/engine/src/update_item.rs +++ b/crates/engine/src/update_item.rs @@ -298,8 +298,11 @@ pub(crate) async fn handle_update_item_with( region: ctx.region.clone(), }); let need_old_for_stream = stream.is_some(); - let need_old_for_capacity = - input.return_consumed_capacity != extenddb_core::types::ReturnConsumedCapacity::None; + // The server charges a write to each global secondary index the write + // touched, which the old item decides as much as the new one. + let need_old_for_capacity = input.return_consumed_capacity + != extenddb_core::types::ReturnConsumedCapacity::None + || !key_info.global_secondary_indexes.is_empty(); let (old_item, new_item) = ctx .storage @@ -338,6 +341,9 @@ pub(crate) async fn handle_update_item_with( false, &key_info, ); + let index_write_units = + capacity_helpers::index_write_units(old_item.as_ref(), new_item.as_ref(), false, &key_info) + .0; // Select the appropriate return value. // UPDATED_OLD and UPDATED_NEW return only the attributes that were @@ -369,6 +375,7 @@ pub(crate) async fn handle_update_item_with( body, metrics: DispatchMetrics { write_capacity_units: wcu, + index_write_units, ..Default::default() }, }) diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index c30b1193c..75ad945c4 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -242,7 +242,27 @@ pub async fn handle_update_table( &input, existing.billing_mode_summary.as_ref(), ); - crate::gsi_updates::refuse_bare_updates(&input, pay_per_request)?; + let stored_on_demand = existing + .billing_mode_summary + .as_ref() + .is_some_and(|s| s.billing_mode == BillingMode::PayPerRequest); + crate::gsi_updates::refuse_bare_updates( + &input, + pay_per_request, + !pay_per_request && !stored_on_demand, + )?; + // An index throughput the backend stores names an index of the + // table, checked here before any backend write, as for + // WarmThroughput. + for upd in input + .global_secondary_index_updates + .iter() + .flatten() + .filter_map(|u| u.update.as_ref()) + .filter(|u| u.provisioned_throughput.is_some()) + { + crate::warm_throughput::gsi_named(&existing, &upd.index_name, &input.table_name)?; + } } if touches_warm { crate::warm_throughput::validate_warm_throughput_updates(&input, &existing)?; diff --git a/crates/engine/src/warm_throughput.rs b/crates/engine/src/warm_throughput.rs index 6434be79c..dbe23b4e7 100644 --- a/crates/engine/src/warm_throughput.rs +++ b/crates/engine/src/warm_throughput.rs @@ -12,8 +12,8 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::types::{ - BillingMode, ON_DEMAND_WARM_READ_UNITS, ON_DEMAND_WARM_WRITE_UNITS, TableDescription, - UpdateTableInput, WarmThroughput, WarmThroughputDefaults, epoch_seconds_now, + BillingMode, GsiDescription, ON_DEMAND_WARM_READ_UNITS, ON_DEMAND_WARM_WRITE_UNITS, + TableDescription, UpdateTableInput, WarmThroughput, WarmThroughputDefaults, epoch_seconds_now, }; use extenddb_core::validation::{ WarmThroughputSubject, validate_created_gsi_warm_throughput, validate_warm_throughput_on_update, @@ -136,6 +136,25 @@ pub(crate) fn on_demand_switch_warm_throughput( }) } +/// The table's global secondary index `name`, or the service's +/// `ResourceNotFoundException` for an `Update` naming one the table does not have. +pub(crate) fn gsi_named<'a>( + existing: &'a TableDescription, + name: &str, + table_name: &str, +) -> Result<&'a GsiDescription, DynamoDbError> { + existing + .global_secondary_indexes + .iter() + .flatten() + .find(|g| g.index_name == name) + .ok_or_else(|| { + DynamoDbError::ResourceNotFoundException(format!( + "Requested resource not found: Index {name} for table {table_name}" + )) + }) +} + /// Apply the measured update rules to `input` against `existing`: /// /// - the table's `WarmThroughput` may not go below its current values @@ -168,17 +187,7 @@ pub(crate) fn validate_warm_throughput_updates( if let Some(update) = &action.update && let Some(spec) = &update.warm_throughput { - let gsi = existing - .global_secondary_indexes - .iter() - .flatten() - .find(|g| g.index_name == update.index_name) - .ok_or_else(|| { - DynamoDbError::ResourceNotFoundException(format!( - "Requested resource not found: Index {} for table {}", - update.index_name, input.table_name - )) - })?; + let gsi = gsi_named(existing, &update.index_name, &input.table_name)?; let (rcu, wcu) = gsi.provisioned_throughput.as_ref().map_or((0, 0), |pt| { (pt.read_capacity_units, pt.write_capacity_units) }); @@ -322,6 +331,21 @@ mod tests { )); } + /// An `Update` of `missing` on a provisioned table with the index `gsi`. + #[test] + fn an_update_naming_no_index_of_the_table_is_not_found() { + let existing = TableDescription { + global_secondary_indexes: on_demand_table(None).global_secondary_indexes, + ..provisioned_table(5, None) + }; + let err = gsi_named(&existing, "missing", "t").expect_err("no such index"); + assert!( + matches!(&err, DynamoDbError::ResourceNotFoundException(m) + if m == "Requested resource not found: Index missing for table t"), + "{err:?}" + ); + } + /// A created index's WarmThroughput follows the create rule under the /// table's billing mode. #[test] diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 82e791210..08a31289d 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -19,11 +19,12 @@ use crate::request_helpers::{ }; use crate::response::{error_response, record_error_metrics, success_response}; use crate::throttle_helpers::{ - batch_entry_counts, classify_data_operation, extract_partition_value, - record_partial_batch_throttle, table_description_to_throughput, throttle_error, + batch_entry_counts, extract_index_name, extract_partition_value, record_partial_batch_throttle, update_throttle_buckets, }; +mod throttle_segment; + /// Main Virtual `DynamoDB` request handler. /// REQ-WIRE-001: Accept HTTP POST to `/`. /// REQ-WIRE-002: Parse X-Amz-Target header. @@ -152,6 +153,7 @@ pub(crate) async fn handle_request( table_name, metric_table, partition_value, + index_name, batch_entries, dispatch_result, auth_us, @@ -250,7 +252,11 @@ pub(crate) async fn handle_request( m.read_capacity_units, m.write_capacity_units, partition_value.as_deref(), + index_name.as_deref(), ); + state + .throttle + .consume_index_writes(&account_id, tn, &m.index_write_units); } succeeded = true; @@ -387,6 +393,9 @@ struct Served { table_name: Option, metric_table: Option, partition_value: Option, + /// The index a `Query` or `Scan` named, charged in place of the table on + /// a read when it is a provisioned global secondary index. + index_name: Option, /// The entries of a batch by table, for the throttle events of a batch /// whose every entry a backend throttled; `None` for any other request. batch_entries: Option>, @@ -524,83 +533,18 @@ async fn serve_request( // --- Throttle segment --- let throttle_start = std::time::Instant::now(); - let (is_read_op, is_write_op) = classify_data_operation(operation); let partition_value = extract_partition_value(&input, operation); - // A name the table name rules refuse (length or pattern), and the ARN of - // a table in another Region, are not throttled: the engine answers them - // as it does with capacity left. The service refuses such a name before - // any throttle (measured 2026-11-25 with GetItem and PutItem on `ab`, an - // empty name, 256 characters and the ARN of a table in another Region). - // The ARN of a table in this account and Region is checked by the name it - // carries, and a throttle refusal names that table. - if let Some(ref tn) = table_name - && (is_read_op || is_write_op) - && let name = crate::authz_resource::key_lookup_name(tn, &state.region, &ctx.account_id) - && extenddb_core::validation::validate_table_name(&name, &state.limits).is_ok() - { - if !state.throttle.is_registered(&ctx.account_id, tn) - && let Ok(desc) = ctx - .storage - .describe_table( - &ctx.account_id, - extenddb_core::types::DescribeTableInput { - table_name: tn.clone(), - }, - ) - .await - { - let throughput = table_description_to_throughput(&desc); - state - .throttle - .register_table(&ctx.account_id, tn, throughput); - } - - let result = state.throttle.check_capacity_with_partition( - &ctx.account_id, - tn, - is_read_op, - is_write_op, - partition_value.as_deref(), - ); - if let Some(cause) = result.cause() { - let throttled_read = matches!( - result, - extenddb_core::throttle::ThrottleResult::ThrottledRead(_) - ); - let metric = if throttled_read { - extenddb_core::metrics::MetricName::ReadThrottleEvents - } else { - extenddb_core::metrics::MetricName::WriteThrottleEvents - }; - state.metrics.record( - metric, - 1.0, - Some(&ctx.account_id), - metric_table.as_deref(), - None, - Some(operation), - ); - state.metrics.record( - extenddb_core::metrics::MetricName::ThrottledRequests, - 1.0, - Some(&ctx.account_id), - metric_table.as_deref(), - None, - Some(operation), - ); - // The service names the throttled resource and the limit on a - // throttle: one reason with the table ARN, the same string - // DescribeTable returns as TableArn. The error class, the message - // and the limit follow the bucket that refused and the table's - // billing mode. - let table_arn = - extenddb_storage::util::table_arn(&state.region, &ctx.account_id, &name); - return Err(Refused { - error: throttle_error(cause, throttled_read, &table_arn), - account_id: Some(ctx.account_id.to_string()), - }); - } - } + let index_name = extract_index_name(&input, operation); + throttle_segment::check( + state, + &ctx, + operation, + table_name.as_deref(), + metric_table.as_deref(), + partition_value.as_deref(), + index_name.as_deref(), + ) + .await?; #[allow(clippy::cast_precision_loss)] let throttle_us = throttle_start.elapsed().as_micros() as f64; @@ -644,6 +588,7 @@ async fn serve_request( table_name, metric_table, partition_value, + index_name, batch_entries, dispatch_result, auth_us, @@ -695,3 +640,6 @@ mod request_scope_tests; mod start_server_tests; #[cfg(test)] mod throttle_wire_tests; + +#[cfg(test)] +mod index_throttle_wire_tests; diff --git a/crates/server/src/handler/index_throttle_wire_tests.rs b/crates/server/src/handler/index_throttle_wire_tests.rs new file mode 100644 index 000000000..e683495b3 --- /dev/null +++ b/crates/server/src/handler/index_throttle_wire_tests.rs @@ -0,0 +1,513 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The server's refusal on a provisioned global secondary index's own +//! capacity, driven through `handle_request` against an in-memory engine: the +//! two measured bodies and the metric records they leave, the index ARN they +//! name, the write charged to an index only when its item carries the index +//! key, the local secondary index served from the table's buckets, the index +//! deleted by `UpdateTable`, the index raised by `UpdateTable`, the index set +//! kept across a table throughput update, the index read that does not +//! consult the table's read bucket, and the registration of the indexes on +//! the first request after a restart. + +use std::sync::Arc; + +use extenddb_core::error::{ + INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, +}; +use extenddb_core::metrics::{Dimension, MetricName, MetricsQuery, TimeWindow}; +use serde_json::{Value, json}; + +use super::throttle_wire_tests::{arn, build_state, call, create_table, item}; +use crate::AppState; + +const GSI: &str = "by-g"; +const LSI: &str = "by-l"; + +/// The units a test drains a 1-unit bucket by: a debt of 999 seconds at that +/// rate, so no delay in a run refills it before the request under test, and +/// far less than one second of the account's aggregate, which a read drain +/// is charged to as well. +const DRAIN: f64 = 1_000.0; + +/// A provisioned table with a sort key, one global secondary index at +/// `index_rcu` and `index_wcu`, and one local secondary index. +async fn create_indexed_table( + state: &Arc, + table: &str, + table_rcu: i64, + table_wcu: i64, + index_rcu: i64, + index_wcu: i64, +) { + create_table( + state, + table, + json!({ + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"}, + {"AttributeName": "l", "AttributeType": "S"}, + ], + "ProvisionedThroughput": { + "ReadCapacityUnits": table_rcu, + "WriteCapacityUnits": table_wcu, + }, + "GlobalSecondaryIndexes": [{ + "IndexName": GSI, + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + "ProvisionedThroughput": { + "ReadCapacityUnits": index_rcu, + "WriteCapacityUnits": index_wcu, + }, + }], + "LocalSecondaryIndexes": [{ + "IndexName": LSI, + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "l", "KeyType": "RANGE"}, + ], + "Projection": {"ProjectionType": "ALL"}, + }], + }), + ) + .await; +} + +fn index_arn(account_id: &str, table: &str, index: &str) -> String { + format!("{}/index/{index}", arn(account_id, table)) +} + +fn query(table: &str, index: &str, key: &str) -> Value { + json!({ + "TableName": table, + "IndexName": index, + "KeyConditionExpression": format!("{key} = :v"), + "ExpressionAttributeValues": {":v": {"S": "k"}}, + }) +} + +/// The `(metric, dimensions, sum)` throttle records the collector holds for +/// `table` in the last minute, sorted, for an assertion on what a refusal +/// recorded. +fn throttle_records(state: &AppState, table: &str) -> Vec<(MetricName, Vec, f64)> { + let mut records: Vec<_> = state + .metrics + .query(&MetricsQuery { + table_name: Some(table.to_owned()), + window: Some(TimeWindow::LastMinute), + ..MetricsQuery::default() + }) + .into_iter() + .filter(|s| { + matches!( + s.metric, + MetricName::ReadThrottleEvents + | MetricName::WriteThrottleEvents + | MetricName::ThrottledRequests + ) + }) + .map(|s| (s.metric, s.dimensions, s.sum)) + .collect(); + records.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + records +} + +/// The dimensions of a throttle record: the account, the table, the index +/// when there is one, and the operation. +fn dims(account: &str, table: &str, index: Option<&str>, op: &str) -> Vec { + let mut dims = vec![ + Dimension::AccountId(account.to_owned()), + Dimension::TableName(table.to_owned()), + ]; + dims.extend(index.map(|i| Dimension::GlobalSecondaryIndexName(i.to_owned()))); + dims.push(Dimension::Operation(op.to_owned())); + dims +} + +fn indexed_item() -> Value { + let mut it = item(16); + it["sk"] = json!({"S": "s"}); + it["g"] = json!({"S": "k"}); + it["l"] = json!({"S": "k"}); + it +} + +/// A `Query` naming the index past its read capacity is refused with the +/// provisioned class, the table message and one reason naming the index ARN, +/// the same string `DescribeTable` returns as the index's `IndexArn`. +#[tokio::test] +async fn index_read_throttle_names_the_index_arn_with_the_table_message() { + let (state, account_id) = build_state().await; + let table = "index-reads"; + create_indexed_table(&state, table, 1000, 1000, 1, 1).await; + let (_, described) = call(&state, "DescribeTable", json!({"TableName": table})).await; + let described_arn = described["Table"]["GlobalSecondaryIndexes"][0]["IndexArn"] + .as_str() + .expect("IndexArn") + .to_owned(); + assert_eq!(described_arn, index_arn(&account_id, table, GSI)); + // Drained directly, by far more than the index's one second of burst at + // 1 RCU (see `DRAIN`). + state + .throttle + .consume_with_partition(&account_id, table, DRAIN, 0.0, None, Some(GSI)); + let (status, body) = call(&state, "Query", query(table, GSI, "g")).await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body, + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#ProvisionedThroughputExceededException", + "message": PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + "ThrottlingReasons": [{ + "reason": "IndexReadProvisionedThroughputExceeded", + "resource": described_arn, + }], + }) + ); + // Scan naming the index is refused the same way. + let (status, body) = call( + &state, + "Scan", + json!({"TableName": table, "IndexName": GSI}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["ThrottlingReasons"][0]["reason"], + "IndexReadProvisionedThroughputExceeded" + ); + // The throttle event carries the index as its dimension; the request + // count carries the account, the table and the operation, and no index. + let mut expected = Vec::new(); + for op in ["Query", "Scan"] { + let index = dims(&account_id, table, Some(GSI), op); + expected.push((MetricName::ReadThrottleEvents, index, 1.0)); + let table_only = dims(&account_id, table, None, op); + expected.push((MetricName::ThrottledRequests, table_only, 1.0)); + } + expected.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + assert_eq!(throttle_records(&state, table), expected); +} + +/// A write to the base table held back by the index's write capacity, while +/// the table's own capacity is large, carries the index message (no trailing +/// period) and the index ARN. +#[tokio::test] +async fn index_write_throttle_names_the_index_message_and_arn() { + let (state, account_id) = build_state().await; + let table = "index-writes"; + create_indexed_table(&state, table, 1000, 1000, 1, 1).await; + // The index's write bucket drained directly (see `DRAIN`); the table at + // 1000 WCU keeps capacity. + drain_index_writes(&state, &account_id, table); + // The segment throttles a request with a top-level `TableName`; a + // `BatchWriteItem` or `TransactWriteItems` names its tables per item and + // is not checked here, as before this change. + for operation in ["PutItem", "UpdateItem", "DeleteItem"] { + let body = match operation { + "PutItem" => json!({"TableName": table, "Item": indexed_item()}), + "UpdateItem" => json!({ + "TableName": table, + "Key": {"pk": {"S": "k"}, "sk": {"S": "s"}}, + "UpdateExpression": "SET v = :v", + "ExpressionAttributeValues": {":v": {"S": "x"}}, + }), + _ => json!({ + "TableName": table, + "Key": {"pk": {"S": "k"}, "sk": {"S": "s"}}, + }), + }; + let (status, got) = call(&state, operation, body).await; + assert_eq!(status, 400, "{operation}: {got}"); + assert_eq!( + got, + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#ProvisionedThroughputExceededException", + "message": INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + "ThrottlingReasons": [{ + "reason": "IndexWriteProvisionedThroughputExceeded", + "resource": index_arn(&account_id, table, GSI), + }], + }), + "{operation}" + ); + } + assert!( + !INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE.ends_with('.'), + "the index write message carries no trailing period" + ); + // Each refusal is a throttle event of the index and of the table: the + // service publishes WriteThrottleEvents for both series on an index write + // refusal. The request count carries no index. + let mut expected = Vec::new(); + for op in ["PutItem", "UpdateItem", "DeleteItem"] { + let index = dims(&account_id, table, Some(GSI), op); + let table_only = dims(&account_id, table, None, op); + expected.push((MetricName::WriteThrottleEvents, index, 1.0)); + expected.push((MetricName::WriteThrottleEvents, table_only.clone(), 1.0)); + expected.push((MetricName::ThrottledRequests, table_only, 1.0)); + } + expected.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + assert_eq!(throttle_records(&state, table), expected); +} + +/// A write is charged to an index only when its item carries the index's +/// key, as the service charges it. Each row: an item and the reason of the +/// first refusal. On a table at 3 WCU with the index at 1 WCU, 2 KB items +/// without the index key are served until the table's capacity is gone and +/// then refused with the table reason; the same items with the key drain the +/// index on the first write and the second is refused with the index reason. +#[tokio::test] +async fn a_write_is_charged_to_an_index_only_when_its_item_carries_the_index_key() { + let (state, _) = build_state().await; + let mut without_key = item(2_000); + without_key["sk"] = json!({"S": "s"}); + let mut with_key = without_key.clone(); + with_key["g"] = json!({"S": "k"}); + let rows = [ + ( + "no-index-key", + without_key, + 2, + "TableWriteProvisionedThroughputExceeded", + ), + ( + "index-key", + with_key, + 1, + "IndexWriteProvisionedThroughputExceeded", + ), + ]; + for (table, item, served, reason) in rows { + create_indexed_table(&state, table, 1000, 3, 1000, 1).await; + let put = json!({"TableName": table, "Item": item}); + for _ in 0..served { + let (status, body) = call(&state, "PutItem", put.clone()).await; + assert_eq!(status, 200, "{table}: {body}"); + } + let (status, body) = call(&state, "PutItem", put).await; + assert_eq!(status, 400, "{table}: {body}"); + assert_eq!(body["ThrottlingReasons"][0]["reason"], reason, "{table}"); + } +} + +/// Drain the index's write bucket by `DRAIN`, as a served write that carries +/// the index key is charged. +fn drain_index_writes(state: &AppState, account_id: &str, table: &str) { + let writes = [(GSI.to_owned(), DRAIN)].into_iter().collect(); + state + .throttle + .consume_index_writes(account_id, table, &writes); +} + +/// A local secondary index shares the table's capacity: a `Query` naming it +/// past the table's read capacity carries the table body and the table ARN. +#[tokio::test] +async fn lsi_read_throttle_is_the_table_body() { + let (state, account_id) = build_state().await; + let table = "lsi-reads"; + create_indexed_table(&state, table, 1, 1000, 1000, 1000).await; + state.throttle.consume(&account_id, table, DRAIN, 0.0); + let (status, body) = call(&state, "Query", query(table, LSI, "pk")).await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["ThrottlingReasons"], + json!([{ + "reason": "TableReadProvisionedThroughputExceeded", + "resource": arn(&account_id, table), + }]) + ); +} + +/// `UpdateTable` deleting the index replaces the registered set, so the write +/// the index was holding back is served. +#[tokio::test] +async fn deleting_the_index_stops_its_write_refusals() { + let (state, account_id) = build_state().await; + let table = "index-deleted"; + create_indexed_table(&state, table, 1000, 1000, 1, 1).await; + drain_index_writes(&state, &account_id, table); + let put = json!({"TableName": table, "Item": indexed_item()}); + let (status, body) = call(&state, "PutItem", put.clone()).await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["ThrottlingReasons"][0]["reason"], + "IndexWriteProvisionedThroughputExceeded" + ); + let (status, body) = call( + &state, + "UpdateTable", + json!({ + "TableName": table, + "GlobalSecondaryIndexUpdates": [{"Delete": {"IndexName": GSI}}], + }), + ) + .await; + assert_eq!(status, 200, "{body}"); + let (status, body) = call(&state, "PutItem", put).await; + assert_eq!(status, 200, "{body}"); +} + +/// `UpdateTable` raising the index's `ProvisionedThroughput` is the way out +/// the refusal names: the response and `DescribeTable` show the new units, +/// and the index's buckets take the new rate from the response, so the write +/// the index was holding back is served at once. The index is drained by +/// writes of new items that carry its key (one unit each, one second of +/// burst at 1 WCU). At the old rate the debt of about one unit takes a second +/// to repay; the retries below stop after 200 ms. +#[tokio::test] +async fn raising_the_index_throughput_ends_its_write_refusals() { + let (state, _) = build_state().await; + let table = "index-raised"; + create_indexed_table(&state, table, 1000, 1000, 1, 1).await; + let put = |n: usize| { + let mut it = indexed_item(); + it["pk"] = json!({"S": format!("k{n}")}); + json!({"TableName": table, "Item": it}) + }; + let mut refused = None; + for n in 0..10 { + let (status, body) = call(&state, "PutItem", put(n)).await; + if status != 200 { + refused = Some(body); + break; + } + } + let refused = refused.expect("the index at 1 WCU refuses within ten writes"); + assert_eq!( + refused["ThrottlingReasons"][0]["reason"], "IndexWriteProvisionedThroughputExceeded", + "{refused}" + ); + let raised = json!({"ReadCapacityUnits": 5, "WriteCapacityUnits": 1000}); + let (status, body) = call( + &state, + "UpdateTable", + json!({ + "TableName": table, + "GlobalSecondaryIndexUpdates": [{"Update": { + "IndexName": GSI, + "ProvisionedThroughput": raised, + }}], + }), + ) + .await; + assert_eq!(status, 200, "{body}"); + let units = |description: &Value| { + let pt = &description["GlobalSecondaryIndexes"][0]["ProvisionedThroughput"]; + ( + pt["ReadCapacityUnits"].clone(), + pt["WriteCapacityUnits"].clone(), + ) + }; + assert_eq!( + units(&body["TableDescription"]), + (json!(5), json!(1000)), + "{body}" + ); + let (_, described) = call(&state, "DescribeTable", json!({"TableName": table})).await; + assert_eq!( + units(&described["Table"]), + (json!(5), json!(1000)), + "{described}" + ); + let mut last = Value::Null; + for _ in 0..20 { + let (status, body) = call(&state, "PutItem", put(10)).await; + if status == 200 { + return; + } + last = body; + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + panic!("the write is still refused 200 ms after the raise: {last}"); +} + +/// An index read is served from the index's read bucket and does not consult +/// the table's: with the table's read bucket drained, a `Scan` of the base +/// table is refused and a `Query` on the index is served. +#[tokio::test] +async fn index_read_does_not_consult_the_table_read_bucket() { + let (state, account_id) = build_state().await; + let table = "index-apart"; + create_indexed_table(&state, table, 1, 1000, 1000, 1000).await; + state.throttle.consume(&account_id, table, DRAIN, 0.0); + let (status, body) = call(&state, "Scan", json!({"TableName": table})).await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["ThrottlingReasons"][0]["reason"], + "TableReadProvisionedThroughputExceeded" + ); + let (status, body) = call(&state, "Query", query(table, GSI, "g")).await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["Count"], 0); +} + +/// An `UpdateTable` that changes only the table's throughput re-sends the +/// index set from its response, so a drained index keeps holding writes back. +#[tokio::test] +async fn a_table_throughput_update_keeps_the_index_buckets() { + let (state, account_id) = build_state().await; + let table = "index-kept"; + create_indexed_table(&state, table, 1000, 1000, 1, 1).await; + drain_index_writes(&state, &account_id, table); + let (status, body) = call( + &state, + "UpdateTable", + json!({ + "TableName": table, + "ProvisionedThroughput": {"ReadCapacityUnits": 1000, "WriteCapacityUnits": 1001}, + }), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!( + body["TableDescription"]["GlobalSecondaryIndexes"][0]["IndexName"], GSI, + "{body}" + ); + let (status, body) = call( + &state, + "PutItem", + json!({"TableName": table, "Item": indexed_item()}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["ThrottlingReasons"][0]["reason"], + "IndexWriteProvisionedThroughputExceeded" + ); +} + +/// Buckets live in memory, so after a restart the first data request on a +/// table registers it from its description, indexes included. Dropping the +/// registration stands in for the restart: the next index read registers the +/// index again, and draining it then refuses with the index body. +#[tokio::test] +async fn the_lazy_registration_path_registers_the_indexes() { + let (state, account_id) = build_state().await; + let table = "index-lazy"; + create_indexed_table(&state, table, 1000, 1000, 1, 1).await; + state.throttle.remove_table(&account_id, table); + assert!(!state.throttle.is_registered(&account_id, table)); + let (status, body) = call(&state, "Query", query(table, GSI, "g")).await; + assert_eq!(status, 200, "{body}"); + assert!(state.throttle.is_registered(&account_id, table)); + state + .throttle + .consume_with_partition(&account_id, table, DRAIN, 0.0, None, Some(GSI)); + let (status, body) = call(&state, "Query", query(table, GSI, "g")).await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["ThrottlingReasons"], + json!([{ + "reason": "IndexReadProvisionedThroughputExceeded", + "resource": index_arn(&account_id, table, GSI), + }]) + ); +} diff --git a/crates/server/src/handler/throttle_segment.rs b/crates/server/src/handler/throttle_segment.rs new file mode 100644 index 000000000..dcf221f86 --- /dev/null +++ b/crates/server/src/handler/throttle_segment.rs @@ -0,0 +1,145 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The throttle segment of a data-plane request: the table's buckets are +//! registered the first time the manager sees the table, checked, and a +//! refusal becomes the throttle error the service sends. + +use std::sync::Arc; + +use extenddb_engine::OperationContext; + +use super::Refused; +use crate::AppState; +use crate::throttle_helpers::{ + classify_data_operation, table_description_to_index_throughputs, + table_description_to_throughput, throttle_error, +}; + +/// Check the throttle buckets for `operation` on `table_name`, registering +/// the table and its provisioned global secondary indexes from its +/// description first when the manager has no buckets for it. A control-plane +/// operation, a request with no table name, and a name the table name rules +/// refuse are not throttled. `index_name` +/// is the index a `Query` or `Scan` names; a provisioned global secondary +/// index is checked on its own read bucket, and a write is checked on every +/// registered index's write bucket after the table's. A refusal carries the +/// account the request authenticated as. Its throttle metrics are recorded +/// under that account and `metric_table`, the table the request's metrics +/// use (see `metric_table_name`). +pub(super) async fn check( + state: &Arc, + ctx: &OperationContext, + operation: &str, + table_name: Option<&str>, + metric_table: Option<&str>, + partition_value: Option<&str>, + index_name: Option<&str>, +) -> Result<(), Refused> { + let (is_read_op, is_write_op) = classify_data_operation(operation); + // A name the table name rules refuse (length or pattern), and the ARN of + // a table in another Region, are not throttled: the engine answers them + // as it does with capacity left. The service refuses such a name before + // any throttle (measured 2026-11-25 with GetItem and PutItem on `ab`, an + // empty name, 256 characters and the ARN of a table in another Region). + // The ARN of a table in this account and Region is checked by the name it + // carries, and a throttle refusal names that table. + if let Some(tn) = table_name + && (is_read_op || is_write_op) + && let name = crate::authz_resource::key_lookup_name(tn, &state.region, &ctx.account_id) + && extenddb_core::validation::validate_table_name(&name, &state.limits).is_ok() + { + if !state.throttle.is_registered(&ctx.account_id, tn) + && let Ok(desc) = ctx + .storage + .describe_table( + &ctx.account_id, + extenddb_core::types::DescribeTableInput { + table_name: tn.to_owned(), + }, + ) + .await + { + let throughput = table_description_to_throughput(&desc); + state + .throttle + .register_table(&ctx.account_id, tn, throughput); + state.throttle.register_indexes( + &ctx.account_id, + tn, + table_description_to_index_throughputs(&desc), + ); + } + + let result = state.throttle.check_capacity_with_partition( + &ctx.account_id, + tn, + is_read_op, + is_write_op, + partition_value, + index_name, + ); + if let Some(cause) = result.cause() { + let throttled_read = matches!( + result, + extenddb_core::throttle::ThrottleResult::ThrottledRead(_) + ); + // The throttle event metrics carry the index that refused as + // their index dimension, as the service publishes + // Read/WriteThrottleEvents per table and per global secondary + // index; ThrottledRequests is published per table and operation + // only, so a count by table sees an index refusal too. A write an + // index refused is a throttled event of the table as well: the + // service publishes WriteThrottleEvents for both series then, and + // for an index read refusal the index series only. + let refused_index = cause.index_name().map(str::to_owned); + let metric = if throttled_read { + extenddb_core::metrics::MetricName::ReadThrottleEvents + } else { + extenddb_core::metrics::MetricName::WriteThrottleEvents + }; + state.metrics.record( + metric, + 1.0, + Some(&ctx.account_id), + metric_table, + refused_index.as_deref(), + Some(operation), + ); + if refused_index.is_some() && !throttled_read { + state.metrics.record( + metric, + 1.0, + Some(&ctx.account_id), + metric_table, + None, + Some(operation), + ); + } + state.metrics.record( + extenddb_core::metrics::MetricName::ThrottledRequests, + 1.0, + Some(&ctx.account_id), + metric_table, + None, + Some(operation), + ); + // The service names the throttled resource and the limit on a + // throttle: one reason with the table ARN, the same string + // DescribeTable returns as TableArn, or the index ARN (its + // IndexArn) when an index's bucket refused. The error class, the + // message and the limit follow the bucket that refused and the + // table's billing mode. + let resource_arn = match &refused_index { + Some(index) => { + extenddb_storage::util::index_arn(&state.region, &ctx.account_id, &name, index) + } + None => extenddb_storage::util::table_arn(&state.region, &ctx.account_id, &name), + }; + return Err(Refused { + error: throttle_error(cause, throttled_read, &resource_arn), + account_id: Some(ctx.account_id.to_string()), + }); + } + } + Ok(()) +} diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs index 3f7d84b0d..0443cdb62 100644 --- a/crates/server/src/handler/throttle_wire_tests.rs +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -199,11 +199,11 @@ pub(super) async fn create_table(state: &Arc, table: &str, billing: Va panic!("table {table} did not become ACTIVE"); } -fn arn(account_id: &str, table: &str) -> String { +pub(super) fn arn(account_id: &str, table: &str) -> String { format!("arn:aws:dynamodb:us-east-1:{account_id}:table/{table}") } -fn item(size: usize) -> Value { +pub(super) fn item(size: usize) -> Value { json!({"pk": {"S": "k"}, "v": {"S": "x".repeat(size)}}) } @@ -289,7 +289,7 @@ async fn on_demand_hot_key_write_names_the_key_range_and_read_carries_no_reasons state.throttle.remove_table(&account_id, table); state .throttle - .consume_with_partition(&account_id, table, 1.0e9, 1.0e9, Some("k")); + .consume_with_partition(&account_id, table, 1.0e9, 1.0e9, Some("k"), None); let (status, body) = call( &state, "PutItem", diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 57ac44520..74a0a4505 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -11,6 +11,15 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::throttle::ThrottleManager; use serde_json::Value; +mod index; +#[cfg(test)] +mod index_tests; + +pub(crate) use index::{ + extract_index_name, extract_index_throughputs_from_response, + table_description_to_index_throughputs, +}; + /// Convert a `TableDescription` to a `TableThroughput` for throttle registration. pub(crate) fn table_description_to_throughput( desc: &extenddb_core::types::TableDescription, @@ -55,9 +64,12 @@ pub(crate) fn classify_data_operation(operation: &str) -> (bool, bool) { /// Update throttle buckets after a successful table lifecycle operation. /// -/// - `CreateTable` / `DescribeTable`: registers the table's throughput. -/// - `UpdateTable`: updates the table's throughput. -/// - `DeleteTable`: removes the table's buckets. +/// - `CreateTable` / `DescribeTable`: registers the table's throughput and +/// its provisioned global secondary indexes. +/// - `UpdateTable`: updates the table's throughput and replaces the index +/// set, so an index the update created gets buckets and one it deleted +/// stops holding back writes. +/// - `DeleteTable`: removes the table's buckets and its indexes'. /// /// Extracts throughput from the response body's `TableDescription` to avoid /// an extra database round-trip. @@ -74,6 +86,9 @@ pub(crate) fn update_throttle_buckets( if let Some(throughput) = extract_throughput_from_response(body) { throttle.register_table(account_id, tn, throughput); } + if let Some(indexes) = extract_index_throughputs_from_response(body) { + throttle.register_indexes(account_id, tn, indexes); + } } "DeleteTable" => { throttle.remove_table(account_id, tn); @@ -199,7 +214,8 @@ pub(crate) fn extract_partition_value(input: &Value, operation: &str) -> Option< } /// The throttle error the service sends for a refusal by `cause` on a table -/// billed as the cause says, naming `table_arn` as the throttled resource. +/// billed as the cause says, naming `resource_arn` as the throttled resource: +/// the table ARN, or the index ARN for an [`ThrottleCause::Index`] cause. /// /// Measured against the service (2026-10-20 and 2026-10-24, two Regions): a /// provisioned table's own capacity gives `ProvisionedThroughputExceededException` @@ -212,26 +228,34 @@ pub(crate) fn extract_partition_value(input: &Value, operation: &str) -> Option< /// provisioned table was captured once on 2026-10-20 (a `BatchWriteItem`): /// the provisioned class, the table message and /// `TableWriteKeyRangeThroughputExceeded`; the read form follows the -/// documented grammar. Documented in the API Reference (ThrottlingReason, -/// PutItem Errors; read 2026-10-20) and not produced by the probes: an -/// on-demand table past its default ceiling and the account aggregate carry -/// `Table{Read|Write}AccountLimitExceeded`, on `ThrottlingException` and -/// `RequestLimitExceeded` respectively. +/// documented grammar. A provisioned global secondary index past its own +/// capacity (2026-10-24 and 2026-10-25: 648 index reads, 104 `BatchWriteItem` +/// and 5,876 `PutItem`, `UpdateItem` and single-item `TransactWriteItems`) +/// gives the provisioned class with the index +/// ARN as the resource: a `Query` or `Scan` naming the index carries the +/// table message and `IndexReadProvisionedThroughputExceeded`; a base-table +/// write carries the index message and +/// `IndexWriteProvisionedThroughputExceeded`. Documented in the API Reference +/// (ThrottlingReason, PutItem Errors; read 2026-10-20) and not produced by +/// the probes: an on-demand table past its default ceiling and the account +/// aggregate carry `Table{Read|Write}AccountLimitExceeded`, on +/// `ThrottlingException` and `RequestLimitExceeded` respectively. pub(crate) fn throttle_error( - cause: extenddb_core::throttle::ThrottleCause, + cause: &extenddb_core::throttle::ThrottleCause, read: bool, - table_arn: &str, + resource_arn: &str, ) -> DynamoDbError { use extenddb_core::error::{ - MAX_ON_DEMAND_THROUGHPUT_MESSAGE, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, - REQUEST_LIMIT_EXCEEDED_MESSAGE, THROTTLING_EXCEPTION_MESSAGE, ThrottlingReason, + INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, MAX_ON_DEMAND_THROUGHPUT_MESSAGE, + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, REQUEST_LIMIT_EXCEEDED_MESSAGE, + THROTTLING_EXCEPTION_MESSAGE, ThrottlingReason, }; use extenddb_core::throttle::ThrottleCause; let op = if read { "Read" } else { "Write" }; - let reason = |limit: &str| { + let reason = |scope: &str, limit: &str| { vec![ThrottlingReason { - reason: format!("Table{op}{limit}"), - resource: table_arn.to_owned(), + reason: format!("{scope}{op}{limit}"), + resource: resource_arn.to_owned(), }] }; match cause { @@ -239,12 +263,22 @@ pub(crate) fn throttle_error( on_demand: false, .. } => DynamoDbError::provisioned_throughput_exceeded( PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, - reason("ProvisionedThroughputExceeded"), + reason("Table", "ProvisionedThroughputExceeded"), + ), + // An index read carries the table message; an index write carries + // its own, with no trailing period. + ThrottleCause::Index { .. } if read => DynamoDbError::provisioned_throughput_exceeded( + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + reason("Index", "ProvisionedThroughputExceeded"), + ), + ThrottleCause::Index { .. } => DynamoDbError::provisioned_throughput_exceeded( + INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + reason("Index", "ProvisionedThroughputExceeded"), ), ThrottleCause::Partition { on_demand: false } => { DynamoDbError::provisioned_throughput_exceeded( PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, - reason("KeyRangeThroughputExceeded"), + reason("Table", "KeyRangeThroughputExceeded"), ) } // A hot-key read on an on-demand table carries no reasons list @@ -254,7 +288,7 @@ pub(crate) fn throttle_error( } ThrottleCause::Partition { on_demand: true } => DynamoDbError::throttling( THROTTLING_EXCEPTION_MESSAGE, - reason("KeyRangeThroughputExceeded"), + reason("Table", "KeyRangeThroughputExceeded"), ), // `capped` is the refusing direction's own cap, so a table capped in // one direction sends the default-ceiling body for the other. @@ -263,17 +297,18 @@ pub(crate) fn throttle_error( capped: true, } => DynamoDbError::throttling( MAX_ON_DEMAND_THROUGHPUT_MESSAGE, - reason("MaxOnDemandThroughputExceeded"), + reason("Table", "MaxOnDemandThroughputExceeded"), ), ThrottleCause::Table { on_demand: true, capped: false, - } => { - DynamoDbError::throttling(THROTTLING_EXCEPTION_MESSAGE, reason("AccountLimitExceeded")) - } + } => DynamoDbError::throttling( + THROTTLING_EXCEPTION_MESSAGE, + reason("Table", "AccountLimitExceeded"), + ), ThrottleCause::Account => DynamoDbError::request_limit_exceeded( REQUEST_LIMIT_EXCEEDED_MESSAGE, - reason("AccountLimitExceeded"), + reason("Table", "AccountLimitExceeded"), ), } } @@ -490,7 +525,7 @@ mod throttle_error_tests { ), ]; for (cause, read, class, message, reasons) in cases { - let err = throttle_error(cause, read, ARN); + let err = throttle_error(&cause, read, ARN); assert_eq!( parts(&err), (class, message.to_owned(), reasons), diff --git a/crates/server/src/throttle_helpers/index.rs b/crates/server/src/throttle_helpers/index.rs new file mode 100644 index 000000000..b543e78c3 --- /dev/null +++ b/crates/server/src/throttle_helpers/index.rs @@ -0,0 +1,85 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The provisioned global secondary indexes a table description lists, for +//! the throttle manager's index buckets, and the index a read names. + +use extenddb_core::throttle::IndexThroughput; +use serde_json::Value; + +/// The throughput of every provisioned global secondary index in `desc`, in +/// the order the description lists them. An on-demand table's indexes have no +/// capacity of their own and give an empty list, as does an index whose +/// description carries no `ProvisionedThroughput` or carries `0` in both +/// directions (the placeholder a backend describes for an index created on a +/// provisioned table without throughput; a bucket at rate 0 would refuse +/// every request). +pub(crate) fn table_description_to_index_throughputs( + desc: &extenddb_core::types::TableDescription, +) -> Vec { + let is_on_demand = desc + .billing_mode_summary + .as_ref() + .is_some_and(|bms| bms.billing_mode == extenddb_core::types::BillingMode::PayPerRequest); + if is_on_demand { + return Vec::new(); + } + desc.global_secondary_indexes + .iter() + .flatten() + .filter_map(|gsi| { + let pt = gsi.provisioned_throughput.as_ref()?; + if pt.read_capacity_units < 1 && pt.write_capacity_units < 1 { + return None; + } + Some(IndexThroughput::provisioned( + gsi.index_name.clone(), + pt.read_capacity_units, + pt.write_capacity_units, + )) + }) + .collect() +} + +/// The same list read from a `CreateTable`, `UpdateTable` or `DescribeTable` +/// response body. `None` when the body carries no table description. +pub(crate) fn extract_index_throughputs_from_response( + body: &Value, +) -> Option> { + let desc = body.get("TableDescription").or_else(|| body.get("Table"))?; + let is_on_demand = desc + .get("BillingModeSummary") + .and_then(|bms| bms.get("BillingMode")) + .and_then(Value::as_str) + .is_some_and(|bm| bm == "PAY_PER_REQUEST"); + if is_on_demand { + return Some(Vec::new()); + } + Some( + desc.get("GlobalSecondaryIndexes") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|gsi| { + let name = gsi.get("IndexName")?.as_str()?; + let pt = gsi.get("ProvisionedThroughput")?; + let rcu = pt.get("ReadCapacityUnits")?.as_i64()?; + let wcu = pt.get("WriteCapacityUnits")?.as_i64()?; + if rcu < 1 && wcu < 1 { + return None; + } + Some(IndexThroughput::provisioned(name, rcu, wcu)) + }) + .collect(), + ) +} + +/// The index a `Query` or `Scan` names in `IndexName`. Every other operation +/// reads or writes the base table and gives `None`; a `BatchGetItem` or +/// `TransactGetItems` cannot name an index. +pub(crate) fn extract_index_name(input: &Value, operation: &str) -> Option { + match operation { + "Query" | "Scan" => input.get("IndexName")?.as_str().map(str::to_owned), + _ => None, + } +} diff --git a/crates/server/src/throttle_helpers/index_tests.rs b/crates/server/src/throttle_helpers/index_tests.rs new file mode 100644 index 000000000..605996a27 --- /dev/null +++ b/crates/server/src/throttle_helpers/index_tests.rs @@ -0,0 +1,178 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use extenddb_core::error::{ + DynamoDbError, INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, +}; +use extenddb_core::throttle::{IndexThroughput, ThrottleCause}; +use extenddb_core::types::{ + BillingMode, BillingModeSummary, GsiDescription, ProvisionedThroughputDescription, + TableDescription, +}; +use serde_json::json; + +use super::{ + extract_index_name, extract_index_throughputs_from_response, + table_description_to_index_throughputs, throttle_error, +}; + +fn gsi(name: &str, throughput: Option<(i64, i64)>) -> GsiDescription { + GsiDescription { + index_name: name.to_owned(), + key_schema: Vec::new(), + projection: extenddb_core::types::Projection { + projection_type: extenddb_core::types::ProjectionType::All, + non_key_attributes: None, + }, + index_status: "ACTIVE".to_owned(), + provisioned_throughput: throughput.map(|(rcu, wcu)| ProvisionedThroughputDescription { + read_capacity_units: rcu, + write_capacity_units: wcu, + number_of_decreases_today: 0, + last_increase_date_time: None, + last_decrease_date_time: None, + }), + index_size_bytes: 0, + item_count: 0, + index_arn: String::new(), + warm_throughput: None, + warm_throughput_record: None, + } +} + +fn description(on_demand: bool, gsis: Vec) -> TableDescription { + TableDescription { + billing_mode_summary: on_demand.then_some(BillingModeSummary { + billing_mode: BillingMode::PayPerRequest, + last_update_to_pay_per_request_date_time: None, + }), + global_secondary_indexes: Some(gsis), + ..TableDescription::default() + } +} + +/// The typed path: every provisioned index in order; one without throughput +/// and one at the 0/0 placeholder give no buckets; an on-demand table's +/// indexes give none. +#[test] +fn typed_description_lists_the_provisioned_indexes_in_order() { + let desc = description( + false, + vec![ + gsi("b", Some((5, 6))), + gsi("none", None), + gsi("zero", Some((0, 0))), + gsi("a", Some((1, 2))), + ], + ); + assert_eq!( + table_description_to_index_throughputs(&desc), + vec![ + IndexThroughput::provisioned("b", 5, 6), + IndexThroughput::provisioned("a", 1, 2), + ] + ); + let on_demand = description(true, vec![gsi("b", Some((5, 6)))]); + assert!(table_description_to_index_throughputs(&on_demand).is_empty()); + let no_indexes = TableDescription::default(); + assert!(table_description_to_index_throughputs(&no_indexes).is_empty()); +} + +/// The response-body path reads the same list under `TableDescription` or +/// `Table`, and gives `None` only when neither is present. +#[test] +fn response_body_lists_the_provisioned_indexes() { + let body = json!({"TableDescription": { + "ProvisionedThroughput": {"ReadCapacityUnits": 10, "WriteCapacityUnits": 10}, + "GlobalSecondaryIndexes": [ + {"IndexName": "b", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 6}}, + {"IndexName": "none"}, + {"IndexName": "zero", "ProvisionedThroughput": {"ReadCapacityUnits": 0, "WriteCapacityUnits": 0}}, + {"IndexName": "a", "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 2}}, + ], + }}); + assert_eq!( + extract_index_throughputs_from_response(&body), + Some(vec![ + IndexThroughput::provisioned("b", 5, 6), + IndexThroughput::provisioned("a", 1, 2), + ]) + ); + let on_demand = json!({"Table": { + "BillingModeSummary": {"BillingMode": "PAY_PER_REQUEST"}, + "GlobalSecondaryIndexes": [ + {"IndexName": "b", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 6}}, + ], + }}); + assert_eq!( + extract_index_throughputs_from_response(&on_demand), + Some(Vec::new()) + ); + let without_indexes = json!({"Table": { + "ProvisionedThroughput": {"ReadCapacityUnits": 10, "WriteCapacityUnits": 10}, + }}); + assert_eq!( + extract_index_throughputs_from_response(&without_indexes), + Some(Vec::new()) + ); + assert_eq!( + extract_index_throughputs_from_response(&json!({"Items": []})), + None + ); +} + +/// Only `Query` and `Scan` name an index. +#[test] +fn index_name_is_read_from_query_and_scan_only() { + let input = json!({"TableName": "t", "IndexName": "i"}); + assert_eq!(extract_index_name(&input, "Query").as_deref(), Some("i")); + assert_eq!(extract_index_name(&input, "Scan").as_deref(), Some("i")); + for operation in ["GetItem", "PutItem", "BatchGetItem", "UpdateTable"] { + assert_eq!(extract_index_name(&input, operation), None, "{operation}"); + } + assert_eq!( + extract_index_name(&json!({"TableName": "t"}), "Query"), + None + ); + assert_eq!(extract_index_name(&json!({"IndexName": 7}), "Scan"), None); +} + +/// The two measured index bodies: the provisioned class for both; the table +/// message on a read and the index message (no trailing period) on a write; +/// the reason in the `Index` scope; the resource as given. +#[test] +fn index_cause_maps_to_the_two_measured_bodies() { + const INDEX_ARN: &str = "arn:aws:dynamodb:us-east-1:123456789012:table/T/index/I"; + let cause = ThrottleCause::Index { + index_name: "I".to_owned(), + }; + for (read, message, reason) in [ + ( + true, + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + "IndexReadProvisionedThroughputExceeded", + ), + ( + false, + INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + "IndexWriteProvisionedThroughputExceeded", + ), + ] { + let err = throttle_error(&cause, read, INDEX_ARN); + assert!( + matches!( + err, + DynamoDbError::ProvisionedThroughputExceededException { .. } + ), + "read={read}: {err:?}" + ); + assert_eq!(err.message(), message, "read={read}"); + let reasons = err.throttling_reasons().expect("reasons"); + assert_eq!(reasons.len(), 1, "read={read}"); + assert_eq!(reasons[0].reason, reason, "read={read}"); + assert_eq!(reasons[0].resource, INDEX_ARN, "read={read}"); + } + assert!(!INDEX_WRITE_PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE.ends_with('.')); + assert!(PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE.ends_with('.')); +} diff --git a/crates/storage-cassandra/src/update_table.rs b/crates/storage-cassandra/src/update_table.rs index 116c69260..a950da613 100644 --- a/crates/storage-cassandra/src/update_table.rs +++ b/crates/storage-cassandra/src/update_table.rs @@ -175,6 +175,44 @@ impl CassandraEngine { self.merged_index_warm_throughput(&table_id, &action.index_name, spec) .await?; } + // A provisioned index's new ProvisionedThroughput, in the shape + // the create path writes, in the indexes batch. The engine has + // checked the units, that the table is PROVISIONED before and + // after the request, and that the index exists. A Cassandra + // UPDATE writes a row even when none exists, so the index is read + // again here: one removed since the engine's check is refused + // before anything is written. + if let Some(action) = &update.update + && let Some(pt) = action.provisioned_throughput_units() + { + let index_type: Option = query_optional( + &self.session, + &format!( + "SELECT index_type FROM {catalog_ks}.indexes \ + WHERE table_id = ? AND index_name = ?" + ), + cdrs_tokio::query_values!(table_id.as_str(), action.index_name.as_str()), + "update_table gsi throughput", + ) + .await? + .and_then(|row| row.get_by_name("index_type").ok().flatten()); + if index_type.as_deref() != Some("GSI") { + return Err(StorageError::IndexNotFound(action.index_name.clone())); + } + let pt_json = serde_json::to_string(&pt) + .map_err(|e| StorageError::Internal(e.to_string()))?; + add_index_op!( + format!( + "UPDATE {catalog_ks}.indexes SET provisioned_throughput = ? \ + WHERE table_id = ? AND index_name = ?" + ), + cdrs_tokio::query_values!( + pt_json.as_str(), + table_id.as_str(), + action.index_name.as_str() + ) + ); + } } // Stream specification: the catalog columns go in the tables LWT; the diff --git a/crates/storage-mongodb/src/table_engine.rs b/crates/storage-mongodb/src/table_engine.rs index 09f7eabb6..1236c848d 100644 --- a/crates/storage-mongodb/src/table_engine.rs +++ b/crates/storage-mongodb/src/table_engine.rs @@ -1010,7 +1010,22 @@ impl MongoEngine { self.store_warm_throughput_updates(account_id, &input) .await?; - if clear_provisioned_throughput { + // A provisioned index's new ProvisionedThroughput, in the shape the + // create path writes. The engine has checked the units, that the + // table is PROVISIONED before and after the request, and that the + // index exists. An Update naming no GSI of the table (one removed + // since that check) is IndexNotFound, as for WarmThroughput. + let throughput_updates: Vec<_> = input + .global_secondary_index_updates + .iter() + .flatten() + .filter_map(|u| u.update.as_ref()) + .filter_map(|u| { + u.provisioned_throughput_units() + .map(|pt| (&u.index_name, pt)) + }) + .collect(); + if clear_provisioned_throughput || !throughput_updates.is_empty() { let table_doc = tables_coll .find_one(doc! { "_id": { "account_id": account_id, "table_name": &input.table_name }, @@ -1021,14 +1036,33 @@ impl MongoEngine { let table_id = table_doc .get_str("table_id") .map_err(|_| StorageError::Internal("missing table_id".to_owned()))?; - self.catalog_db - .collection::("indexes") - .update_many( - doc! { "_id.table_id": table_id, "index_type": "GSI" }, - doc! { "$set": { "provisioned_throughput": bson::Bson::Null } }, - ) - .await - .map_err(|e| StorageError::Internal(e.to_string()))?; + let indexes = self.catalog_db.collection::("indexes"); + if clear_provisioned_throughput { + indexes + .update_many( + doc! { "_id.table_id": table_id, "index_type": "GSI" }, + doc! { "$set": { "provisioned_throughput": bson::Bson::Null } }, + ) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + } + for (index_name, pt) in throughput_updates { + let pt_bson = + bson::to_bson(&pt).map_err(|e| StorageError::Internal(e.to_string()))?; + let written = indexes + .update_one( + doc! { + "_id": { "table_id": table_id, "index_name": index_name }, + "index_type": "GSI", + }, + doc! { "$set": { "provisioned_throughput": pt_bson } }, + ) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + if written.matched_count == 0 { + return Err(StorageError::IndexNotFound(index_name.clone())); + } + } } // Handle GSI updates diff --git a/crates/storage-postgres/src/update_table.rs b/crates/storage-postgres/src/update_table.rs index e52a8ead4..1e219e805 100755 --- a/crates/storage-postgres/src/update_table.rs +++ b/crates/storage-postgres/src/update_table.rs @@ -42,6 +42,45 @@ async fn release_taken_holds( } } +/// Store the `ProvisionedThroughput` of each `GlobalSecondaryIndexUpdates` +/// `Update` as the index's throughput, in the shape the create path writes, +/// inside the caller's catalog transaction. The engine has checked the units, +/// that the table is PROVISIONED before and after the request, and that the +/// index exists. An `Update` naming no GSI of the table (one removed since +/// that check) is `IndexNotFound`. +async fn store_index_throughput_updates( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + table_id: &str, + input: &extenddb_core::types::UpdateTableInput, +) -> Result<(), StorageError> { + for update in input + .global_secondary_index_updates + .iter() + .flatten() + .filter_map(|u| u.update.as_ref()) + { + let Some(pt) = update.provisioned_throughput_units() else { + continue; + }; + let stored = + serde_json::to_value(&pt).map_err(|e| StorageError::Internal(e.to_string()))?; + let written = sqlx::query( + "UPDATE indexes SET provisioned_throughput = $1 \ + WHERE table_id = $2 AND index_name = $3 AND index_type = 'GSI'", + ) + .bind(&stored) + .bind(table_id) + .bind(&update.index_name) + .execute(&mut **tx) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + if written.rows_affected() == 0 { + return Err(StorageError::IndexNotFound(update.index_name.clone())); + } + } + Ok(()) +} + /// Refuse a GSI Create, or a Delete of a GSI other than the one building, while /// a GSI on the table is `CREATING`. async fn refuse_while_building( @@ -382,6 +421,7 @@ impl PostgresEngine { // WarmThroughput on the table and on updated indexes: stored as sent, // nothing acts on it. Validated by the engine against the current values. Self::store_warm_throughput_updates(&mut tx, account_id, &table_id, &input).await?; + store_index_throughput_updates(&mut tx, &table_id, &input).await?; // Apply GSI updates (create/delete). // The WarmThroughput record each created GSI was inserted with, so the diff --git a/crates/storage-sqlite/src/table_helpers.rs b/crates/storage-sqlite/src/table_helpers.rs index 59ec899a7..3632f497e 100644 --- a/crates/storage-sqlite/src/table_helpers.rs +++ b/crates/storage-sqlite/src/table_helpers.rs @@ -138,6 +138,19 @@ fn parse_gsi_throughput(s: &str) -> Result Result { + serde_json::to_string(&ProvisionedThroughputDescription { + read_capacity_units: pt.read_capacity_units, + write_capacity_units: pt.write_capacity_units, + number_of_decreases_today: 0, + last_increase_date_time: None, + last_decrease_date_time: None, + }) + .map_err(|e| StorageError::Internal(e.to_string())) +} + impl SqliteEngine { /// Build a `TableDescription` by reading the catalog. pub(crate) async fn build_table_description( diff --git a/crates/storage-sqlite/src/update_table.rs b/crates/storage-sqlite/src/update_table.rs index 3c8878139..afc64c09c 100644 --- a/crates/storage-sqlite/src/update_table.rs +++ b/crates/storage-sqlite/src/update_table.rs @@ -14,8 +14,8 @@ //! backfill lifecycle the service was measured to report. use extenddb_core::types::{ - AttributeDefinition, BillingMode, KeySchemaElement, ProvisionedThroughputDescription, - TableDescription, UpdateTableInput, VectorIndexSpecification, + AttributeDefinition, BillingMode, KeySchemaElement, TableDescription, UpdateTableInput, + VectorIndexSpecification, }; use extenddb_storage::error::StorageError; use extenddb_storage::util::{ @@ -24,6 +24,7 @@ use extenddb_storage::util::{ }; use crate::store::SqliteEngine; +use crate::table_helpers::gsi_throughput_json; /// Refuse a GSI Create, or a Delete of a GSI other than the one building, while /// a GSI on the table is `CREATING`. @@ -47,6 +48,44 @@ async fn refuse_while_building( Ok(()) } +/// Store the `ProvisionedThroughput` of each `GlobalSecondaryIndexUpdates` +/// `Update` as the index's throughput, in the shape the create path writes, +/// inside the caller's catalog transaction. The engine has checked the units, +/// that the table is PROVISIONED before and after the request, and that the +/// index exists. An `Update` naming no GSI of the table (one removed since +/// that check) is `IndexNotFound`. +async fn store_index_throughput_updates( + tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, + table_id: &str, + input: &UpdateTableInput, +) -> Result<(), StorageError> { + for update in input + .global_secondary_index_updates + .iter() + .flatten() + .filter_map(|u| u.update.as_ref()) + { + let Some(pt) = update.provisioned_throughput_units() else { + continue; + }; + let stored = gsi_throughput_json(&pt)?; + let written = sqlx::query( + "UPDATE indexes SET provisioned_throughput = ? \ + WHERE table_id = ? AND index_name = ? AND index_type = 'GSI'", + ) + .bind(&stored) + .bind(table_id) + .bind(&update.index_name) + .execute(&mut **tx) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + if written.rows_affected() == 0 { + return Err(StorageError::IndexNotFound(update.index_name.clone())); + } + } + Ok(()) +} + /// Refuse a new index whose name is already taken on this table, whatever index /// family holds it. /// @@ -336,6 +375,7 @@ impl SqliteEngine { // WarmThroughput on the table and on updated indexes: stored as sent, // nothing acts on it. Validated by the engine against the current values. Self::store_warm_throughput_updates(&mut tx, account_id, &table_id, &input).await?; + store_index_throughput_updates(&mut tx, &table_id, &input).await?; // GSI create/delete. let mut created: Vec = Vec::new(); @@ -373,17 +413,8 @@ impl SqliteEngine { let pt = create .provisioned_throughput .as_ref() - .map(|pt| { - serde_json::to_string(&ProvisionedThroughputDescription { - read_capacity_units: pt.read_capacity_units, - write_capacity_units: pt.write_capacity_units, - number_of_decreases_today: 0, - last_increase_date_time: None, - last_decrease_date_time: None, - }) - }) - .transpose() - .map_err(|e| StorageError::Internal(e.to_string()))?; + .map(gsi_throughput_json) + .transpose()?; let warm = warm_throughput_record_for_create( create.warm_throughput.as_ref(), Self::control_plane_delay_secs(&mut tx).await?, @@ -1309,10 +1340,12 @@ mod gsi_throughput_tests { /// A GSI added by UpdateTable with ProvisionedThroughput on a PROVISIONED /// table is stored as the throughput description DescribeTable reads, so /// DescribeTable keeps working and reports the index's units with - /// NumberOfDecreasesToday 0. A row an earlier build wrote in the request's - /// shape (no NumberOfDecreasesToday) is read the same way. + /// NumberOfDecreasesToday 0, and so is the throughput of a later Update of + /// the index; an Update naming no index is IndexNotFound. A row an earlier + /// build wrote in the request's shape (no NumberOfDecreasesToday) is read + /// the same way. #[tokio::test] - async fn describe_table_works_after_adding_a_provisioned_gsi() { + async fn describe_table_works_after_adding_and_raising_a_provisioned_gsi() { let engine = SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) .await .expect("engine"); @@ -1374,6 +1407,50 @@ mod gsi_throughput_tests { (3, 4, 0) ); + let raise = |index: &str| -> extenddb_core::types::UpdateTableInput { + serde_json::from_value(json!({ + "TableName": "t", + "GlobalSecondaryIndexUpdates": [{"Update": { + "IndexName": index, + "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 7} + }}] + })) + .expect("update") + }; + let returned = engine + .update_table(account, raise("gsi")) + .await + .expect("UpdateTable raising the GSI"); + let described = engine + .describe_table( + account, + extenddb_core::types::DescribeTableInput { + table_name: "t".to_owned(), + }, + ) + .await + .expect("DescribeTable after raising the GSI"); + for desc in [returned, described] { + let gsi = &desc.global_secondary_indexes.expect("gsis")[0]; + let pt = gsi.provisioned_throughput.as_ref().expect("gsi throughput"); + assert_eq!( + ( + pt.read_capacity_units, + pt.write_capacity_units, + pt.number_of_decreases_today + ), + (5, 7, 0) + ); + } + let err = engine + .update_table(account, raise("missing")) + .await + .expect_err("an Update naming no index is refused"); + assert!( + matches!(&err, extenddb_storage::error::StorageError::IndexNotFound(n) if n == "missing"), + "{err:?}" + ); + // The shape earlier builds stored for the same UpdateTable. sqlx::query( "UPDATE indexes SET provisioned_throughput = \ diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 492542df2..4d1737a6a 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -627,6 +627,8 @@ struct TokenBucketState { The handler calls `core::capacity::calculator` to compute consumed RCU/WCU, then calls `ThroughputTracker::consume()` to deduct tokens. If insufficient tokens, returns the throttle error for the refusing bucket and billing mode (`throttle_helpers::throttle_error`): the provisioned class, `ThrottlingException` or `RequestLimitExceeded`, with the table ARN and the limit in the reasons list where the service sends one; see differences-from-dynamodb.md. +A provisioned global secondary index has a read bucket and a write bucket of its own, keyed by the table and kept in the order `DescribeTable` lists the indexes. They are registered with the table's buckets from its description on `CreateTable`, `UpdateTable` and `DescribeTable` and on the first request after a restart; an `UpdateTable` that creates or deletes an index replaces the set, an index kept across the update keeps its balance and takes the rate the response describes (the new one when the update changed the index's `ProvisionedThroughput`, which the backends store), and `DeleteTable` removes them. A `Query` or `Scan` naming the index is checked against and charged to the index's read bucket in place of the table's; a local secondary index, or a name no registered index has, reads from the table's buckets. A write is checked against the table's write bucket and then each index's write bucket in order. It is charged to the table, and to each index whose key attributes the old or the new item carries, by the index write units the engine reports for `PutItem`, `UpdateItem` and `DeleteItem` (`DispatchMetrics::index_write_units`, counted as `ConsumedCapacity` counts the index arms); an index the write did not touch is not charged, as the service charges it. A refusal by an index carries the index ARN as the resource, `IndexReadProvisionedThroughputExceeded` with the table message on a read, and `IndexWriteProvisionedThroughputExceeded` with the index message on a write, both measured against Amazon DynamoDB on 2026-10-24 and 2026-10-25. The `ReadThrottleEvents` or `WriteThrottleEvents` record for an index refusal carries the index as its index dimension, as the service publishes those metrics per table and per global secondary index, and an index write refusal also records `WriteThrottleEvents` for the table, as the service publishes both series then; `ThrottledRequests` carries no index dimension, as the service publishes it per table and operation. An on-demand table's indexes have no buckets. + --- ## License diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 598d6a80a..3946bb524 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -212,7 +212,7 @@ alone, with the same wording. For PartiQL this holds in `ExecuteStatement`, | Throttling | Always on; throttles requests that exceed provisioned/burst capacity. No setting to disable | Configurable via `throttling_enabled` runtime setting (default: `true`) | | Throttle error bodies | A throttle names the throttled resource and the limit. A provisioned table's own capacity is `ProvisionedThroughputExceededException` with `ThrottlingReasons: [{reason: Table{Read\|Write}ProvisionedThroughputExceeded, resource: }]` on every read and write operation; a hot key on an on-demand table is `ThrottlingException` in the `com.amazon.coral.availability#` namespace with `throttlingReasons` (lower t) naming `TableWriteKeyRangeThroughputExceeded` on a write and no reasons list on a read; an on-demand table at its `OnDemandThroughput` caps is `ThrottlingException` with the message `Throughput exceeds the maximum OnDemandThroughput configured on table or index` and `Table{Read\|Write}MaxOnDemandThroughputExceeded`. Measured 2026-10-20 (435 bodies, one Region) and 2026-10-24 (9,622 bodies, two Regions). No `x-amz-retry-after` header | The throttle covers GetItem, PutItem, UpdateItem, DeleteItem, Query and Scan, the operations whose request names one table in `TableName`, and sends the same classes, namespaces, messages, field names and reasons for the table, hot-key and caps buckets. BatchGetItem, BatchWriteItem, TransactGetItems, TransactWriteItems and the PartiQL operations are not throttled. The account aggregate bucket sends `RequestLimitExceeded` with `Table{Read\|Write}AccountLimitExceeded`, and an on-demand table past its default ceiling sends `ThrottlingException` with the same reason: both follow the API Reference and were not produced by the measurements. A hot key on a provisioned table names `Table{Read\|Write}KeyRangeThroughputExceeded` with the provisioned class and message; the write form was captured once on 2026-10-20, the read form follows the documented grammar | | Partial batch success under throttling | `BatchGetItem` and `BatchWriteItem` serve the entries the table has capacity for and return the rest under `UnprocessedKeys` or `UnprocessedItems`, with the request's `KeysAndAttributes` fields echoed beside the reduced `Keys`, `ConsumedCapacity` counting the served entries only, and an empty map present as `{}`. The call fails with the throttle error only when no entry could be served. Measured 2026-10-21 (two partial `BatchGetItem` responses, 16 of 25 keys served with `ConsistentRead` and `ProjectionExpression` echoed; 26 of 26 full responses with `UnprocessedKeys: {}`; 13 of 13 full `BatchWriteItem` responses with `UnprocessedItems: {}`) and 2026-10-20 (18 of 80 on-demand `BatchWriteItem` batches partial). The all-throttled failure, the echo of `ExpressionAttributeNames` and `AttributesToGet`, and `DeleteRequest` entries under `UnprocessedItems` follow the API Reference and were not reached in the samples | The server's own token bucket runs before dispatch and keys on the request's top-level `TableName`, so it applies to single-item calls and not to `BatchGetItem`, `BatchWriteItem` or the transactions (no bucket check, no partial). When a backend reports a throttle for one entry through `StorageError::Service`, the engine serves the remaining entries and returns the throttled ones in the measured shape, with `ConsumedCapacity` and `ItemCollectionMetrics` for the served entries only and the throttle error when every entry was throttled. Any other backend error still fails the request. A `BatchWriteItem` also defers a transient, conflict or connection failure, and a batch with nothing applied that has such a deferral answers 503 (see "`BatchWriteItem` where no request could be applied now") | -| Index back-pressure | A base-table write held back by an under-provisioned global secondary index is throttled with `IndexWriteProvisionedThroughputExceeded`, the index ARN and a message naming global secondary indexes; an index read past the index's capacity names `IndexReadProvisionedThroughputExceeded` and the index ARN (measured 2026-10-24: 104 index-write bodies, 648 index-read bodies) | Not modelled: the token buckets are per table and per partition key, with no per-index capacity | +| Index back-pressure | A base-table write held back by an under-provisioned global secondary index is throttled with `IndexWriteProvisionedThroughputExceeded`, the index ARN and a message naming global secondary indexes; an index read past the index's capacity names `IndexReadProvisionedThroughputExceeded` and the index ARN (measured 2026-10-24 and 2026-10-25: 648 index-read bodies, 451 `Query` and 197 `Scan`; 104 `BatchWriteItem` and 5,876 `PutItem`, `UpdateItem` and single-item `TransactWriteItems` bodies). The service charges an index write only for an item that carries the index's key attributes. An `UpdateTable` that raises an exhausted index's `ProvisionedThroughput` ends its refusals a few seconds later, while the response still shows the old units (measured 2026-11-24: 1.9 s and 3.4 s). A hot index key on a provisioned index carries no reasons list; an on-demand index past its `OnDemandThroughput` caps names `IndexReadMaxOnDemandThroughputExceeded` with the index ARN | A provisioned global secondary index has its own read and write buckets, registered from the table description and replaced on `UpdateTable`. A `Query` or `Scan` naming the index is served from the index's read bucket and refused with the index read body; a `PutItem`, `UpdateItem` or `DeleteItem` is checked against every index's write bucket after the table's and refused with the index write body naming the first exhausted index in `DescribeTable` order. A served write is charged to each index whose key attributes its old or new item carries, by the index's write units, as on the service; an item without an index's key attributes does not drain that index. A `BatchWriteItem` or `TransactWriteItems` names its tables per item and is not checked against the server's buckets, as before. An `UpdateTable` that changes a provisioned index's `ProvisionedThroughput` is applied at once: the response and `DescribeTable` show the new units, the index stays `ACTIVE`, and the index's buckets take the new rate from the response. A local secondary index shares the table's buckets. Not modelled: on-demand index caps (the GSI definition has no `OnDemandThroughput` member) and the hot index key (the server extracts no partition value for `Query` or `Scan`) | ## Transactions diff --git a/tests/python/test_warm_throughput_updates.py b/tests/python/test_warm_throughput_updates.py index b804e71a1..f93594c62 100644 --- a/tests/python/test_warm_throughput_updates.py +++ b/tests/python/test_warm_throughput_updates.py @@ -136,6 +136,98 @@ def test_an_update_without_warm_throughput_names_the_billing_mode( ) _validation(exc, ON_DEMAND_UPDATE_MEMBERS) + def test_an_update_of_a_provisioned_index_throughput_is_stored(self, dynamodb_client, tables): + """An Update carrying ProvisionedThroughput on a PROVISIONED table changes the + index's throughput: once the table and the index are ACTIVE, DescribeTable + shows the new units.""" + name, _ = _create( + dynamodb_client, + tables, + BillingMode="PROVISIONED", + ProvisionedThroughput=PROVISIONED_5, + GlobalSecondaryIndexes=[ + {**GSI, "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}} + ], + ) + _wait_all_active(dynamodb_client, name) + dynamodb_client.update_table( + TableName=name, + GlobalSecondaryIndexUpdates=[{ + "Update": { + "IndexName": "gsi", + "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 7}, + } + }], + ) + t = _wait_all_active(dynamodb_client, name) + pt = t["GlobalSecondaryIndexes"][0]["ProvisionedThroughput"] + assert (pt["ReadCapacityUnits"], pt["WriteCapacityUnits"]) == (5, 7) + + def test_an_update_of_an_index_the_table_does_not_have_changes_nothing( + self, dynamodb_client, tables + ): + """An Update of an index the table does not have answers + ResourceNotFoundException, and the table's own ProvisionedThroughput in the + same request is not applied.""" + name, _ = _create( + dynamodb_client, + tables, + BillingMode="PROVISIONED", + ProvisionedThroughput=PROVISIONED_5, + GlobalSecondaryIndexes=[{**GSI, "ProvisionedThroughput": PROVISIONED_5}], + ) + _wait_all_active(dynamodb_client, name) + with pytest.raises(ClientError) as exc: + dynamodb_client.update_table( + TableName=name, + ProvisionedThroughput={"ReadCapacityUnits": 10, "WriteCapacityUnits": 10}, + GlobalSecondaryIndexUpdates=[ + {"Update": {"IndexName": "missing", "ProvisionedThroughput": PROVISIONED_5}} + ], + ) + assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException" + pt = dynamodb_client.describe_table(TableName=name)["Table"]["ProvisionedThroughput"] + assert (pt["ReadCapacityUnits"], pt["WriteCapacityUnits"]) == (5, 5) + + @pytest.mark.parametrize( + "throughput,expected", + [ + ({"ReadCapacityUnits": 0, "WriteCapacityUnits": 5}, [("0", "readCapacityUnits", "ge1")]), + ({"ReadCapacityUnits": 5, "WriteCapacityUnits": 0}, [("0", "writeCapacityUnits", "ge1")]), + ({"ReadCapacityUnits": -1, "WriteCapacityUnits": 5}, [("-1", "readCapacityUnits", "ge1")]), + ({"ReadCapacityUnits": 5}, [(None, "writeCapacityUnits", "null")]), + ({}, [(None, "writeCapacityUnits", "null"), (None, "readCapacityUnits", "null")]), + ], + ) + def test_the_units_of_an_index_update_are_checked_before_the_table( + self, raw_client, throughput, expected + ): + """Measured 2026-11-25 on a table name that does not exist, each twice: the + member-path clauses, write units before read units, ahead of the + ResourceNotFoundException the same request answers with valid units. The + SDK's own checks are off, so the server answers.""" + path = "globalSecondaryIndexUpdates.1.member.update.provisionedThroughput." + rules = { + "ge1": "Member must have value greater than or equal to 1", + "null": "Member must not be null", + } + clauses = [] + for value, unit, rule in expected: + shown = "null" if value is None else f"'{value}'" + clauses.append( + f"Value {shown} at '{path}{unit}' failed to satisfy constraint: {rules[rule]}" + ) + count = len(clauses) + message = f"{count} validation error{'s' if count > 1 else ''} detected: " + "; ".join(clauses) + with pytest.raises(ClientError) as exc: + raw_client.update_table( + TableName=unique_name("wt-absent"), + GlobalSecondaryIndexUpdates=[ + {"Update": {"IndexName": "gsi", "ProvisionedThroughput": throughput}} + ], + ) + _validation(exc, message) + INDEX_CHANGE_WITH_STREAM = ( "One or more parameter values were invalid: You cannot create or delete index while "