diff --git a/crates/storage-cassandra/src/data/mod.rs b/crates/storage-cassandra/src/data/mod.rs index 86806a120..dff1a028e 100644 --- a/crates/storage-cassandra/src/data/mod.rs +++ b/crates/storage-cassandra/src/data/mod.rs @@ -23,6 +23,7 @@ pub mod index; mod put_get_item; mod query; mod query_helpers; +mod rows; mod scan; mod sk_range; mod transact_stream; diff --git a/crates/storage-cassandra/src/data/rows.rs b/crates/storage-cassandra/src/data/rows.rs new file mode 100644 index 000000000..20bb253d8 --- /dev/null +++ b/crates/storage-cassandra/src/data/rows.rs @@ -0,0 +1,187 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Data rows for the Cassandra Scan and Query: the item a row holds, reads +//! that go on after the last row read, and reads that Cassandra refuses. +//! +//! A partition whose items have all been deleted answers a read with one row +//! of its static columns. A TTL claim on an absent key, and a transaction +//! prepare that lands on an item deleted after the transaction read it, leave +//! a row with no `item_data`. The reads skip such rows. When every row of a +//! full read holds no item, the scan reads on after the last row read (its +//! partition key and, for a row with one, its sort key), with up to twice as +//! many rows each time and at most [`RUN_READ_ROWS`] (or the read's own +//! LIMIT, if larger). Cassandra counts a tombstone for each deleted row in +//! the partitions a read passes, so every read of a call, the first one +//! included, that Cassandra refuses with a read failure (for example +//! `READ_TOO_MANY_TOMBSTONES`) is tried again with half as many rows, down to +//! one, and the later reads in the same call stay at that size. + +use cdrs_tokio::error::Error as CdrsError; +use cdrs_tokio::frame::message_error::ErrorType; +use cdrs_tokio::query::QueryValues; +use cdrs_tokio::types::IntoRustByName; +use cdrs_tokio::types::blob::Blob; +use cdrs_tokio::types::decimal::Decimal; +use cdrs_tokio::types::value::Value; +use extenddb_core::types::{Item, ScalarAttributeType}; +use extenddb_storage::error::StorageError; +use extenddb_storage::util::sk_column; +use std::sync::Arc; + +use super::json_to_item; +use crate::cassandra_util::{CassandraSession, PolicySession, Stmt}; + +/// The most rows one read takes while a read goes on through rows that hold +/// no item, unless the read's own LIMIT is larger. +pub(super) const RUN_READ_ROWS: usize = 1_000; + +pub(super) type Row = cdrs_tokio::types::rows::Row; + +/// A clustering predicate after `pk = ? AND`, and the values it binds. +pub(super) type Clustering = (String, Vec); + +/// A position to read on after: a partition key text, and a clustering +/// predicate when the read goes on inside that partition. +pub(super) type Position = (String, Option); + +/// The item `row` holds, or `None` for a row without `item_data`. +pub(super) fn row_item(row: &Row, context: &str) -> Result, StorageError> { + let item_data: Option = row.get_by_name("item_data").map_err(|error| { + StorageError::Internal(format!("{context} parse item_data failed: {error}")) + })?; + item_data.map(json_to_item).transpose() +} + +/// The position of a base-table row, to read on after it: its partition key +/// text, and its sort key as a clustering predicate when the row has one. A +/// static-only row has no sort key, and neither does a hash-only table's row. +pub(super) fn row_position( + row: &Row, + sk_type: Option, +) -> Result { + let parse = + |error: CdrsError| StorageError::Internal(format!("scan parse row key failed: {error}")); + let pk: Option = row.get_by_name("pk").map_err(parse)?; + let pk = pk.ok_or_else(|| StorageError::Internal("scan row without pk".to_owned()))?; + let Some(sk_type) = sk_type else { + return Ok((pk, None)); + }; + let col = sk_column(sk_type); + let value = match sk_type { + ScalarAttributeType::S => IntoRustByName::::get_by_name(row, col) + .map_err(parse)? + .map(Value::from), + ScalarAttributeType::N => IntoRustByName::::get_by_name(row, col) + .map_err(parse)? + .map(Value::from), + ScalarAttributeType::B => IntoRustByName::::get_by_name(row, col) + .map_err(parse)? + .map(Value::from), + }; + Ok((pk, value.map(|v| (format!("{col} > ?"), vec![v])))) +} + +/// Runs one read at the consistency level of [`Stmt::Read`] and returns its +/// rows, keeping the driver's error. +async fn rows_of( + session: &Arc, + query: &str, + values: Vec, + context: &'static str, +) -> Result, (&'static str, CdrsError)> { + let result = session + .run(Stmt::Read, query, QueryValues::SimpleValues(values)) + .await + .map_err(|e| (context, e))?; + let body = result.response_body().map_err(|e| (context, e))?; + Ok(body.into_rows().unwrap_or_default()) +} + +/// Up to `limit` rows of a scan within the inclusive `token_bounds` (the +/// whole ring when `None`). With no `position`, the rows from the lower +/// bound. Else the rows after `position`: the rest of its partition past its +/// clustering predicate (query 1, when it has one), then the partitions after +/// it in token order up to the upper bound (query 2). +pub(super) async fn scan_rows( + session: &Arc, + select_prefix: &str, + position: Option<&Position>, + token_bounds: Option<(i64, i64)>, + limit: usize, +) -> Result, (&'static str, CdrsError)> { + let Some((pk_text, clustering)) = position else { + let (bounds, values) = match token_bounds { + Some((lo, hi)) => ( + " WHERE token(pk) >= ? AND token(pk) <= ?", + vec![Value::from(lo), Value::from(hi)], + ), + None => ("", Vec::new()), + }; + let query = format!("{select_prefix}{bounds} LIMIT {limit}"); + return rows_of(session, &query, values, "scan_first_page").await; + }; + let mut all_rows = Vec::new(); + + if let Some((clustering_predicate, clustering_binds)) = clustering { + let query1 = + format!("{select_prefix} WHERE pk = ? AND {clustering_predicate} LIMIT {limit}"); + let mut values: Vec = Vec::with_capacity(1 + clustering_binds.len()); + values.push(Value::from(pk_text.as_str())); + values.extend(clustering_binds.iter().cloned()); + all_rows.extend(rows_of(session, &query1, values, "scan_finish_partition").await?); + } + + if all_rows.len() < limit { + let remaining = limit - all_rows.len(); + let token_clause = if token_bounds.is_some() { + " AND token(pk) <= ?" + } else { + "" + }; + let query2 = + format!("{select_prefix} WHERE token(pk) > token(?){token_clause} LIMIT {remaining}"); + let mut values: Vec = vec![Value::from(pk_text.as_str())]; + if let Some((_, hi)) = token_bounds { + values.push(Value::from(hi)); + } + all_rows.extend(rows_of(session, &query2, values, "scan_next_partitions").await?); + } + + Ok(all_rows) +} + +/// Runs `read` with `*limit` rows. A read Cassandra refuses with a read +/// failure runs again with half the rows, down to one; `*limit` ends as the +/// size that was read and `*ceiling` is lowered to it, so the reads after it +/// do not grow back past it. +pub(super) async fn read_halving( + limit: &mut usize, + ceiling: &mut usize, + mut read: F, +) -> Result, StorageError> +where + F: FnMut(usize) -> Fut, + Fut: Future, (&'static str, CdrsError)>>, +{ + loop { + match read(*limit).await { + Ok(rows) => return Ok(rows), + Err((context, CdrsError::Server { body, .. })) + if *limit > 1 && matches!(body.ty, ErrorType::ReadFailure(_)) => + { + tracing::warn!( + rows = *limit, + "{context}: read failure ({}), reading again with half the rows", + body.message + ); + *limit /= 2; + *ceiling = *limit; + } + Err((context, error)) => { + tracing::error!("{context} query failed: {error}"); + return Err(StorageError::Internal(format!("{context}: {error}"))); + } + } + } +} diff --git a/crates/storage-cassandra/src/data/scan.rs b/crates/storage-cassandra/src/data/scan.rs index 3c4c2d4f2..9b84f6291 100644 --- a/crates/storage-cassandra/src/data/scan.rs +++ b/crates/storage-cassandra/src/data/scan.rs @@ -41,6 +41,12 @@ //! additionally bounding the "next partitions" query with the segment's upper //! token bound. //! +//! ## Rows that hold no item +//! +//! The scan skips rows that hold no item (see `rows`). A page they leave +//! short still carries a LastEvaluatedKey when its read filled the LIMIT, and +//! a full read of nothing but such rows reads on after its last row. +//! //! ## Known limitation //! //! Token-based pagination can, in theory, skip partition keys that hash to the @@ -49,18 +55,16 @@ //! the "token range pagination" approach approved in the workplan. use cdrs_tokio::query::QueryValues; -use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::blob::Blob; use cdrs_tokio::types::value::Value; use extenddb_core::types::{Item, ScalarAttributeType, TableKeyInfo}; use extenddb_storage::error::StorageError; use extenddb_storage::util::{SortKeyValue, composite_pk_to_text, parse_sk, sk_column, sk_info}; -use std::sync::Arc; use super::ddl::{data_table_name, index_table_name}; use super::index::fetch_index_by_name; -use super::json_to_item; -use crate::cassandra_util::{self, CassandraSession}; +use super::rows::{RUN_READ_ROWS, read_halving, row_item, row_position, scan_rows}; +use crate::cassandra_util; /// Compute the inclusive `[lower, upper]` token bounds for a parallel-scan /// segment, or `None` when the whole ring should be scanned. @@ -100,23 +104,6 @@ fn sk_to_value(sk: &SortKeyValue) -> Value { } } -/// Execute a scan query that has no bind parameters and return the rows. -/// -/// Used for the first page (no `ExclusiveStartKey`), where the only predicates -/// are literal token-range bounds. -async fn rows_no_values( - session: &Arc, - query: &str, -) -> Result, StorageError> { - crate::cassandra_util::query_rows( - session, - query, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - "scan query failed", - ) - .await -} - impl crate::CassandraEngine { /// Implementation of `DataEngine::scan`. /// @@ -153,7 +140,6 @@ impl crate::CassandraEngine { }; let account_keyspace = self.account_keyspace(&key_info.account_id); - let select_prefix = format!("SELECT item_data FROM {account_keyspace}.{table_name}"); // Sort-key info for the scanned table/index, and (for index scans) the // base table's sort key — both are clustering columns on the index table. @@ -164,8 +150,21 @@ impl crate::CassandraEngine { None }; + // A base-table read also selects the primary key columns, so that a + // read whose rows all hold no item can go on after its last row. + let resume_sk_type = sk_info_opt + .filter(|_| index_name.is_none()) + .map(|(_, sk_type)| sk_type); + let select_prefix = if index_name.is_none() { + let sk_col = resume_sk_type + .map(|sk_type| format!(", {}", sk_column(sk_type))) + .unwrap_or_default(); + format!("SELECT item_data, pk{sk_col} FROM {account_keyspace}.{table_name}") + } else { + format!("SELECT item_data FROM {account_keyspace}.{table_name}") + }; + let token_bounds = segment_token_bounds(segment, total_segments); - let token_upper = token_bounds.map(|(_, hi)| hi); #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] let actual_limit = limit.map_or(1_000_000_usize, |l| l.max(0) as usize); @@ -181,60 +180,62 @@ impl crate::CassandraEngine { "scan: executing" ); - let rows = if let Some(start_key) = exclusive_start_key { - self.scan_paginated( - &session, - &select_prefix, - &scan_key_schema, - key_info, - sk_info_opt, - base_sk_info_opt, - index_name.is_some(), - start_key, - token_upper, - fetch_limit, - ) - .await? - } else { - // First page: full scan within the (optional) segment token range. - let mut query = select_prefix.clone(); - let mut values: Vec = Vec::new(); - if let Some((lo, hi)) = token_bounds { - query.push_str(" WHERE token(pk) >= ? AND token(pk) <= ?"); - values.push(Value::from(lo)); - values.push(Value::from(hi)); - } - query.push_str(&format!(" LIMIT {fetch_limit}")); - if values.is_empty() { - // Unrestricted full scan — no bind parameters. - rows_no_values(&session, &query).await? - } else { - cassandra_util::query_rows::( + // The first read starts after the ExclusiveStartKey when there is one. + let mut position = match exclusive_start_key { + Some(start_key) => Some(( + composite_pk_to_text(start_key, &scan_key_schema)?, + self.build_resume_clustering( + key_info, + sk_info_opt, + base_sk_info_opt, + index_name.is_some(), + start_key, + )?, + )), + None => None, + }; + + // Rows without item_data are skipped; a full read of nothing but such + // rows reads on after its last row (see "Rows that hold no item"). + // Every read, the first one included, is read again with half the + // rows when Cassandra refuses it with a read failure. + let mut read_limit = fetch_limit; + let mut ceiling = RUN_READ_ROWS.max(fetch_limit); + let (items, full) = loop { + let rows = read_halving(&mut read_limit, &mut ceiling, |limit| { + scan_rows( &session, - &query, - QueryValues::SimpleValues(values), - "scan_first_page", + &select_prefix, + position.as_ref(), + token_bounds, + limit, ) - .await? + }) + .await?; + let full = rows.len() >= read_limit; + let resume = match rows.last() { + Some(row) if full && index_name.is_none() => { + Some(row_position(row, resume_sk_type)?) + } + _ => None, + }; + let items = rows + .iter() + .map(|row| row_item(row, "scan")) + .filter_map(Result::transpose) + .collect::, _>>()?; + match resume { + Some(resume) if items.is_empty() => { + position = Some(resume); + read_limit = read_limit.saturating_mul(2).min(ceiling); + } + _ => break (items, full), } }; - // Parse item_data JSON into items. - let items: Vec = rows - .into_iter() - .map(|row| { - let item_data: Option = row.get_by_name("item_data").map_err(|error| { - StorageError::Internal(format!("scan parse item_data failed: {error}")) - })?; - item_data.map(json_to_item).transpose() - }) - .collect::, StorageError>>()? - .into_iter() - .flatten() - .collect(); - // Enforce the limit and derive the LastEvaluatedKey from the last item. - let has_more = items.len() > actual_limit; + // A full read may have items after it even when this page is short. + let has_more = full || items.len() > actual_limit; let final_items: Vec = items.into_iter().take(actual_limit).collect(); let last_key = if has_more { @@ -327,84 +328,6 @@ impl crate::CassandraEngine { Ok(token >= lower && token <= upper) } - /// Token-based two-query pagination for `scan_impl`. - #[allow(clippy::too_many_arguments)] - async fn scan_paginated( - &self, - session: &Arc, - select_prefix: &str, - scan_key_schema: &[extenddb_core::types::KeySchemaElement], - key_info: &TableKeyInfo, - sk_info_opt: Option<(&str, ScalarAttributeType)>, - base_sk_info_opt: Option<(&str, ScalarAttributeType)>, - is_index: bool, - start_key: &Item, - token_upper: Option, - fetch_limit: usize, - ) -> Result, StorageError> { - // Partition key text of the resume row (single or composite HASH key). - let pk_text = composite_pk_to_text(start_key, scan_key_schema)?; - - let mut all_rows = Vec::new(); - - // "Next partitions" upper token bound (bound parameter, if segmented). - let token_clause: &str = if token_upper.is_some() { - " AND token(pk) <= ?" - } else { - "" - }; - - // ── Query 1: finish the resume partition (only if there are clustering - // columns to advance past — i.e. the table/index has a sort key, or an - // index carries base-table key clustering columns). ────────────────── - let q1_clustering = self.build_resume_clustering( - key_info, - sk_info_opt, - base_sk_info_opt, - is_index, - start_key, - )?; - - if let Some((clustering_predicate, clustering_binds)) = q1_clustering { - let query1 = format!( - "{select_prefix} WHERE pk = ? AND {clustering_predicate} LIMIT {fetch_limit}" - ); - let mut values: Vec = Vec::with_capacity(1 + clustering_binds.len()); - values.push(Value::from(pk_text.as_str())); - values.extend(clustering_binds); - let rows1 = cassandra_util::query_rows::( - session, - &query1, - QueryValues::SimpleValues(values), - "scan_finish_partition", - ) - .await?; - all_rows.extend(rows1); - } - - // ── Query 2: subsequent partitions in token order. ────────────────────── - if all_rows.len() < fetch_limit { - let remaining = fetch_limit - all_rows.len(); - let query2 = format!( - "{select_prefix} WHERE token(pk) > token(?){token_clause} LIMIT {remaining}" - ); - let mut values: Vec = vec![Value::from(pk_text.as_str())]; - if let Some(hi) = token_upper { - values.push(Value::from(hi)); - } - let rows2 = cassandra_util::query_rows::( - session, - &query2, - QueryValues::SimpleValues(values), - "scan_next_partitions", - ) - .await?; - all_rows.extend(rows2); - } - - Ok(all_rows) - } - /// Build the clustering-comparison predicate for query 1 of pagination /// (the part after `pk = ? AND`), plus the bound values it references. /// diff --git a/crates/storage-cassandra/tests/common/mod.rs b/crates/storage-cassandra/tests/common/mod.rs index 19028ad30..bca2fb214 100644 --- a/crates/storage-cassandra/tests/common/mod.rs +++ b/crates/storage-cassandra/tests/common/mod.rs @@ -1040,3 +1040,186 @@ pub fn skip_without_cassandra() -> bool { } !reachable } + +/// The key of an item of a test table: `id`, and `sort` on a table with a +/// sort key. +pub fn key( + id: &str, + sort: Option, +) -> extenddb_core::types::Item { + let mut key = std::collections::BTreeMap::from([( + "id".to_string(), + extenddb_core::types::AttributeValue::S(id.to_string()), + )]); + if let Some(sort) = sort { + key.insert("sort".to_string(), sort); + } + key +} + +/// Puts the item with the key `key` and one more attribute, `v = "x"`. +pub async fn put(engine: &CassandraEngine, table: &TestTable, key: extenddb_core::types::Item) { + use extenddb_storage::DataEngine; + + let mut item = key; + item.insert( + "v".to_string(), + extenddb_core::types::AttributeValue::S("x".to_string()), + ); + engine + .put_item( + &table.key_info, + item, + false, + None, + &Default::default(), + None, + ) + .await + .expect("put_item"); +} + +/// The CQL name of `table`'s data table: `.items_`. +pub fn data_table(engine: &CassandraEngine, table: &TestTable) -> String { + format!( + "{}.items_{}", + engine.account_keyspace(&table.key_info.account_id), + table.key_info.table_id.replace('-', "_") + ) +} + +/// The column that holds `table`'s sort key: `sk_s`, `sk_n` or `sk_b`. +fn sort_key_column(table: &TestTable) -> &'static str { + let (_, sk_type) = extenddb_storage::util::sk_info( + &table.key_info.key_schema, + &table.key_info.attribute_definitions, + ) + .expect("a table with a sort key"); + extenddb_storage::util::sk_column(sk_type) +} + +/// Writes with CQL the row a TTL claim on the absent key `pk` (and `sk`, on +/// a table with a sort key) leaves: `prepared_txn_id` and +/// `prepared_txn_timestamp` set, and no `item_data`. +pub async fn claim_row( + engine: &CassandraEngine, + table: &TestTable, + pk: &str, + sk: Option, +) { + let set = format!( + "UPDATE {} SET prepared_txn_id = uuid(), prepared_txn_timestamp = 1 WHERE pk = ?", + data_table(engine, table) + ); + let session = engine.session_arc(); + match sk { + Some(sk) => { + let cql = format!("{set} AND {} = ?", sort_key_column(table)); + session + .query_with_values(cql, cdrs_tokio::query_values!(pk, sk)) + .await + } + None => { + session + .query_with_values(set, cdrs_tokio::query_values!(pk)) + .await + } + } + .expect("claim row"); +} + +/// Writes with CQL partition `pk` as DeleteItem leaves it on a table with a +/// sort key once its items are gone: the static delete timestamp, and a +/// deleted row for each sort key in `deleted`. +pub async fn emptied_partition( + engine: &CassandraEngine, + table: &TestTable, + pk: &str, + deleted: &[cdrs_tokio::types::value::Value], +) { + use cdrs_tokio::types::value::Value; + + let (t, col) = (data_table(engine, table), sort_key_column(table)); + let mut cql = format!( + "BEGIN UNLOGGED BATCH UPDATE {t} SET partition_max_delete_timestamp = 1 WHERE pk = ?; " + ); + let mut values = vec![Value::from(pk)]; + for sk in deleted { + cql.push_str(&format!("DELETE FROM {t} WHERE pk = ? AND {col} = ?; ")); + values.extend([Value::from(pk), sk.clone()]); + } + cql.push_str("APPLY BATCH"); + engine + .session_arc() + .query_with_values(cql, cdrs_tokio::query::QueryValues::SimpleValues(values)) + .await + .expect("emptied partition"); +} + +/// `column` of `system_views.` for `table`'s data table: one of +/// Cassandra's read metrics of that table, such as the `count` of +/// `local_scan_latency` or the `max` of `tombstones_per_read`. `None` before +/// the table's first read. +pub async fn data_table_metric( + engine: &CassandraEngine, + table: &TestTable, + view: &str, + column: &str, +) -> Option +where + cdrs_tokio::types::rows::Row: cdrs_tokio::types::IntoRustByName, +{ + use cdrs_tokio::types::IntoRustByName; + + let keyspace = engine.account_keyspace(&table.key_info.account_id); + let name = format!("items_{}", table.key_info.table_id.replace('-', "_")); + let rows = engine + .session_arc() + .query_with_values( + format!( + "SELECT {column} FROM system_views.{view} \ + WHERE keyspace_name = ? AND table_name = ?" + ), + cdrs_tokio::query_values!(keyspace.as_str(), name.as_str()), + ) + .await + .expect(view) + .response_body() + .expect(view) + .into_rows() + .unwrap_or_default(); + rows.first() + .and_then(|row| IntoRustByName::::get_by_name(row, column).expect(column)) +} + +/// Pages a Scan of `table` (or of one `(segment, total segments)` of it) +/// with `limit` to the end, and returns the items in the order read. +pub async fn scan_all( + engine: &CassandraEngine, + table: &TestTable, + limit: Option, + segment: Option<(i64, i64)>, +) -> Vec { + use extenddb_storage::DataEngine; + + let (mut all, mut start) = (Vec::new(), None); + for _ in 0..3000 { + let (items, last_key) = engine + .scan( + &table.key_info, + limit, + start.as_ref(), + segment.map(|(s, _)| s), + segment.map(|(_, t)| t), + None, + ) + .await + .expect("scan"); + all.extend(items); + match last_key { + Some(k) => start = Some(k), + None => return all, + } + } + panic!("more than 3000 pages"); +} diff --git a/crates/storage-cassandra/tests/direct/scan.rs b/crates/storage-cassandra/tests/direct/scan.rs index cb5d2a6c3..1eb4b8913 100644 --- a/crates/storage-cassandra/tests/direct/scan.rs +++ b/crates/storage-cassandra/tests/direct/scan.rs @@ -46,7 +46,7 @@ async fn put_pk_only_items( } /// Collect the `id` attribute (string) from a list of items. -fn ids(items: &[BTreeMap]) -> Vec { +pub(crate) fn ids(items: &[BTreeMap]) -> Vec { items .iter() .map(|item| match item.get("id") { diff --git a/crates/storage-cassandra/tests/direct/scan_rows_without_item.rs b/crates/storage-cassandra/tests/direct/scan_rows_without_item.rs new file mode 100644 index 000000000..2fd992f64 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/scan_rows_without_item.rs @@ -0,0 +1,265 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Scan over data rows that hold no item. +//! +//! A partition whose items have all been deleted answers a read with one row +//! of its static columns, and a TTL claim on an absent key writes a row with +//! no `item_data`. Neither row is an item. A page may come back short because +//! of them, but while items remain it carries a LastEvaluatedKey, so a reader +//! paging on from the last item reads every item. With a Limit under 1,000, a +//! long run of such rows is read in reads of at most 1,000 rows each, and no +//! read goes back to the start of the run. + +use cdrs_tokio::types::value::Value; +use extenddb_core::types::{AttributeValue, Item}; +use extenddb_storage::DataEngine; +use extenddb_storage_cassandra::CassandraEngine; +use futures::StreamExt; +use std::collections::BTreeSet; + +use crate::helpers::{ + TestTable, claim_row, data_table_metric, emptied_partition, key, put, scan_all, setup_engine, +}; +use crate::scan::ids; + +/// The key of item `id`: sort key "a" on a table with a sort key. +fn key_a(table: &TestTable, id: &str) -> Item { + let sort = (table.key_info.key_schema.len() > 1).then(|| AttributeValue::S("a".to_string())); + key(id, sort) +} + +async fn put_and_delete(engine: &CassandraEngine, table: &TestTable, id: &str) { + put(engine, table, key_a(table, id)).await; + engine + .delete_item( + &table.key_info, + &key_a(table, id), + false, + None, + &Default::default(), + None, + ) + .await + .expect("delete_item"); +} + +/// Pages through the table (or one segment of it) with `limit` and returns +/// every partition key read, in the order read. +async fn read_all( + engine: &CassandraEngine, + table: &TestTable, + limit: Option, + segment: Option<(i64, i64)>, +) -> Vec { + ids(&scan_all(engine, table, limit, segment).await) +} + +/// 30 live partitions among 300 emptied ones and 20 claim rows, so runs of +/// rows without an item sit between the items in token order. +async fn fill(engine: &CassandraEngine, table: &TestTable) -> BTreeSet { + let live: Vec = (0..30).map(|i| format!("live{i:03}")).collect(); + let emptied: Vec = (0..300).map(|i| format!("gone{i:03}")).collect(); + let claims: Vec = (0..20).map(|i| format!("claim{i:03}")).collect(); + let claim_sk = (table.key_info.key_schema.len() > 1).then(|| Value::from("a")); + futures::stream::iter(&live) + .for_each_concurrent(32, |id| put(engine, table, key_a(table, id))) + .await; + futures::stream::iter(&emptied) + .for_each_concurrent(32, |id| put_and_delete(engine, table, id)) + .await; + futures::stream::iter(&claims) + .for_each_concurrent(32, |id| claim_row(engine, table, id, claim_sk.clone())) + .await; + live.into_iter().collect() +} + +async fn assert_scans_read_every_item(engine: &CassandraEngine, table: &TestTable) { + let live = fill(engine, table).await; + for limit in [None, Some(1), Some(2), Some(7), Some(50)] { + let read = read_all(engine, table, limit, None).await; + assert_eq!(read.len(), live.len(), "limit {limit:?}: {read:?}"); + assert_eq!( + read.into_iter().collect::>(), + live, + "limit {limit:?}" + ); + } + for limit in [None, Some(1), Some(3)] { + let mut read = read_all(engine, table, limit, Some((0, 2))).await; + read.extend(read_all(engine, table, limit, Some((1, 2))).await); + assert_eq!( + read.len(), + live.len(), + "segments, limit {limit:?}: {read:?}" + ); + assert_eq!( + read.into_iter().collect::>(), + live, + "segments, limit {limit:?}" + ); + } +} + +#[tokio::test] +async fn test_scan_past_partitions_without_an_item() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanRowsWithoutItem", true).await; + assert_scans_read_every_item(&engine, &table).await; +} + +#[tokio::test] +async fn test_scan_of_a_hash_only_table_past_claim_rows() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanHashOnlyClaims", false).await; + assert_scans_read_every_item(&engine, &table).await; +} + +#[tokio::test] +async fn test_scan_of_a_table_with_no_item_left() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanNoItemLeft", true).await; + let emptied: Vec = (0..50).map(|i| format!("gone{i:03}")).collect(); + futures::stream::iter(&emptied) + .for_each_concurrent(32, |id| put_and_delete(&engine, &table, id)) + .await; + for limit in [None, Some(1), Some(7)] { + let (items, last_key) = engine + .scan(&table.key_info, limit, None, None, None, None) + .await + .expect("scan"); + assert!(items.is_empty(), "limit {limit:?}: {:?}", ids(&items)); + assert_eq!(last_key, None, "limit {limit:?}"); + } +} + +/// Writes `n` emptied partitions with CQL, as DeleteItem leaves them on a +/// table with a sort key: the static delete timestamp and a deleted row. +async fn emptied_partitions(engine: &CassandraEngine, table: &TestTable, n: usize) { + let ids: Vec = (0..n).map(|i| format!("gone{i:06}")).collect(); + let deleted = [Value::from("a")]; + futures::stream::iter(&ids) + .for_each_concurrent(8, |id| emptied_partition(engine, table, id, &deleted)) + .await; +} + +/// A run of claim rows inside one partition, ahead of an item in the same +/// partition: the scan reads on within the partition (query 1), not past it. +#[tokio::test] +async fn test_scan_past_claim_rows_inside_a_partition() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanClaimRun", true).await; + for i in 0..40 { + claim_row(&engine, &table, "p", Some(Value::from(format!("c{i:03}")))).await; + } + put( + &engine, + &table, + key("p", Some(AttributeValue::S("z".to_string()))), + ) + .await; + for limit in [None, Some(1), Some(3)] { + assert_eq!( + read_all(&engine, &table, limit, None).await, + ["p"], + "limit {limit:?}" + ); + } +} + +/// Checks Cassandra's `system_views.tombstones_per_read` histogram for +/// `table`: no read counted 1,500 tombstones or more. The histogram rounds +/// up: a read of 1,001 rows shows as about 1,109. +async fn assert_no_read_of_1500_tombstones(engine: &CassandraEngine, table: &TestTable) { + let max = data_table_metric::(engine, table, "tombstones_per_read", "max") + .await + .unwrap_or(0.0); + assert!( + max > 0.0, + "no tombstones counted, so the check proves nothing" + ); + assert!(max < 1_500.0, "one read counted {max} tombstones"); +} + +/// The range reads Cassandra has made of `table` (its +/// `system_views.local_scan_latency` count, which a refused read adds to as +/// well). The table is the test's own, so a change in the count is the +/// test's reads. +pub(crate) async fn range_reads(engine: &CassandraEngine, table: &TestTable) -> i64 { + data_table_metric::(engine, table, "local_scan_latency", "count") + .await + .unwrap_or(0) +} + +/// A run of emptied partitions longer than one bounded read, between items. +/// A paged Scan reads it in statements of at most 1,000 rows each, so no +/// single read of the data table counts more tombstones than that; a scan +/// that read the run again from its start with a growing LIMIT, or let the +/// read size grow without a cap, would read the whole run in one statement. +/// Each read takes twice the rows of the one before, so each pass reads the +/// run in at most 100 range reads; with reads that stay at the first read's +/// 2 rows, the Limit 1 pass takes about 2,500. +#[tokio::test] +async fn test_scan_past_a_long_run_of_emptied_partitions() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanEmptiedRun", true).await; + emptied_partitions(&engine, &table, 5_000).await; + let live: BTreeSet = (0..5).map(|i| format!("live{i}")).collect(); + for id in &live { + put(&engine, &table, key_a(&table, id)).await; + } + for limit in [Some(1), Some(2), Some(1000)] { + let before = range_reads(&engine, &table).await; + let read = read_all(&engine, &table, limit, None).await; + let reads = range_reads(&engine, &table).await - before; + assert_eq!(read.len(), live.len(), "limit {limit:?}: {read:?}"); + assert_eq!( + read.into_iter().collect::>(), + live, + "limit {limit:?}" + ); + assert!(reads <= 100, "limit {limit:?}: {reads} range reads"); + } + assert_no_read_of_1500_tombstones(&engine, &table).await; + // No Limit reads up to 1,000,001 rows in one statement, by design. + let read = read_all(&engine, &table, None, None).await; + assert_eq!(read.into_iter().collect::>(), live, "no limit"); +} + +/// A table with more emptied partitions than Cassandra's +/// `tombstone_failure_threshold` (100,000 by default). Each read of the run +/// stays below it, so the scan answers no item and no key, and no read +/// counts 1,500 tombstones or more. +#[tokio::test] +async fn test_scan_of_a_table_emptied_past_the_tombstone_threshold() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanEmptiedPastThreshold", true).await; + emptied_partitions(&engine, &table, 101_000).await; + for limit in [Some(1000), Some(128)] { + let (items, last_key) = engine + .scan(&table.key_info, limit, None, None, None, None) + .await + .expect("scan of an emptied table"); + assert!(items.is_empty(), "limit {limit:?}"); + assert_eq!(last_key, None, "limit {limit:?}"); + } + assert_no_read_of_1500_tombstones(&engine, &table).await; +} diff --git a/crates/storage-cassandra/tests/direct/scan_sort_key_types.rs b/crates/storage-cassandra/tests/direct/scan_sort_key_types.rs new file mode 100644 index 000000000..194bfdaee --- /dev/null +++ b/crates/storage-cassandra/tests/direct/scan_sort_key_types.rs @@ -0,0 +1,281 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Scan past rows that hold no item, by sort key type, and past emptied +//! partitions that each hold many deleted rows. +//! +//! A full read of rows that hold no item reads on after its last row, with +//! the row's sort key read back from Cassandra and bound again; the typed +//! tests check that this works for number, binary and string sort keys. A +//! read through partitions with many deleted rows can reach Cassandra's +//! `tombstone_failure_threshold` (100,000 by default); the scan then reads +//! again with fewer rows, the first read of a storage call included, and the +//! later reads of the call stay at that size. + +use bigdecimal::BigDecimal; +use cdrs_tokio::types::IntoRustByName; +use cdrs_tokio::types::blob::Blob; +use cdrs_tokio::types::decimal::Decimal; +use cdrs_tokio::types::value::Value; +use extenddb_core::types::{AttributeValue, ScalarAttributeType}; +use extenddb_storage::DataEngine; +use extenddb_storage_cassandra::CassandraEngine; +use futures::StreamExt; +use std::str::FromStr; + +use crate::helpers::{TestTable, claim_row, emptied_partition, key, put, scan_all, setup_engine}; +use crate::scan::ids; +use crate::scan_rows_without_item::range_reads; + +#[derive(Clone, Debug)] +enum Sk { + S(&'static str), + N(&'static str), + B(Vec), +} + +impl Sk { + fn attr(&self) -> AttributeValue { + match self { + Sk::S(s) => AttributeValue::S((*s).to_string()), + Sk::N(n) => AttributeValue::N((*n).to_string()), + Sk::B(b) => AttributeValue::B(b.clone()), + } + } + + fn bind(&self) -> Value { + match self { + Sk::S(s) => Value::from(*s), + Sk::N(n) => { + let (unscaled, scale) = BigDecimal::from_str(n) + .expect("decimal") + .as_bigint_and_exponent(); + Value::from(Decimal::new(unscaled, i32::try_from(scale).expect("scale"))) + } + Sk::B(b) => Value::from(Blob::new(b.clone())), + } + } +} + +/// Numbers are stored in a normal form, so they are compared by value. +fn canon(v: &AttributeValue) -> String { + match v { + AttributeValue::N(n) => BigDecimal::from_str(n) + .expect("number") + .normalized() + .to_string(), + other => format!("{other:?}"), + } +} + +/// Partition `p` holding `rows` in sort key order (a claim row or an item +/// each), and 40 emptied partitions. Every page size reads exactly the items +/// of `p`, once each and in order. +async fn check_typed(ty: ScalarAttributeType, name: &str, rows: Vec<(Sk, bool)>, gone: Sk) { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::with_sort_key_type(&engine, name, ty).await; + for (sk, is_item) in &rows { + if *is_item { + put(&engine, &table, key("p", Some(sk.attr()))).await; + } else { + claim_row(&engine, &table, "p", Some(sk.bind())).await; + } + } + for i in 0..40 { + emptied_partition(&engine, &table, &format!("gone{i:02}"), &[gone.bind()]).await; + } + let want: Vec = rows + .iter() + .filter(|(_, is_item)| *is_item) + .map(|(sk, _)| canon(&sk.attr())) + .collect(); + for limit in [Some(1), Some(2), Some(3), Some(7), None] { + let items = scan_all(&engine, &table, limit, None).await; + let got: Vec = items + .iter() + .map(|item| canon(item.get("sort").expect("sort"))) + .collect(); + assert_eq!(got, want, "limit {limit:?}"); + } +} + +#[tokio::test] +async fn test_scan_past_claim_rows_with_a_number_sort_key() { + let rows = vec![ + (Sk::N("-123456789012345678901234567890.123456789"), false), + (Sk::N("-99999.5"), false), + (Sk::N("-99999"), true), + (Sk::N("-0.000000000000000000000000000001"), false), + (Sk::N("0"), true), + (Sk::N("0.1"), false), + (Sk::N("0.10000000000000000000000000000000000001"), false), + (Sk::N("0.2"), true), + (Sk::N("1.000000000000000000000000000000000001"), false), + (Sk::N("1E+5"), false), + (Sk::N("1E+10"), true), + (Sk::N("9.9999999999999999999999999999999999998E+125"), false), + (Sk::N("9.9999999999999999999999999999999999999E+125"), false), + ]; + check_typed(ScalarAttributeType::N, "ScanClaimNumber", rows, Sk::N("5")).await; +} + +#[tokio::test] +async fn test_scan_past_claim_rows_with_a_binary_sort_key() { + let b = |bytes: &[u8]| Sk::B(bytes.to_vec()); + let rows = vec![ + (b(&[0x00]), false), + (b(&[0x00, 0x00]), false), + (b(&[0x00, 0x01]), true), + (b(&[0x7f, 0xff]), false), + (b(&[0x80]), true), + (b(&[0x80, 0x00]), false), + (b(&[0xab; 1024]), false), + (b(&[0xfe]), true), + (b(&[0xff, 0x00]), false), + (b(&[0xff, 0xff, 0x01]), true), + (b(&[0xff, 0xff, 0xff]), false), + ]; + check_typed(ScalarAttributeType::B, "ScanClaimBinary", rows, b(&[0x01])).await; +} + +#[tokio::test] +async fn test_scan_past_claim_rows_with_a_string_sort_key() { + let rows = vec![ + (Sk::S("A"), false), + (Sk::S("a"), true), + (Sk::S("\u{e9}"), false), + (Sk::S("\u{65e5}\u{672c}"), false), + (Sk::S("\u{1f600}"), true), + (Sk::S("\u{1f601}"), false), + ]; + check_typed(ScalarAttributeType::S, "ScanClaimString", rows, Sk::S("a")).await; +} + +/// The sort keys `s000` onwards of the `n` deleted rows of an emptied +/// partition. +fn deleted_rows(n: usize) -> Vec { + (0..n).map(|j| Value::from(format!("s{j:03}"))).collect() +} + +async fn token_of(engine: &CassandraEngine, pk: &str) -> i64 { + let rows = engine + .session_arc() + .query_with_values( + "SELECT token(?) AS t FROM system.local", + cdrs_tokio::query_values!(pk), + ) + .await + .expect("token") + .response_body() + .expect("body") + .into_rows() + .expect("rows"); + IntoRustByName::::get_by_name(&rows[0], "t") + .expect("decode") + .expect("not null") +} + +/// `n` partition keys ``, in token order. +async fn keys_in_token_order(engine: &CassandraEngine, prefix: &str, n: usize) -> Vec { + let mut tokens = Vec::with_capacity(n); + for i in 0..n { + let pk = format!("{prefix}{i:04}"); + tokens.push((token_of(engine, &pk).await, pk)); + } + tokens.sort(); + tokens.into_iter().map(|(_, pk)| pk).collect() +} + +/// 2,100 emptied partitions that each held 110 rows, and one item in the +/// partition with the highest token. A read of 1,000 such rows counts about +/// 110,000 tombstones, past the threshold; a read of 500 counts about 55,000. +/// A Scan with a small Limit reads through all of them to the item. +#[tokio::test] +async fn test_scan_past_emptied_partitions_with_many_deleted_rows() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanHeavyEmptied", true).await; + let mut pks = keys_in_token_order(&engine, "heavy", 2101).await; + let live = pks.pop().expect("partition keys"); + let deleted = deleted_rows(110); + futures::stream::iter(&pks) + .for_each_concurrent(8, |pk| emptied_partition(&engine, &table, pk, &deleted)) + .await; + put( + &engine, + &table, + key(&live, Some(AttributeValue::S("a".to_string()))), + ) + .await; + for limit in [Some(1), Some(128)] { + let items = scan_all(&engine, &table, limit, None).await; + assert_eq!(ids(&items), std::slice::from_ref(&live), "limit {limit:?}"); + } +} + +/// Five items at the lowest tokens, then 300 emptied partitions that each +/// held 400 rows. The engine reads a page in storage calls: the first, with +/// Limit 128, reads the 5 items and 124 emptied partitions and returns the +/// fifth item's key. The second, with Limit 1,024, starts after that item. +/// Its reads of 1,025, 512 and 256 rows pass more than 100,000 tombstones, +/// and Cassandra refuses each of them. Each refused read runs again with half +/// the rows, and the later reads of the call stay at 128 rows. So the call +/// answers no item and no key in 6 range reads: the 3 refused ones, then 128, +/// 128 and 44 rows. Later reads that grew back to 256 rows would take the +/// last 172 partitions in one read, for 5 range reads. +#[tokio::test] +async fn test_scan_after_items_past_partitions_with_many_deleted_rows() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "ScanHeavyAfterItems", true).await; + let mut gone = keys_in_token_order(&engine, "p", 305).await; + let live: Vec = gone.drain(..5).collect(); + let sort = || Some(AttributeValue::S("a".to_string())); + for pk in &live { + put(&engine, &table, key(pk, sort())).await; + } + let deleted = deleted_rows(400); + futures::stream::iter(&gone) + .for_each_concurrent(8, |pk| emptied_partition(&engine, &table, pk, &deleted)) + .await; + + let (items, last_key) = engine + .scan(&table.key_info, Some(128), None, None, None, None) + .await + .expect("scan, Limit 128"); + assert_eq!(ids(&items), live); + assert_eq!(last_key, Some(key(&live[4], sort()))); + let before = range_reads(&engine, &table).await; + let (items, last_key) = engine + .scan( + &table.key_info, + Some(1024), + last_key.as_ref(), + None, + None, + None, + ) + .await + .expect("scan after the fifth item, Limit 1024"); + let reads = range_reads(&engine, &table).await - before; + assert_eq!((ids(&items), last_key), (Vec::::new(), None)); + assert_eq!(reads, 6, "range reads of the call after the fifth item"); + + // CreateBackup, export and the TTL work read with Limit 1,000 from the + // start. Cassandra refuses that first read of 1,001 rows and its retry + // of 500. A read of 250 rows passes 245 emptied partitions (98,000 + // tombstones) and returns the 5 items with the fifth item's key. + let (items, last_key) = engine + .scan(&table.key_info, Some(1000), None, None, None, None) + .await + .expect("scan from the start, Limit 1000"); + assert_eq!(ids(&items), live); + assert_eq!(last_key, Some(key(&live[4], sort()))); +} diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 1a7efefab..8d663380a 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -64,6 +64,10 @@ mod query; mod roles; #[path = "direct/scan.rs"] mod scan; +#[path = "direct/scan_rows_without_item.rs"] +mod scan_rows_without_item; +#[path = "direct/scan_sort_key_types.rs"] +mod scan_sort_key_types; #[path = "direct/secret_rows.rs"] mod secret_rows; #[path = "direct/settings_store.rs"] diff --git a/tests/test_scan_emptied_partitions.py b/tests/test_scan_emptied_partitions.py new file mode 100644 index 000000000..56fe5ae09 --- /dev/null +++ b/tests/test_scan_emptied_partitions.py @@ -0,0 +1,136 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Scan of a table whose items sit among partitions whose items were deleted. + +Amazon DynamoDB answers such a Scan with every live item and counts only +live items in ScannedCount, with no Limit, with a Limit, across parallel +segments, with Select COUNT and with a FilterExpression. Measured on +2026-10-26 at 15:29 UTC (us-east-1), each case twice. The measurement wrote +30 live items and 100 partitions whose one item it put and then deleted, in +a table that already held 29 other items. With Limit 1, a Scan of that +table's 59 live items took 60 pages: 59 with one item and a last one with +none. A table whose 50 items have all been deleted, with a sort key or hash +only, answers Count 0, ScannedCount 0 and no LastEvaluatedKey with no Limit +and with Limit 1 and 7. Measured at 16:39 UTC, each case twice. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest + +from conftest import scoped_table + +LIVE = [f"live-{i:02d}" for i in range(30)] +GONE = [f"gone-{i:03d}" for i in range(100)] + + +def _key(pk, sort_key): + key = {"pk": {"S": pk}} + if sort_key: + key["sk"] = {"S": "a"} + return key + + +def _fill(client, name, sort_key): + for pk in LIVE: + client.put_item(TableName=name, Item={**_key(pk, sort_key), "x": {"S": "x"}}) + for pk in GONE: + client.put_item(TableName=name, Item={**_key(pk, sort_key), "x": {"S": "x"}}) + client.delete_item(TableName=name, Key=_key(pk, sort_key)) + + +SORT_KEY_TABLE = { + "attribute_definitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + ], + "key_schema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], +} + + +@pytest.fixture(scope="module", params=["sort_key", "hash_only"]) +def table(request, dynamodb_client): + sort_key = request.param == "sort_key" + with scoped_table(dynamodb_client, **(SORT_KEY_TABLE if sort_key else {})) as name: + _fill(dynamodb_client, name, sort_key) + yield name + + +def _page_all(client, name, **kw): + pks, pages, start = [], [], None + for _ in range(500): + args = {"TableName": name, "ConsistentRead": True, **kw} + if start: + args["ExclusiveStartKey"] = start + resp = client.scan(**args) + pages.append(resp) + pks += [item["pk"]["S"] for item in resp.get("Items", [])] + start = resp.get("LastEvaluatedKey") + if not start: + return pks, pages + raise AssertionError("more than 500 pages") + + +def test_scan_with_no_limit(dynamodb_client, table): + pks, pages = _page_all(dynamodb_client, table) + assert len(pages) == 1 + assert (pages[0]["Count"], pages[0]["ScannedCount"]) == (30, 30) + assert sorted(pks) == LIVE + + +@pytest.mark.parametrize("limit", [1, 7, 50]) +def test_scan_pages_through_every_item(dynamodb_client, table, limit): + """On this file's table of 30 items, the service answers 31 pages with + Limit 1 (30 with one item and a last one with none) and 5 pages with + Limit 7, measured in the review of #612 on 2026-11-24 + (https://github.com/ExtendDB/extenddb/pull/612#pullrequestreview-6049018549). + No page count is pinned for Limit 50, which has no such measurement. + """ + pks, pages = _page_all(dynamodb_client, table, Limit=limit) + assert sorted(pks) == LIVE + first = pages[0] + expected = min(limit, 30) + assert (first["Count"], first["ScannedCount"]) == (expected, expected) + measured_pages = {1: 31, 7: 5}.get(limit) + if measured_pages is not None: + assert len(pages) == measured_pages + + +def test_parallel_scan_reads_every_item(dynamodb_client, table): + pks = [] + for segment in (0, 1): + seg_pks, _ = _page_all(dynamodb_client, table, Limit=3, Segment=segment, TotalSegments=2) + pks += seg_pks + assert sorted(pks) == LIVE + + +def test_scan_count(dynamodb_client, table): + _, pages = _page_all(dynamodb_client, table, Select="COUNT") + assert sum(p["Count"] for p in pages) == 30 + + +def test_scan_with_a_filter(dynamodb_client, table): + flt = {"FilterExpression": "begins_with(pk, :p)", "ExpressionAttributeValues": {":p": {"S": "live-0"}}} + pks, pages = _page_all(dynamodb_client, table, **flt) + assert (pages[0]["Count"], pages[0]["ScannedCount"]) == (10, 30) + assert sorted(pks) == LIVE[:10] + pks, _ = _page_all(dynamodb_client, table, Limit=7, **flt) + assert sorted(pks) == LIVE[:10] + + +@pytest.mark.parametrize("sort_key", [True, False], ids=["sort_key", "hash_only"]) +def test_scan_of_a_table_with_no_item_left(dynamodb_client, sort_key): + with scoped_table(dynamodb_client, **(SORT_KEY_TABLE if sort_key else {})) as name: + for pk in GONE[:50]: + dynamodb_client.put_item(TableName=name, Item={**_key(pk, sort_key), "x": {"S": "x"}}) + dynamodb_client.delete_item(TableName=name, Key=_key(pk, sort_key)) + for kw in ({}, {"Limit": 1}, {"Limit": 7}): + resp = dynamodb_client.scan(TableName=name, ConsistentRead=True, **kw) + assert (resp["Count"], resp["ScannedCount"]) == (0, 0), kw + assert "LastEvaluatedKey" not in resp, kw