From 005888658271e2ab8ebf67c9202ed55a4470cc41 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Mon, 26 Oct 2026 02:30:01 +0000 Subject: [PATCH 1/4] fix(cassandra): give every data-path statement a consistency level Every statement on the Cassandra data path that did not state a consistency level ran at the driver default, ONE: GetItem, Query and Scan, the OCC and put-if-absent lightweight transactions, the plain delete, and the TransactWriteItems prepare and commit statements. With the default keyspace replication factor of 3, a ConsistentRead: true read could return an item as it was before a write the client had seen acknowledged (issue #560). Each statement under data/ now states its level through one of four constructors in cassandra_util: - read_params(consistent_read): LOCAL_QUORUM for true, LOCAL_ONE for false - write_params: LOCAL_QUORUM, for a write with no IF clause - lwt_params: LOCAL_QUORUM with serial consistency LOCAL_SERIAL, for a statement with an IF clause - batch_builder: a BatchQueryBuilder at LOCAL_QUORUM, for every batch GetItem, Query and Scan pass ReadOptions::consistent_read. The reads whose result decides a write run at LOCAL_QUORUM. Those are the OCC reads before a put, update or delete and the transaction, idempotency token and ledger reads. The export scan, the TTL backfill and table size scans and the GSI backfill read at LOCAL_QUORUM too, so that a page reflects every write acknowledged before it was read. Catalog and queue metadata reads that ran at ONE run at LOCAL_ONE. The backend creates each keyspace with NetworkTopologyStrategy in the one datacenter named by `datacenter`, so a LOCAL_QUORUM read and a LOCAL_QUORUM write each reach a majority of the same replicas and a true read reflects every write acknowledged before it started. Schema statements stay at the driver default. GetItem derives the partition key with composite_pk_to_text, as the write path does, so a table whose key has more than one HASH attribute reads its row; the TTL worker's quorum read shares the derivation. clippy.toml disallows the Session calls (query, query_with_values, exec, exec_with_values, paged), StatementParamsBuilder::new, BatchQueryBuilder::new and the cassandra_util helpers that run at the driver default. The crate allows the lint outside data/, where clippy counts 225 of those calls in the catalog, metadata, backup and bootstrap code, and data/mod.rs turns it back on. The lint cannot see which constructor a call passes, so a test in data/level_pairing_tests.rs reads the statement sites under data/ whose CQL and level it can resolve (121 on this tree) and checks that a SELECT carries a read level, a plain write write_params and an IF statement lwt_params, and that no BatchQueryBuilder::new, BatchQueryBuilder::default, Default::default() or .with_consistency( appears under data/, so a batch is built by batch_builder() or not at all. The integration test crates allow the lint for their setup statements. A base-row write now waits for a local quorum to acknowledge its commit, and a ConsistentRead: true read needs a local quorum to answer: two of three replicas at the default replication factor. The lightweight transactions already needed a Paxos majority. The replication_factor and datacenter docs in config.rs, the upgrade manual and the differences table say so. ADR-0025 records the levels, the trade and the lint; the storage and HA designs, the backend author manual and the ReadOptions doc state the new levels and cite it. Tests: unit tests check the levels each constructor sets. A direct integration test reads an item through GetItem, Query and Scan with both ConsistentRead values. A second raises the account keyspace to replication factor 3 on a one-node cluster, where LOCAL_ONE can be met and LOCAL_QUORUM cannot: the false reads return the item and the true reads are refused. A third reads a row of a table with a two-part HASH key. --- clippy.toml | 21 + crates/storage-cassandra/src/backup_engine.rs | 1 + .../storage-cassandra/src/cassandra_util.rs | 250 ++++++++-- crates/storage-cassandra/src/config.rs | 16 + .../storage-cassandra/src/data/data_engine.rs | 35 +- crates/storage-cassandra/src/data/ddl.rs | 46 +- .../storage-cassandra/src/data/delete_item.rs | 74 +-- crates/storage-cassandra/src/data/index.rs | 47 +- .../src/data/level_pairing_tests.rs | 457 ++++++++++++++++++ crates/storage-cassandra/src/data/mod.rs | 260 ++++------ .../src/data/put_get_item.rs | 113 ++--- crates/storage-cassandra/src/data/query.rs | 40 +- .../src/data/query_helpers.rs | 83 +++- crates/storage-cassandra/src/data/scan.rs | 57 +-- .../src/data/transaction_ledger.rs | 35 +- .../src/data/transactions.rs | 176 ++++--- crates/storage-cassandra/src/data/ttl.rs | 26 +- .../storage-cassandra/src/data/update_item.rs | 19 +- crates/storage-cassandra/src/lib.rs | 6 + .../storage-cassandra/src/metadata_engine.rs | 30 +- .../tests/direct/consistent_read.rs | 316 ++++++++++++ .../tests/direct_integration.rs | 6 + crates/storage-cassandra/tests/ttl_bench.rs | 4 + .../tests/ttl_integration.rs | 4 + crates/storage/src/lib.rs | 9 +- ...-cassandra-statement-consistency-levels.md | 123 +++++ docs/adr/README.md | 3 +- docs/design/04-component-storage.md | 12 +- docs/design/11-high-availability.md | 21 +- docs/differences-from-dynamodb.md | 1 + docs/manuals/07-upgrade-manual.md | 48 ++ docs/manuals/12-extending-extenddb-storage.md | 2 +- 32 files changed, 1795 insertions(+), 546 deletions(-) create mode 100644 clippy.toml create mode 100644 crates/storage-cassandra/src/data/level_pairing_tests.rs create mode 100644 crates/storage-cassandra/tests/direct/consistent_read.rs create mode 100644 docs/adr/0025-cassandra-statement-consistency-levels.md diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 000000000..f8f622bcf --- /dev/null +++ b/clippy.toml @@ -0,0 +1,21 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 +# +# The Cassandra data path states the consistency level of every statement it +# runs. Each entry below runs a statement at the driver default, `ONE`, or +# builds parameters or a batch at it. The extenddb-storage-cassandra crate +# allows them outside `src/data/`, and `src/data/mod.rs` turns the lint back on +# for the data path, where the only allow is on a schema statement. +disallowed-methods = [ + { path = "cdrs_tokio::cluster::session::Session::query_with_values", reason = "the data path states its consistency: use cassandra_util::{query_rows_at, query_optional_at, execute_quorum, query_lwt}, or query_with_params / execute_at with read_params, write_params or lwt_params" }, + { path = "cdrs_tokio::cluster::session::Session::query", reason = "the data path states its consistency: use cassandra_util::{query_rows_at, query_optional_at, execute_quorum, query_lwt}, or query_with_params / execute_at with read_params, write_params or lwt_params" }, + { path = "cdrs_tokio::query::BatchQueryBuilder::new", reason = "a batch starts at the driver default: the data path builds batches with cassandra_util::batch_builder" }, + { path = "cdrs_tokio::cluster::session::Session::exec", reason = "the data path states its consistency: run a prepared statement through execute_at with read_params, write_params or lwt_params" }, + { path = "cdrs_tokio::cluster::session::Session::exec_with_values", reason = "the data path states its consistency: run a prepared statement through execute_at with read_params, write_params or lwt_params" }, + { path = "cdrs_tokio::cluster::session::Session::paged", reason = "the data path states its consistency: page with query_rows_at and a paging state in the parameters" }, + { path = "cdrs_tokio::statement::StatementParamsBuilder::new", reason = "the data path builds statement parameters only through cassandra_util::{read_params, write_params, lwt_params}" }, + { path = "extenddb_storage_cassandra::cassandra_util::query_rows", reason = "runs at the driver default: the data path uses query_rows_at" }, + { path = "extenddb_storage_cassandra::cassandra_util::query_optional", reason = "runs at the driver default: the data path uses query_optional_at" }, + { path = "extenddb_storage_cassandra::cassandra_util::execute", reason = "runs at the driver default: the data path uses execute_quorum" }, + { path = "extenddb_storage_cassandra::cassandra_util::apply_lwt", reason = "runs at the driver default: the data path uses query_lwt or execute_at with lwt_params" }, +] diff --git a/crates/storage-cassandra/src/backup_engine.rs b/crates/storage-cassandra/src/backup_engine.rs index 7c070934e..88a908c46 100755 --- a/crates/storage-cassandra/src/backup_engine.rs +++ b/crates/storage-cassandra/src/backup_engine.rs @@ -1512,6 +1512,7 @@ impl BackupEngine for CassandraEngine { None, None, None, + true, ) .await?; for item in items { diff --git a/crates/storage-cassandra/src/cassandra_util.rs b/crates/storage-cassandra/src/cassandra_util.rs index a4ebf5c0c..22d436ed6 100644 --- a/crates/storage-cassandra/src/cassandra_util.rs +++ b/crates/storage-cassandra/src/cassandra_util.rs @@ -5,8 +5,11 @@ use cdrs_tokio::cluster::TcpConnectionManager; use cdrs_tokio::cluster::session::Session; +use cdrs_tokio::consistency::Consistency; +use cdrs_tokio::frame::Envelope; use cdrs_tokio::load_balancing::RoundRobinLoadBalancingStrategy; use cdrs_tokio::query::QueryValues; +use cdrs_tokio::statement::{StatementParams, StatementParamsBuilder}; use cdrs_tokio::transport::TransportTcp; use cdrs_tokio::types::rows::Row; use std::sync::Arc; @@ -17,25 +20,146 @@ pub type CassandraSession = Session< RoundRobinLoadBalancingStrategy, >; -/// Execute a lightweight transaction with explicit regional quorum and serial -/// consistency. TTL claims and lifecycle metadata use this rather than the -/// driver's default consistency. -pub async fn query_lwt( - session: &CassandraSession, - query: &str, - values: QueryValues, -) -> Result { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::statement::StatementParamsBuilder; +// ══════════════════════════════════════════════════════════════════════════════ +// Statement consistency for the data path +// ══════════════════════════════════════════════════════════════════════════════ +// +// Every statement under `data/` states its level through `read_params`, +// `write_params` or `lwt_params`; schema statements in `data/ddl.rs` are the +// one exception. `clippy.toml` disallows the driver calls that run at the +// driver default, `Consistency::One`, and `data/mod.rs` turns that lint on for +// the data path. + +/// The level a data-path read runs at for a request's `ConsistentRead`. +/// +/// Base-row writes and lightweight transactions are acknowledged at +/// `LOCAL_QUORUM` ([`write_params`], [`lwt_params`]). A `LOCAL_QUORUM` read +/// intersects that write set within the datacenter, because a quorum plus a +/// quorum exceeds the replication factor, so a `true` read reflects every +/// write acknowledged before it started. `LOCAL_ONE` reads one replica and +/// may miss recently acknowledged writes, which is the contract for `false`. +#[must_use] +pub const fn read_consistency(consistent_read: bool) -> Consistency { + if consistent_read { + Consistency::LocalQuorum + } else { + Consistency::LocalOne + } +} + +/// Parameters for a data-path read at [`read_consistency`]. +#[must_use] +pub fn read_params(consistent_read: bool, values: QueryValues) -> StatementParams { + StatementParamsBuilder::new() + .with_consistency(read_consistency(consistent_read)) + .with_values(values) + .build() +} - let params = StatementParamsBuilder::new() +/// Parameters for a data-path write with no `IF` clause, acknowledged at +/// `LOCAL_QUORUM`. +#[must_use] +pub fn write_params(values: QueryValues) -> StatementParams { + StatementParamsBuilder::new() + .with_consistency(Consistency::LocalQuorum) + .with_values(values) + .build() +} + +/// A batch of plain writes, acknowledged at `LOCAL_QUORUM`. `Session::batch` +/// sends the builder's own consistency, and `BatchQueryBuilder::new()` starts +/// at the driver default, so every batch of the data path is built here. +#[must_use] +#[allow(clippy::disallowed_methods)] // the one place a batch builder is created +pub fn batch_builder() -> cdrs_tokio::query::BatchQueryBuilder { + cdrs_tokio::query::BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum) +} + +/// Parameters for a lightweight transaction (a statement with an `IF` +/// clause): the Paxos round runs at `LOCAL_SERIAL` and the commit is +/// acknowledged at `LOCAL_QUORUM`. +#[must_use] +pub fn lwt_params(values: QueryValues) -> StatementParams { + StatementParamsBuilder::new() .with_consistency(Consistency::LocalQuorum) .with_serial_consistency(Consistency::LocalSerial) .with_values(values) - .build(); + .build() +} + +/// Execute one statement with parameters from [`read_params`], +/// [`write_params`] or [`lwt_params`] and return the response envelope, from +/// which a lightweight transaction's `[applied]` column is read with +/// [`lwt_applied`]. +/// +/// # Errors +/// Returns an error if Cassandra does not execute the statement at the stated +/// level. +pub async fn execute_at( + session: &CassandraSession, + query: &str, + params: StatementParams, + context: &str, +) -> Result { session .query_with_params(query, params) .await + .map_err(|e| E::db_error(format!("{context}: {e}"))) +} + +/// Execute a data-path read at [`read_consistency`] and return all rows. +/// +/// # Errors +/// Returns an error if the Cassandra query fails or the response cannot be parsed. +pub async fn query_rows_at( + session: &CassandraSession, + query: &str, + values: QueryValues, + consistent_read: bool, + context: &str, +) -> Result, E> { + let result = session + .query_with_params(query, read_params(consistent_read, values)) + .await + .map_err(|e| { + tracing::error!("{context} query failed: {e}"); + E::db_error(format!("{context}: {e}")) + })?; + + let body = result.response_body().map_err(|e| { + tracing::error!("{context} response_body failed: {e}"); + E::db_error(format!("{context} response_body: {e}")) + })?; + + Ok(body.into_rows().unwrap_or_default()) +} + +/// [`query_rows_at`], returning the first row, if any. +/// +/// # Errors +/// Returns an error if the Cassandra query fails or the response cannot be parsed. +pub async fn query_optional_at( + session: &CassandraSession, + query: &str, + values: QueryValues, + consistent_read: bool, + context: &str, +) -> Result, E> { + let rows = query_rows_at(session, query, values, consistent_read, context).await?; + Ok(rows.into_iter().next()) +} + +/// Execute a lightweight transaction at [`lwt_params`]: a statement with an +/// `IF` clause runs with these parameters, through this helper or through +/// `query_with_params` and the `data/mod.rs` helpers. +pub async fn query_lwt( + session: &CassandraSession, + query: &str, + values: QueryValues, +) -> Result { + session + .query_with_params(query, lwt_params(values)) + .await .map_err(|error| { extenddb_storage::error::StorageError::Internal(format!("LWT query failed: {error}")) }) @@ -85,7 +209,11 @@ pub fn is_fk_violation(_err: &cdrs_tokio::error::Error) -> bool { // Phase 1: Core Query Helpers // ══════════════════════════════════════════════════════════════════════════════ -/// Execute a query and return all rows with standardized error handling. +/// Execute a query at the driver's default consistency, `ONE`, and return all +/// rows with standardized error handling. +/// +/// For catalog, metadata and backup reads outside the data path. A read under +/// `data/` states its level with [`query_rows_at`] instead. /// /// # Errors /// Returns an error if the Cassandra query fails or the response cannot be parsed. @@ -111,7 +239,8 @@ pub async fn query_rows( Ok(body.into_rows().unwrap_or_default()) } -/// Execute a query at `LOCAL_QUORUM` and return all rows. +/// Execute a query at `LOCAL_QUORUM` and return all rows: [`query_rows_at`] +/// with `consistent_read` set. /// /// [`query_rows`] uses the driver's default consistency, which is `ONE`. Use /// this instead wherever an *empty* result is treated as authoritative and acted @@ -124,32 +253,13 @@ pub async fn query_rows_quorum( values: QueryValues, context: &str, ) -> Result, E> { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::statement::StatementParamsBuilder; - - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_values(values) - .build(); - let result = session - .query_with_params(query, params) - .await - .map_err(|e| { - tracing::error!("{context} quorum query failed: {e}"); - E::db_error(format!("{context}: {e}")) - })?; - - let body = result.response_body().map_err(|e| { - tracing::error!("{context} response_body failed: {e}"); - E::db_error(format!("{context} response_body: {e}")) - })?; - - Ok(body.into_rows().unwrap_or_default()) + query_rows_at(session, query, values, true, context).await } /// Execute a query and return the first row, if any. /// -/// Similar to `sqlx::query().fetch_optional()`. +/// Similar to `sqlx::query().fetch_optional()`. Runs at the driver's default +/// consistency like [`query_rows`]; under `data/` use [`query_optional_at`]. /// /// # Errors /// Returns an error if the Cassandra query fails or the response cannot be parsed. @@ -163,7 +273,8 @@ pub async fn query_optional( Ok(rows.drain(..).next()) } -/// Execute a non-query statement (INSERT/UPDATE/DELETE). +/// Execute a non-query statement (INSERT/UPDATE/DELETE) at the driver's +/// default consistency; under `data/` use [`execute_quorum`]. /// /// # Errors /// Returns an error if the Cassandra statement fails. @@ -184,10 +295,10 @@ pub async fn execute( Ok(()) } -/// Execute a non-query statement at `LOCAL_QUORUM`. +/// Execute a non-query statement at [`write_params`] (`LOCAL_QUORUM`). /// -/// Use this for writes that are prerequisites for a later quorum operation or -/// whose loss would make an absence decision unsafe. +/// A plain write of the data path runs with [`write_params`]; this helper +/// runs one that returns no rows. A batch runs through [`batch_builder`]. /// /// # Errors /// Returns an error if Cassandra does not acknowledge the statement at quorum. @@ -197,15 +308,8 @@ pub async fn execute_quorum( values: QueryValues, context: &str, ) -> Result<(), E> { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::statement::StatementParamsBuilder; - - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_values(values) - .build(); session - .query_with_params(query, params) + .query_with_params(query, write_params(values)) .await .map_err(|error| { tracing::error!("{context} quorum execute failed: {error}"); @@ -343,6 +447,12 @@ pub fn lwt_applied( }) } +/// Execute a lightweight transaction at the driver's default consistency and +/// return whether it applied. +/// +/// For catalog and management writes outside the data path; a conditional +/// write under `data/` runs with [`lwt_params`] instead, through +/// [`query_lwt`], [`execute_at`] or `query_with_params`. /// /// Parses the `[applied]` column from the Cassandra LWT response. /// Use for `INSERT ... IF NOT EXISTS` and `UPDATE ... IF ...` statements. @@ -376,3 +486,47 @@ pub async fn apply_lwt( .and_then(|row| row.get_r_by_name("[applied]").ok()) .unwrap_or(false)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn bound() -> QueryValues { + cdrs_tokio::query_values!("pk", 7_i64) + } + + #[test] + fn consistent_read_selects_local_quorum_and_eventual_selects_local_one() { + assert_eq!(read_consistency(true), Consistency::LocalQuorum); + assert_eq!(read_consistency(false), Consistency::LocalOne); + } + + #[test] + fn read_params_carry_the_read_level_and_no_serial_level() { + for (consistent_read, level) in [ + (true, Consistency::LocalQuorum), + (false, Consistency::LocalOne), + ] { + let params = read_params(consistent_read, bound()).query_params; + assert_eq!(params.consistency, level); + assert_eq!(params.serial_consistency, None); + assert_eq!(params.values, Some(bound())); + } + } + + #[test] + fn write_params_are_local_quorum_with_no_serial_level() { + let params = write_params(bound()).query_params; + assert_eq!(params.consistency, Consistency::LocalQuorum); + assert_eq!(params.serial_consistency, None); + assert_eq!(params.values, Some(bound())); + } + + #[test] + fn lwt_params_commit_at_local_quorum_and_run_paxos_at_local_serial() { + let params = lwt_params(bound()).query_params; + assert_eq!(params.consistency, Consistency::LocalQuorum); + assert_eq!(params.serial_consistency, Some(Consistency::LocalSerial)); + assert_eq!(params.values, Some(bound())); + } +} diff --git a/crates/storage-cassandra/src/config.rs b/crates/storage-cassandra/src/config.rs index d631fd7bd..bd783f280 100644 --- a/crates/storage-cassandra/src/config.rs +++ b/crates/storage-cassandra/src/config.rs @@ -22,10 +22,26 @@ pub struct CassandraStorageConfig { pub keyspace_prefix: String, /// Replication factor for keyspaces (default: 3) + /// + /// Writes, and reads with `ConsistentRead: true`, need a local quorum + /// (`LOCAL_QUORUM`): `replication_factor / 2 + 1` replicas up in + /// `datacenter`, two of three at the default. Reads with + /// `ConsistentRead: false` need one (`LOCAL_ONE`). At 1, every statement + /// needs the one replica. The setting applies to keyspaces created after + /// it changes; an existing keyspace keeps its factor until altered + /// (ADR-0025). #[serde(default = "default_replication_factor")] pub replication_factor: u32, /// Datacenter name for `NetworkTopologyStrategy` (default: "datacenter1") + /// + /// Every keyspace replicates to this one datacenter, and `LOCAL_QUORUM` + /// and `LOCAL_ONE` are evaluated in the coordinator's datacenter. The + /// driver sends statements to every node it discovers, so the contact + /// points and their peers must all be in this datacenter; a coordinator + /// elsewhere refuses every `LOCAL_QUORUM` and `LOCAL_ONE` statement, which + /// is every data-path statement except the four schema statements in + /// `ddl.rs`. #[serde(default = "default_datacenter")] pub datacenter: String, diff --git a/crates/storage-cassandra/src/data/data_engine.rs b/crates/storage-cassandra/src/data/data_engine.rs index de6a49f0b..65ad9e57e 100644 --- a/crates/storage-cassandra/src/data/data_engine.rs +++ b/crates/storage-cassandra/src/data/data_engine.rs @@ -45,23 +45,28 @@ impl DataEngine for CassandraEngine { }) } - /// `_opts.consistent_read` is accepted and not acted on. Reads run at the - /// driver default consistency `ONE`, and the base-row writes (the OCC and - /// put-if-absent lightweight transactions, the plain delete, the - /// transaction commit) are acknowledged at `ONE` as well, so a `true` is - /// not honoured when the keyspace replication factor is above 1. Serving - /// `true` consistently needs those writes acknowledged at `LOCAL_QUORUM` - /// and `true` read at `LOCAL_QUORUM` (reads plus writes above the - /// replication factor); `false` can stay at `LOCAL_ONE`. + /// `opts.consistent_read: true` reads at `LOCAL_QUORUM` and `false` at + /// `LOCAL_ONE`. Base-row writes and the lightweight transactions (the OCC + /// and put-if-absent writes, the conditional and plain deletes, the + /// transaction prepare and commit) are acknowledged at `LOCAL_QUORUM`, with + /// serial consistency `LOCAL_SERIAL` for the lightweight transactions. + /// The backend creates each keyspace with `NetworkTopologyStrategy` in the + /// one datacenter named by `datacenter`, so a `LOCAL_QUORUM` read and a + /// `LOCAL_QUORUM` write each reach a majority of the same + /// `replication_factor` replicas, and a `true` read reflects every write + /// acknowledged before it started (ADR-0025). fn get_item( &self, key_info: &TableKeyInfo, key: &Item, - _opts: ReadOptions, + opts: ReadOptions, ) -> BoxFuture<'_, Result, StorageError>> { let key_info = key_info.clone(); let key = key.clone(); - Box::pin(async move { self.get_item_impl(&key_info, &key).await }) + Box::pin(async move { + self.get_item_impl(&key_info, &key, opts.consistent_read) + .await + }) } fn delete_item( @@ -123,7 +128,7 @@ impl DataEngine for CassandraEngine { }) } - /// `_opts`: see `get_item`. + /// `opts`: see `get_item`. fn query( &self, key_info: &TableKeyInfo, @@ -133,7 +138,7 @@ impl DataEngine for CassandraEngine { limit: Option, exclusive_start_key: Option<&Item>, index_name: Option<&str>, - _opts: ReadOptions, + opts: ReadOptions, ) -> BoxFuture<'_, Result<(Vec, Option), StorageError>> { let key_info = key_info.clone(); let key_condition = key_condition.clone(); @@ -149,12 +154,13 @@ impl DataEngine for CassandraEngine { limit, exclusive_start_key.as_ref(), index_name.as_deref(), + opts.consistent_read, ) .await }) } - /// `_opts`: see `get_item`. + /// `opts`: see `get_item`. fn scan( &self, key_info: &TableKeyInfo, @@ -163,7 +169,7 @@ impl DataEngine for CassandraEngine { segment: Option, total_segments: Option, index_name: Option<&str>, - _opts: ReadOptions, + opts: ReadOptions, ) -> BoxFuture<'_, Result<(Vec, Option), StorageError>> { let key_info = key_info.clone(); let exclusive_start_key = exclusive_start_key.cloned(); @@ -176,6 +182,7 @@ impl DataEngine for CassandraEngine { segment, total_segments, index_name.as_deref(), + opts.consistent_read, ) .await }) diff --git a/crates/storage-cassandra/src/data/ddl.rs b/crates/storage-cassandra/src/data/ddl.rs index 9016422dd..41a77f3df 100644 --- a/crates/storage-cassandra/src/data/ddl.rs +++ b/crates/storage-cassandra/src/data/ddl.rs @@ -84,18 +84,15 @@ impl CassandraEngine { FROM {catalog_keyspace}.tables WHERE account_id = ? AND table_name = ?" ); let values = cdrs_tokio::query_values!(account_id, table_name); - let rows = if quorum { - crate::cassandra_util::query_rows_quorum( - &self.session, - &query, - values, - "fetch_table_key_info", - ) - .await? - } else { - crate::cassandra_util::query_rows(&self.session, &query, values, "fetch_table_key_info") - .await? - }; + // `quorum` reads at `LOCAL_QUORUM`, otherwise at `LOCAL_ONE`. + let rows = crate::cassandra_util::query_rows_at( + &self.session, + &query, + values, + quorum, + "fetch_table_key_info", + ) + .await?; let row = rows .into_iter() @@ -270,6 +267,8 @@ impl CassandraEngine { ) }; + // A schema statement: DDL runs at the driver default. + #[allow(clippy::disallowed_methods)] self.session .query(&ddl) .await @@ -287,6 +286,8 @@ impl CassandraEngine { let ddb_table = data_table_name(table_id); let ddl = format!("DROP TABLE IF EXISTS {account_keyspace}.{ddb_table}"); + // A schema statement: DDL runs at the driver default. + #[allow(clippy::disallowed_methods)] self.session .query(&ddl) .await @@ -304,6 +305,8 @@ impl CassandraEngine { let idx_table = index_table_name(index_id); let ddl = format!("DROP TABLE IF EXISTS {account_keyspace}.{idx_table}"); + // A schema statement: DDL runs at the driver default. + #[allow(clippy::disallowed_methods)] self.session .query(&ddl) .await @@ -409,6 +412,8 @@ impl CassandraEngine { primary_key ); + // A schema statement: DDL runs at the driver default. + #[allow(clippy::disallowed_methods)] self.session .query(&ddl) .await @@ -443,8 +448,6 @@ pub(crate) async fn backfill_gsi( projection: &extenddb_core::types::Projection, ) -> Result<(), StorageError> { use crate::data::index::{insert_index_row_multi, item_has_index_keys, project_item_for_index}; - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::query::BatchQueryBuilder; const PAGE_SIZE: i64 = 500; @@ -471,20 +474,24 @@ pub(crate) async fn backfill_gsi( let mut last_token: Option = None; + // The backfill reads at `LOCAL_QUORUM`, like the other table walks, so a + // page reflects every write acknowledged before it was read. loop { let rows = if let Some(tok) = last_token { - crate::cassandra_util::query_rows::( + crate::cassandra_util::query_rows_at::( session, &next_page_query, cdrs_tokio::query_values!(tok), + true, "backfill_gsi", ) .await? } else { - crate::cassandra_util::query_rows::( + crate::cassandra_util::query_rows_at::( session, &first_page_query, cdrs_tokio::query_values!(), + true, "backfill_gsi", ) .await? @@ -494,7 +501,7 @@ pub(crate) async fn backfill_gsi( break; } - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch_builder(); let mut batch_has_rows = false; for row in &rows { @@ -536,7 +543,7 @@ pub(crate) async fn backfill_gsi( // Update heartbeat after each page so a recovery worker can // distinguish a live (slow) backfill from a crashed one. - if let Err(e) = crate::cassandra_util::execute::( + if let Err(e) = crate::cassandra_util::execute_quorum::( session, &heartbeat_cql, cdrs_tokio::query_values!(table_id, index_name), @@ -560,10 +567,11 @@ pub(crate) async fn backfill_gsi( let token_query = format!( "SELECT token(pk) AS tok FROM {account_keyspace}.{base_table} WHERE pk = ?" ); - let tok_rows = crate::cassandra_util::query_rows::( + let tok_rows = crate::cassandra_util::query_rows_at::( session, &token_query, cdrs_tokio::query_values!(pk.as_str()), + true, "backfill_gsi_token", ) .await?; diff --git a/crates/storage-cassandra/src/data/delete_item.rs b/crates/storage-cassandra/src/data/delete_item.rs index 08c1c297b..019d71c52 100644 --- a/crates/storage-cassandra/src/data/delete_item.rs +++ b/crates/storage-cassandra/src/data/delete_item.rs @@ -3,8 +3,6 @@ //! `delete_item` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; @@ -16,6 +14,7 @@ use super::ddl::data_table_name; use super::index::fetch_indexes_for_table; use super::{json_to_item, query_with_pk_sk}; use crate::CassandraEngine; +use crate::cassandra_util::{lwt_params, query_optional_at, read_params, write_params}; use crate::stream_util::stream_record_statement; /// Lifetime of the base-row claim an ordinary request holds while it commits @@ -219,8 +218,14 @@ impl CassandraEngine { "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let old_result = - query_with_pk_sk(&self.session, &select_query, pk_text.as_ref(), &sk).await?; + let old_result = query_with_pk_sk( + &self.session, + &select_query, + pk_text.as_ref(), + &sk, + |values| read_params(true, values), + ) + .await?; let body = old_result .response_body() @@ -361,14 +366,21 @@ impl CassandraEngine { && ttl_config.is_none() && ttl_claim.is_none() { - query_with_pk_sk(&self.session, &delete_cql, pk_text.as_ref(), &sk).await?; + query_with_pk_sk( + &self.session, + &delete_cql, + pk_text.as_ref(), + &sk, + write_params, + ) + .await?; } else { use super::index::sk_to_value; let delete_qv = cdrs_tokio::query::QueryValues::SimpleValues(vec![ cdrs_tokio::types::value::Value::from(pk_text.as_str()), sk_to_value(&sk), ]); - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch_builder(); if ttl_claim.is_some() { batch = batch.with_timestamp(mutation_timestamp); } @@ -468,10 +480,11 @@ impl CassandraEngine { "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ?" ); - let row = crate::cassandra_util::query_optional( + let row = query_optional_at( &self.session, &select_query, cdrs_tokio::query_values!(pk_text.as_str()), + true, "delete_item", ) .await?; @@ -611,14 +624,17 @@ impl CassandraEngine { && ttl_claim.is_none() { self.session - .query_with_values(&delete_cql, cdrs_tokio::query_values!(pk_text.as_str())) + .query_with_params( + &delete_cql, + write_params(cdrs_tokio::query_values!(pk_text.as_str())), + ) .await .map_err(|e| StorageError::Internal(format!("Delete failed: {e}")))?; } else { let delete_qv = cdrs_tokio::query::QueryValues::SimpleValues(vec![ cdrs_tokio::types::value::Value::from(pk_text.as_str()), ]); - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch_builder(); if ttl_claim.is_some() { batch = batch.with_timestamp(mutation_timestamp); } @@ -748,19 +764,22 @@ impl CassandraEngine { WHERE pk = ? AND {} = ?", sk_column(sk_type) ); - query_with_pk_sk(&self.session, &query, pk.as_str(), &sk) - .await? - .response_body() - .ok() - .and_then(cdrs_tokio::frame::message_response::ResponseBody::into_rows) - .and_then(|rows| rows.into_iter().next()) + query_with_pk_sk(&self.session, &query, pk.as_str(), &sk, |values| { + read_params(true, values) + }) + .await? + .response_body() + .ok() + .and_then(cdrs_tokio::frame::message_response::ResponseBody::into_rows) + .and_then(|rows| rows.into_iter().next()) } else { let query = format!("SELECT item_data, prepared_txn_id FROM {keyspace}.{table} WHERE pk = ?"); - crate::cassandra_util::query_optional( + query_optional_at( &self.session, &query, cdrs_tokio::query_values!(pk.as_str()), + true, "ensure_ttl_work_claim", ) .await? @@ -931,9 +950,7 @@ impl CassandraEngine { // with now-derived micros keeps it also above any older write. let restore_timestamp = (effects_timestamp_ms * 1_000 + 1).max(chrono::Utc::now().timestamp_micros()); - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_timestamp(restore_timestamp); + let mut batch = crate::cassandra_util::batch_builder().with_timestamp(restore_timestamp); // old = None: this is a pure re-upsert of the current image's rows. super::index::sync_indexes( &mut batch, @@ -996,9 +1013,8 @@ impl CassandraEngine { // identical cells at an identical timestamp, and so restoration (which // stamps strictly above this) beats these tombstones by construction // rather than by cross-coordinator clock luck. - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_timestamp(delete_timestamp_ms * 1_000); + let mut batch = + crate::cassandra_util::batch_builder().with_timestamp(delete_timestamp_ms * 1_000); let mut has_effects = !indexes.is_empty(); if !indexes.is_empty() { super::index::sync_indexes( @@ -1391,7 +1407,10 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query_null, cdrs_tokio::query_values!(now_ms, pk)) + .query_with_params( + &query_null, + lwt_params(cdrs_tokio::query_values!(now_ms, pk)), + ) .await .map_err(|e| { tracing::error!("update_partition_max_delete_timestamp (null): {e}"); @@ -1419,9 +1438,9 @@ impl CassandraEngine { ); self.session - .query_with_values( + .query_with_params( &query_compare, - cdrs_tokio::query_values!(now_ms, pk, now_ms), + lwt_params(cdrs_tokio::query_values!(now_ms, pk, now_ms)), ) .await .map_err(|e| { @@ -1476,10 +1495,7 @@ impl CassandraEngine { stream: Option<&extenddb_storage::StreamCapture>, sys_delay: u64, ) -> Result<(), StorageError> { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::query::BatchQueryBuilder; - - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch_builder(); if !indexes.is_empty() { super::index::sync_indexes( diff --git a/crates/storage-cassandra/src/data/index.rs b/crates/storage-cassandra/src/data/index.rs index 4ebd72dac..654f3d711 100644 --- a/crates/storage-cassandra/src/data/index.rs +++ b/crates/storage-cassandra/src/data/index.rs @@ -20,7 +20,7 @@ use extenddb_storage::util::{ use std::sync::Arc; use super::ddl::{all_sort_key_info, index_table_name}; -use crate::cassandra_util::{CassandraSession, get_column, query_rows}; +use crate::cassandra_util::{CassandraSession, get_column, query_rows_at}; /// Metadata for a single index, used during write-path GSI/LSI sync. #[derive(Clone)] @@ -47,7 +47,7 @@ pub async fn fetch_indexes_for_table( /// [`fetch_indexes_for_table`] at `LOCAL_QUORUM`. /// /// For paths where a stale-empty answer is acted on destructively or treated -/// as "nothing to restore": at the default consistency a lagging replica can +/// as "nothing to restore": at `LOCAL_ONE` a lagging replica can /// omit an index, and a must-complete restoration that trusts that omission /// leaves a live item permanently missing an index row. pub async fn fetch_indexes_for_table_quorum( @@ -69,23 +69,15 @@ async fn fetch_indexes_for_table_at( FROM {catalog_keyspace}.indexes WHERE table_id = ?" ); - let rows = if quorum { - crate::cassandra_util::query_rows_quorum( - session, - &query, - query_values!(table_id), - "fetch_indexes_for_table", - ) - .await? - } else { - query_rows( - session, - &query, - query_values!(table_id), - "fetch_indexes_for_table", - ) - .await? - }; + // `quorum` reads at `LOCAL_QUORUM`, otherwise at `LOCAL_ONE`. + let rows = query_rows_at( + session, + &query, + query_values!(table_id), + quorum, + "fetch_indexes_for_table", + ) + .await?; rows.into_iter() .map(|row| { @@ -136,10 +128,11 @@ pub async fn fetch_index_by_name( FROM {catalog_keyspace}.indexes WHERE table_id = ? AND index_name = ?" ); - let rows = query_rows( + let rows = query_rows_at( session, &query, query_values!(table_id, index_name), + false, "fetch_index_by_name", ) .await?; @@ -368,10 +361,11 @@ pub(crate) async fn enqueue_async_indexes( "SELECT last_ready_at FROM {account_keyspace}.gsi_pending \ WHERE worker_partition = ? LIMIT 1" ); - let rows = crate::cassandra_util::query_rows::( + let rows = query_rows_at::( session, &cql, query_values!(worker_partition), + false, "enqueue_async_indexes", ) .await?; @@ -412,7 +406,7 @@ pub(crate) async fn enqueue_async_indexes( cdrs_tokio::types::value::Value::from(context_json.as_str()), ]); - let old = std::mem::replace(batch, BatchQueryBuilder::new()); + let old = std::mem::replace(batch, crate::cassandra_util::batch_builder()); *batch = old.add_query(insert_cql, insert_qv); enqueued += 1; @@ -486,7 +480,7 @@ pub(crate) fn delete_index_row_multi( where_cols.join(" AND ") ); let qv = cdrs_tokio::query::QueryValues::SimpleValues(values); - let old = std::mem::replace(batch, BatchQueryBuilder::new()); + let old = std::mem::replace(batch, crate::cassandra_util::batch_builder()); *batch = old.add_query(cql, qv); Ok(()) } @@ -556,7 +550,7 @@ pub(crate) fn insert_index_row_multi( placeholders ); let qv = cdrs_tokio::query::QueryValues::SimpleValues(values); - let old = std::mem::replace(batch, BatchQueryBuilder::new()); + let old = std::mem::replace(batch, crate::cassandra_util::batch_builder()); *batch = old.add_query(cql, qv); Ok(()) } @@ -589,10 +583,11 @@ pub(crate) async fn delete_indexes_for_table( // Collect index IDs let index_query = format!("SELECT index_id FROM {catalog_keyspace}.indexes WHERE table_id = ?"); - let rows = query_rows( + let rows = query_rows_at( session, &index_query, query_values!(table_id), + false, "delete_indexes_for_table", ) .await?; @@ -606,7 +601,7 @@ pub(crate) async fn delete_indexes_for_table( // Delete index metadata from catalog let delete_query = format!("DELETE FROM {catalog_keyspace}.indexes WHERE table_id = ?"); - crate::cassandra_util::execute( + crate::cassandra_util::execute_quorum( session, &delete_query, query_values!(table_id), diff --git a/crates/storage-cassandra/src/data/level_pairing_tests.rs b/crates/storage-cassandra/src/data/level_pairing_tests.rs new file mode 100644 index 000000000..737a3b357 --- /dev/null +++ b/crates/storage-cassandra/src/data/level_pairing_tests.rs @@ -0,0 +1,457 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The pairing of each data-path statement's kind with the level it states, +//! checked over the source of `src/data/*.rs` at test time. The clippy lint in +//! `clippy.toml` rejects a call that runs at the driver default; it cannot see +//! which constructor a call passes, so a plain write at `read_params`, a +//! `SELECT` at `write_params`, or an `IF` statement at `write_params` would +//! compile and lint clean. This test reads the statement sites whose CQL and +//! level it can resolve (the CQL from a literal or a `format!` in the call, or +//! the nearest `let` binding of the identifier it passes; the level from a +//! constructor named in the arguments or in the `let` binding of an identifier +//! argument), and asserts: a `SELECT` carries a read level, a write without +//! `IF` carries `write_params` or `execute_quorum`, a statement with `IF` +//! carries `lwt_params` or `query_lwt`, and no `BatchQueryBuilder::new`, +//! `BatchQueryBuilder::default`, `Default::default()` or `.with_consistency(` +//! appears under `data/`, so a batch is built by `batch_builder()` or not at +//! all. A site whose CQL resolves and whose level does not is a failure. The +//! schema statements in `ddl.rs` are outside the check. The walker follows a +//! level passed as an identifier to its `let`, not one called in the argument +//! or received as a parameter of the enclosing function; it does not follow +//! text appended with `push_str` or a statement a helper receives as a +//! parameter (those are checked at the call that builds them), and a `let` +//! with several branches is read as the union of its literals. + +use std::fs; +use std::path::Path; + +const WRITE_VERBS: [&str; 3] = ["INSERT", "UPDATE", "DELETE"]; +const SCHEMA_VERBS: [&str; 4] = ["CREATE", "DROP", "ALTER", "TRUNCATE"]; + +/// Calls that run a statement: the name, the index of the argument holding the +/// statement text (`None` when the call has no text of its own), and the level +/// the call states by itself (`None` when the level is in its arguments). +const CALLS: &[(&str, Option, Option)] = &[ + ("query_rows_at", Some(1), Some(Kind::Read)), + ("query_optional_at", Some(1), Some(Kind::Read)), + ("query_rows_quorum", Some(1), Some(Kind::Read)), + ("execute_quorum", Some(1), Some(Kind::Write)), + ("query_lwt", Some(1), Some(Kind::Lwt)), + ("execute_at", Some(1), None), + ("execute_bound", Some(1), None), + ("query_with_params", Some(0), None), + ("query_with_pk_sk", Some(1), None), + ("query_with_pk_sk_txnid", Some(1), None), + ("query_with_txnid_ts_pk_sk", Some(1), None), + ("query_with_pk_sk_item_txnid_ts", Some(1), None), + ("query_with_item_ts_pk_sk_txnid", Some(1), None), + ("query_with_pk_sk_sk", Some(1), None), + ("query_with_pk_sk_pk_sk", Some(1), None), + ("query_with_pk_sk_pk", Some(1), None), + ("query_with_pk_pk_sk", Some(1), None), + ("query_with_pk_sk_sk_sk", Some(1), None), +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Read, + Write, + Lwt, +} + +/// The source of every file under `src/data/`, without its test module. +fn data_sources() -> Vec<(String, String)> { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/data"); + let mut out = Vec::new(); + let mut entries: Vec<_> = fs::read_dir(&dir) + .expect("read src/data") + .map(|e| e.expect("entry").path()) + .filter(|p| p.extension().is_some_and(|e| e == "rs")) + .filter(|p| p.file_name().is_some_and(|n| n != "level_pairing_tests.rs")) + .collect(); + entries.sort(); + for path in entries { + let src = fs::read_to_string(&path).expect("read source"); + // A file's own test module is left out; the `mod level_pairing_tests;` + // declaration in `mod.rs` is not a test module and does not cut it. + let live = match src.find("\n#[cfg(test)]\nmod tests") { + Some(i) => src[..i].to_owned(), + None => src, + }; + out.push(( + path.file_name().unwrap().to_string_lossy().into_owned(), + live, + )); + } + assert!(out.len() > 5, "src/data holds the data path"); + out +} + +/// The index of the `)` closing the `(` at `open`. +fn matching_paren(text: &str, open: usize) -> usize { + let bytes = text.as_bytes(); + let (mut depth, mut i, mut in_str) = (0usize, open, false); + while i < bytes.len() { + let c = bytes[i]; + if in_str { + if c == b'\\' { + i += 2; + continue; + } + if c == b'"' { + in_str = false; + } + } else if c == b'"' { + in_str = true; + } else if c == b'(' { + depth += 1; + } else if c == b')' { + depth -= 1; + if depth == 0 { + return i; + } + } + i += 1; + } + bytes.len() - 1 +} + +/// Top-level comma split of an argument list. +fn split_args(text: &str) -> Vec { + let (mut args, mut depth, mut cur, mut in_str) = (Vec::new(), 0i32, String::new(), false); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if in_str { + cur.push(c); + if c == '\\' { + if let Some(n) = chars.next() { + cur.push(n); + } + continue; + } + if c == '"' { + in_str = false; + } + } else if c == '"' { + in_str = true; + cur.push(c); + } else if "([{".contains(c) { + depth += 1; + cur.push(c); + } else if ")]}".contains(c) { + depth -= 1; + cur.push(c); + } else if c == ',' && depth == 0 { + args.push(cur.trim().to_owned()); + cur.clear(); + } else { + cur.push(c); + } + } + if !cur.trim().is_empty() { + args.push(cur.trim().to_owned()); + } + args +} + +/// Every string literal in `text`, joined. +fn literals(text: &str) -> String { + let mut out = String::new(); + let mut rest = text; + while let Some(start) = rest.find('"') { + let body = &rest[start + 1..]; + let mut end = None; + let mut i = 0; + let b = body.as_bytes(); + while i < b.len() { + if b[i] == b'\\' { + i += 2; + continue; + } + if b[i] == b'"' { + end = Some(i); + break; + } + i += 1; + } + let Some(end) = end else { break }; + out.push_str(&body[..end]); + out.push(' '); + rest = &body[end + 1..]; + } + out +} + +fn has_verb(text: &str, verbs: &[&str]) -> bool { + text.split(|c: char| !c.is_ascii_alphabetic()) + .any(|w| verbs.contains(&w)) +} + +/// The text of the nearest `let = ...;` (or `let (, ..) = ...;`) +/// binding before `call_pos`, from `let` to its `;` at nesting depth 0. +fn binding_body(src: &str, call_pos: usize, ident: &str) -> Option<(usize, String)> { + let head = &src[..call_pos]; + let mut best: Option = None; + for (i, _) in head.match_indices("let ") { + let after = &head[i + 4..]; + let after = after.trim_start_matches("mut ").trim_start(); + let names: Vec<&str> = if let Some(stripped) = after.strip_prefix('(') { + stripped + .split(')') + .next() + .unwrap_or("") + .split(',') + .map(|s| s.trim().trim_start_matches("mut ").trim()) + .collect() + } else { + vec![ + after + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .next() + .unwrap_or(""), + ] + }; + if names.contains(&ident) { + best = Some(i); + } + } + let start = best?; + let bytes = head.as_bytes(); + let (mut depth, mut j, mut in_str) = (0i32, start, false); + while j < bytes.len() { + let c = bytes[j]; + if in_str { + if c == b'\\' { + j += 2; + continue; + } + if c == b'"' { + in_str = false; + } + } else if c == b'"' { + in_str = true; + } else if b"([{".contains(&c) { + depth += 1; + } else if b")]}".contains(&c) { + depth -= 1; + } else if c == b';' && depth <= 0 { + break; + } + j += 1; + } + Some((start, head[start..j].to_owned())) +} + +/// The CQL text the statement argument resolves to, or `None` for a value the +/// call receives as a parameter. +fn statement_text(src: &str, call_pos: usize, arg: &str, hops: u8) -> Option { + let a = arg.trim().trim_start_matches('&').trim(); + if a.starts_with("format!") || a.starts_with('"') { + return Some(literals(a)); + } + let ident: String = a + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + if ident.is_empty() { + let l = literals(a); + return (!l.trim().is_empty()).then_some(l); + } + let (start, body) = binding_body(src, call_pos, &ident)?; + let body = body.as_str(); + let text = literals(body); + if !has_verb(&text, &WRITE_VERBS) + && !text.contains("SELECT") + && !has_verb(&text, &SCHEMA_VERBS) + && hops > 0 + { + // Built from another binding: `format!("{query} AND ..")` or + // `format!("{} ..", query)`. + let mut others: Vec = Vec::new(); + let mut rest = text.as_str(); + while let Some(o) = rest.find('{') { + let after = &rest[o + 1..]; + let name: String = after + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + if !name.is_empty() && after[name.len()..].starts_with('}') { + others.push(name); + } + rest = after; + } + for piece in body.split(',') { + let p = piece.trim().trim_start_matches('&'); + let name: String = p + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + if !name.is_empty() && name != ident && p.len() == name.len() { + others.push(name); + } + } + for other in others { + if other == ident { + continue; + } + if let Some(resolved) = statement_text(src, start, &other, hops - 1) + && (resolved.contains("SELECT") || has_verb(&resolved, &WRITE_VERBS)) + { + return Some(format!("{resolved} {text}")); + } + } + } + (!text.trim().is_empty()).then_some(text) +} + +/// The level the call's arguments state, when the call itself does not. +fn level_in_args(src: &str, call_pos: usize, args: &[String]) -> Option { + let mut joined = args.join(" "); + // A level passed through a variable: `let params = |v| read_params(..)`. + for a in args { + let a = a.trim(); + if !a.is_empty() + && a.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && !["true", "false", "consistent_read"].contains(&a) + && let Some((_, body)) = binding_body(src, call_pos, a) + { + joined.push(' '); + joined.push_str(&body); + } + } + if joined.contains("lwt_params") { + Some(Kind::Lwt) + } else if joined.contains("write_params") { + Some(Kind::Write) + } else if joined.contains("read_params") { + Some(Kind::Read) + } else if args.iter().any(|a| { + a == "true" || a == "false" || a == "consistent_read" || a.ends_with(".consistent_read") + }) { + // A read helper that takes the flag itself (`query_helpers.rs`). + Some(Kind::Read) + } else { + None + } +} + +fn is_lwt(text: &str) -> bool { + text.split_whitespace().any(|w| w == "IF") && !has_verb(text, &SCHEMA_VERBS) +} + +#[test] +fn every_data_path_statement_pairs_its_kind_with_its_level() { + let mut sites = 0usize; + let mut failures: Vec = Vec::new(); + for (file, src) in data_sources() { + for (name, qarg, own) in CALLS { + for (pos, _) in src.match_indices(name) { + // A whole identifier, as a call: not a longer name, not a + // definition, not a method on a receiver. + let before = src[..pos].chars().next_back(); + if before.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') { + continue; + } + // The helpers are free functions; `query_with_params` is the + // one `Session` method the data path calls with parameters. + if before == Some('.') && *name != "query_with_params" { + continue; + } + let after = &src[pos + name.len()..]; + let after_trim = after.trim_start(); + let open_rel = if after_trim.starts_with("::<") { + after_trim.find('(') + } else if after_trim.starts_with('(') { + Some(0) + } else { + None + }; + let Some(open_rel) = open_rel else { continue }; + if after_trim[..open_rel].contains('\n') { + continue; + } + let line_start = src[..pos].rfind('\n').map_or(0, |i| i + 1); + let line = src[line_start..pos].trim_start(); + if line.starts_with("fn ") + || line.starts_with("pub") + || line.starts_with("async fn") + || line.starts_with("//") + { + continue; + } + let open = pos + name.len() + (after.len() - after_trim.len()) + open_rel; + let close = matching_paren(&src, open); + let args = split_args(&src[open + 1..close]); + let lineno = src[..pos].matches('\n').count() + 1; + let site = format!("{file}:{lineno} {name}"); + let level = own.or_else(|| level_in_args(&src, pos, &args)); + let text = qarg + .and_then(|i| args.get(i)) + .and_then(|a| statement_text(&src, pos, a, 2)); + let Some(level) = level else { + // A helper handed the caller's constructor (`params`) with + // a statement it also received: checked at the caller. A + // resolvable statement with no resolvable level is not. + if let Some(text) = text { + failures.push(format!("{site}: statement {text:?} states no level")); + } + continue; + }; + let Some(text) = text else { + // The statement arrives as a parameter of the enclosing + // function; its own call site is checked where it is built. + continue; + }; + sites += 1; + let select = text.contains("SELECT"); + let write = has_verb(&text, &WRITE_VERBS); + let lwt = is_lwt(&text); + let expected = if lwt { + Kind::Lwt + } else if write { + Kind::Write + } else if select { + Kind::Read + } else { + failures.push(format!("{site}: no CQL verb in {text:?}")); + continue; + }; + if expected != level { + failures.push(format!( + "{site}: statement {text:?} is {expected:?} but the call states {level:?}" + )); + } + } + } + // A batch starts only from `batch_builder()`, which sets its level: + // no `BatchQueryBuilder::new`, `::default` or `Default::default()` + // under `data/`, and no `.with_consistency(` that could lower a level + // after the fact. + for needle in [ + "BatchQueryBuilder::new", + "BatchQueryBuilder::default", + "Default::default()", + ".with_consistency(", + ] { + for (pos, _) in src.match_indices(needle) { + let line_start = src[..pos].rfind('\n').map_or(0, |i| i + 1); + if src[line_start..pos].trim_start().starts_with("//") { + continue; + } + let lineno = src[..pos].matches('\n').count() + 1; + failures.push(format!( + "{file}:{lineno}: `{needle}` under data/; batches are built with cassandra_util::batch_builder()" + )); + } + } + } + // 121 sites resolve on the tree this test was written against; the + // statements the `query_helpers.rs` and `occ_delete_lwt` helpers receive + // as parameters are checked where they are built. + assert!( + sites >= 110, + "resolved {sites} statement sites; the walk lost its anchors" + ); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/crates/storage-cassandra/src/data/mod.rs b/crates/storage-cassandra/src/data/mod.rs index 946dbd042..4d1d579fb 100644 --- a/crates/storage-cassandra/src/data/mod.rs +++ b/crates/storage-cassandra/src/data/mod.rs @@ -2,12 +2,35 @@ // SPDX-License-Identifier: Apache-2.0 //! Data table operations for Cassandra. +//! +//! Every statement under this module states its consistency level through +//! [`read_params`](crate::cassandra_util::read_params), +//! [`write_params`](crate::cassandra_util::write_params) or +//! [`lwt_params`](crate::cassandra_util::lwt_params); the schema statements in +//! `ddl.rs` are the one exception. Two checks hold that. The lint below +//! rejects the `Session` methods and `cassandra_util` helpers named in +//! `clippy.toml`, each of which runs a statement at the driver default; it +//! cannot name a `Default` constructor (`StatementParams::default()`, +//! `StatementParamsBuilder::default()`, `BatchQueryBuilder::default()`) and it +//! does not see which constructor a call passes or the level a +//! `BatchQueryBuilder` sets. The test in +//! `level_pairing_tests.rs` reads the statement sites in this module's files +//! whose CQL and level it can resolve and checks that a `SELECT` carries a +//! read level, a plain write `write_params` and an `IF` statement +//! `lwt_params`, and that no batch builder other than +//! [`batch_builder`](crate::cassandra_util::batch_builder) appears here. +//! Allow the lint only on a schema statement. + +#![warn(clippy::disallowed_methods)] use cdrs_tokio::cluster::TcpConnectionManager; use cdrs_tokio::cluster::session::Session; +use cdrs_tokio::frame::Envelope; use cdrs_tokio::load_balancing::RoundRobinLoadBalancingStrategy; +use cdrs_tokio::query::QueryValues; +use cdrs_tokio::statement::StatementParams; use cdrs_tokio::transport::TransportTcp; -use cdrs_tokio::types::blob::Blob; +use cdrs_tokio::types::value::{Bytes, Value}; use extenddb_core::expression::ExpressionMaps; use extenddb_core::types::Item; use extenddb_storage::error::StorageError; @@ -27,8 +50,12 @@ mod transactions; pub(crate) mod ttl; mod update_item; +#[cfg(test)] +mod level_pairing_tests; + use condition::check_condition; use extenddb_core::expression; +use index::sk_to_value; /// Resolve an expression (placeholder) to an `AttributeValue`. pub(crate) fn resolve_expr_to_av( @@ -84,34 +111,32 @@ pub(crate) fn decimal_to_value(n: &bigdecimal::BigDecimal) -> cdrs_tokio::types: cdrs_tokio::types::value::Value::from(bigdecimal_to_cql_decimal(n)) } -/// Execute a query with pk and sort key, returning the result. -/// -/// Helper to reduce repetitive match-on-sk-type pattern. +/// Execute `query` with positional `values` at the level `params` builds: +/// [`read_params`](crate::cassandra_util::read_params), +/// [`write_params`](crate::cassandra_util::write_params) or +/// [`lwt_params`](crate::cassandra_util::lwt_params). +async fn execute_bound( + session: &CassandraSession, + query: &str, + values: Vec, + params: impl FnOnce(QueryValues) -> StatementParams, +) -> Result { + let params = params(QueryValues::SimpleValues(values)); + crate::cassandra_util::execute_at(session, query, params, "Query failed").await +} + +/// Execute a query with `(pk, sk)` bound parameters at the level `params` +/// states. pub(crate) async fn query_with_pk_sk( session: &CassandraSession, query: &str, pk: &str, sk: &SortKeyValue, -) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, s.as_str())) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, decimal_to_value(n))) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, Blob::new(b.clone()))) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + params: impl FnOnce(QueryValues) -> StatementParams, +) -> Result { + execute_bound(session, query, vec![pk.into(), sk_to_value(sk)], params).await } + /// Execute a query with `(pk, sk, txn_id_bytes)` bound parameters. /// /// Used for: rollback DELETE, commit DELETE. @@ -120,32 +145,11 @@ pub(crate) async fn query_with_pk_sk_txnid( query: &str, pk: &str, sk: &SortKeyValue, - txn_id: cdrs_tokio::types::value::Bytes, -) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, s.as_str(), txn_id)) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(pk, decimal_to_value(n), txn_id), - ) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(pk, Blob::new(b.clone()), txn_id), - ) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + txn_id: Bytes, + params: impl FnOnce(QueryValues) -> StatementParams, +) -> Result { + let values = vec![pk.into(), sk_to_value(sk), txn_id.into()]; + execute_bound(session, query, values, params).await } /// Execute a query with `(txn_id_bytes, txn_timestamp, pk, sk)` bound parameters. @@ -154,96 +158,49 @@ pub(crate) async fn query_with_pk_sk_txnid( pub(crate) async fn query_with_txnid_ts_pk_sk( session: &CassandraSession, query: &str, - txn_id: cdrs_tokio::types::value::Bytes, + txn_id: Bytes, txn_timestamp: i64, pk: &str, sk: &SortKeyValue, -) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(txn_id, txn_timestamp, pk, s.as_str()), - ) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(txn_id, txn_timestamp, pk, decimal_to_value(n)), - ) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(txn_id, txn_timestamp, pk, Blob::new(b.clone())), - ) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + params: impl FnOnce(QueryValues) -> StatementParams, +) -> Result { + let values = vec![ + txn_id.into(), + txn_timestamp.into(), + pk.into(), + sk_to_value(sk), + ]; + execute_bound(session, query, values, params).await } /// Execute a query with `(pk, sk, item_text, txn_id_bytes, txn_timestamp)` bound parameters. /// /// Used for: prepare INSERT new item. +#[allow(clippy::too_many_arguments)] pub(crate) async fn query_with_pk_sk_item_txnid_ts( session: &CassandraSession, query: &str, pk: &str, sk: &SortKeyValue, item_text: &str, - txn_id: cdrs_tokio::types::value::Bytes, + txn_id: Bytes, txn_timestamp: i64, -) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(pk, s.as_str(), item_text, txn_id, txn_timestamp), - ) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!( - pk, - decimal_to_value(n), - item_text, - txn_id, - txn_timestamp - ), - ) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!( - pk, - Blob::new(b.clone()), - item_text, - txn_id, - txn_timestamp - ), - ) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + params: impl FnOnce(QueryValues) -> StatementParams, +) -> Result { + let values = vec![ + pk.into(), + sk_to_value(sk), + item_text.into(), + txn_id.into(), + txn_timestamp.into(), + ]; + execute_bound(session, query, values, params).await } /// Execute a query with `(item_text, txn_timestamp, pk, sk, txn_id_bytes)` bound parameters. /// /// Used for: commit PUT/UPDATE. +#[allow(clippy::too_many_arguments)] pub(crate) async fn query_with_item_ts_pk_sk_txnid( session: &CassandraSession, query: &str, @@ -251,53 +208,25 @@ pub(crate) async fn query_with_item_ts_pk_sk_txnid( txn_timestamp: i64, pk: &str, sk: &SortKeyValue, - txn_id: cdrs_tokio::types::value::Bytes, -) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(item_text, txn_timestamp, pk, s.as_str(), txn_id), - ) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!( - item_text, - txn_timestamp, - pk, - decimal_to_value(n), - txn_id - ), - ) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!( - item_text, - txn_timestamp, - pk, - Blob::new(b.clone()), - txn_id - ), - ) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + txn_id: Bytes, + params: impl FnOnce(QueryValues) -> StatementParams, +) -> Result { + let values = vec![ + item_text.into(), + txn_timestamp.into(), + pk.into(), + sk_to_value(sk), + txn_id.into(), + ]; + execute_bound(session, query, values, params).await } -/// Execute a SELECT query by primary key (pk only, or pk + sort key). +/// Execute a SELECT query by primary key (pk only, or pk + sort key) at +/// [`read_consistency`](crate::cassandra_util::read_consistency)`(consistent_read)`. /// /// Builds the appropriate query based on whether a sort key is present, /// executes it, and returns the first row if any. +#[allow(clippy::too_many_arguments)] pub(crate) async fn select_by_pk( session: &CassandraSession, keyspace: &str, @@ -306,17 +235,16 @@ pub(crate) async fn select_by_pk( pk: &str, sk: Option<&SortKeyValue>, sk_col: Option<&str>, + consistent_read: bool, ) -> Result, StorageError> { + let params = |values| crate::cassandra_util::read_params(consistent_read, values); let result = if let (Some(sk), Some(sk_col)) = (sk, sk_col) { let query = format!("SELECT {columns} FROM {keyspace}.{table} WHERE pk = ? AND {sk_col} = ?"); - query_with_pk_sk(session, &query, pk, sk).await + query_with_pk_sk(session, &query, pk, sk, params).await } else { let query = format!("SELECT {columns} FROM {keyspace}.{table} WHERE pk = ?"); - session - .query_with_values(&query, cdrs_tokio::query_values!(pk)) - .await - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + execute_bound(session, &query, vec![pk.into()], params).await }?; let rows = result diff --git a/crates/storage-cassandra/src/data/put_get_item.rs b/crates/storage-cassandra/src/data/put_get_item.rs index aae7567a5..f9fd6bf5f 100644 --- a/crates/storage-cassandra/src/data/put_get_item.rs +++ b/crates/storage-cassandra/src/data/put_get_item.rs @@ -3,18 +3,17 @@ //! `put_item` and `get_item` implementations for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{composite_pk_to_text, parse_sk, pk_to_text, sk_column, sk_info}; +use extenddb_storage::util::{composite_pk_to_text, parse_sk, sk_column, sk_info}; use super::ddl::data_table_name; use super::{json_to_item, query_with_pk_sk}; use crate::CassandraEngine; +use crate::cassandra_util::{lwt_params, query_optional_at, read_params}; use crate::stream_util::stream_record_statement; /// How a put maintains GSIs. @@ -228,12 +227,20 @@ impl CassandraEngine { let sk_col = sk_column(sk_type); // Read old item including version and prepared_txn_id for OCC fence. + // The condition is evaluated against this image, so it is read at + // LOCAL_QUORUM to intersect every acknowledged write. let select_query = format!( "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let old_result = - query_with_pk_sk(&self.session, &select_query, pk_text.as_ref(), &sk).await?; + let old_result = query_with_pk_sk( + &self.session, + &select_query, + pk_text.as_ref(), + &sk, + |values| read_params(true, values), + ) + .await?; let body = old_result .response_body() @@ -340,15 +347,17 @@ impl CassandraEngine { } else { // PK-only table (no sort key) - // Read old item including version and prepared_txn_id for OCC fence. + // Read old item including version and prepared_txn_id for OCC fence, + // at LOCAL_QUORUM like the sort-key branch. let select_query = format!( "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ?" ); - let row = crate::cassandra_util::query_optional( + let row = query_optional_at( &self.session, &select_query, cdrs_tokio::query_values!(pk_text.as_ref() as &str), + true, "put_item read", ) .await?; @@ -509,7 +518,7 @@ impl CassandraEngine { let result = self .session - .query_with_values(&insert_cql, insert_qv) + .query_with_params(&insert_cql, lwt_params(insert_qv)) .await .map_err(|e| StorageError::Internal(format!("put_item_if_not_exists: {e}")))?; @@ -554,7 +563,7 @@ impl CassandraEngine { if indexes.is_empty() && stream_stmt.is_none() { return Ok(None); } - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch_builder(); if !indexes.is_empty() { super::index::sync_indexes( @@ -602,82 +611,37 @@ impl CassandraEngine { Ok(None) // return_old is always None — item didn't exist } - /// Implementation of `DataEngine::get_item`. - /// Read an item at `LOCAL_QUORUM`. + /// Read an item at `LOCAL_QUORUM`: [`Self::get_item_impl`] with + /// `consistent_read` set. /// - /// [`Self::get_item_impl`] reads at the driver's default consistency, which is - /// correct for an eventually-consistent `GetItem` but not for a TTL decision: - /// the expiration worker and the reconciliation outbox both treat `None` as - /// authoritative and act on it destructively — retiring queue work, or - /// dropping an outbox row — and a lagging replica reads as `None` for an item - /// that exists. Acting on that would leave the item with no expiration entry + /// The expiration worker and the reconciliation outbox treat `None` as + /// authoritative and act on it destructively (retiring queue work, or + /// dropping an outbox row), so they read at the level that intersects every + /// acknowledged write: a lagging replica reads as `None` for an item that + /// exists, and acting on that would leave the item with no expiration entry /// and therefore never expiring. - /// - /// All TTL writes commit at `LOCAL_QUORUM`, so a `LOCAL_QUORUM` read - /// intersects them and cannot miss a committed item. pub(crate) async fn get_item_quorum( &self, key_info: &TableKeyInfo, key: &Item, ) -> Result, StorageError> { - let data_keyspace = self.account_keyspace(&key_info.account_id); - let ddb_table = data_table_name(&key_info.table_id); - let pk_text = composite_pk_to_text(key, &key_info.key_schema)?; - - let (query, values) = if let Some((sk_name, sk_type)) = - sk_info(&key_info.key_schema, &key_info.attribute_definitions) - { - let sk_value = key - .get(sk_name) - .ok_or_else(|| StorageError::Internal("missing sort key".to_owned()))?; - let sk = parse_sk(sk_value, sk_type)?; - let sk_col = sk_column(sk_type); - ( - format!( - "SELECT item_data FROM {data_keyspace}.{ddb_table} \ - WHERE pk = ? AND {sk_col} = ?" - ), - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - cdrs_tokio::types::value::Value::from(pk_text.as_str()), - super::index::sk_to_value(&sk), - ]), - ) - } else { - ( - format!("SELECT item_data FROM {data_keyspace}.{ddb_table} WHERE pk = ?"), - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - cdrs_tokio::types::value::Value::from(pk_text.as_str()), - ]), - ) - }; - - let rows = crate::cassandra_util::query_rows_quorum( - &self.session, - &query, - values, - "get_item_quorum", - ) - .await?; - let Some(row) = rows.into_iter().next() else { - return Ok(None); - }; - let item_data: Option = row.get_by_name("item_data").ok().flatten(); - item_data.map(json_to_item).transpose() + self.get_item_impl(key_info, key, true).await } + /// Implementation of `DataEngine::get_item`, read at + /// [`read_consistency`](crate::cassandra_util::read_consistency)`(consistent_read)`. pub(crate) async fn get_item_impl( &self, key_info: &TableKeyInfo, key: &Item, + consistent_read: bool, ) -> Result, StorageError> { let data_keyspace = self.account_keyspace(&key_info.account_id); let ddb_table = data_table_name(&key_info.table_id); - let pk_name = &key_info.key_schema[0].attribute_name; - let pk_value = key - .get(pk_name) - .ok_or_else(|| StorageError::Internal("missing partition key".to_owned()))?; - let pk_text = pk_to_text(pk_value)?; + // The partition key as the write path stores it: one HASH attribute + // binds as itself, several bind as their netstring composite. + let pk_text = composite_pk_to_text(key, &key_info.key_schema)?; if let Some((sk_name, sk_type)) = sk_info(&key_info.key_schema, &key_info.attribute_definitions) @@ -693,7 +657,10 @@ impl CassandraEngine { "SELECT item_data FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let result = query_with_pk_sk(&self.session, &query, pk_text.as_ref(), &sk).await?; + let result = query_with_pk_sk(&self.session, &query, pk_text.as_ref(), &sk, |values| { + read_params(consistent_read, values) + }) + .await?; let body = result .response_body() @@ -713,7 +680,13 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_ref() as &str)) + .query_with_params( + &query, + read_params( + consistent_read, + cdrs_tokio::query_values!(pk_text.as_ref() as &str), + ), + ) .await .map_err(|e| StorageError::Internal(format!("Get item: {e}")))?; diff --git a/crates/storage-cassandra/src/data/query.rs b/crates/storage-cassandra/src/data/query.rs index 65b0c242f..059f90a02 100644 --- a/crates/storage-cassandra/src/data/query.rs +++ b/crates/storage-cassandra/src/data/query.rs @@ -86,7 +86,8 @@ fn base_sk_info( } impl CassandraEngine { - /// Implementation of `DataEngine::query`. + /// Implementation of `DataEngine::query`. Every read runs at + /// [`read_consistency`](crate::cassandra_util::read_consistency)`(consistent_read)`. #[allow(clippy::too_many_arguments)] pub(crate) async fn query_impl( &self, @@ -97,6 +98,7 @@ impl CassandraEngine { limit: Option, exclusive_start_key: Option<&Item>, index_name: Option<&str>, + consistent_read: bool, ) -> Result<(Vec, Option), StorageError> { // Determine table to query (base or index) let (table_name, query_key_schema, is_lsi) = if let Some(idx_name) = index_name { @@ -411,6 +413,7 @@ impl CassandraEngine { &pk_text, start_sk, base_sk, + consistent_read, "same_sk", ) .await?; @@ -447,6 +450,7 @@ impl CassandraEngine { start_sk, base_pk_text, base_sk, + consistent_read, "same_sk_same_base_pk", ) .await?; @@ -466,6 +470,7 @@ impl CassandraEngine { &pk_text, start_sk, base_pk_text, + consistent_read, "same_sk_next_base_pk", ) .await?; @@ -492,6 +497,7 @@ impl CassandraEngine { &pk_text, start_sk, base_pk_text, + consistent_read, "same_sk", ) .await?; @@ -538,14 +544,16 @@ impl CassandraEngine { &pk_text, base_pk_text, base_sk, + consistent_read, "same_sk", ) .await? } else { - cassandra_util::query_rows( + cassandra_util::query_rows_at( &self.session_arc(), &query1, cdrs_tokio::query_values!(pk_text.as_str(), base_pk_text.as_str()), + consistent_read, "same_sk", ) .await? @@ -583,6 +591,7 @@ impl CassandraEngine { &query2, &pk_text, start_sk, + consistent_read, "next_sk", ) .await?; @@ -608,10 +617,11 @@ impl CassandraEngine { "{query} AND base_pk {base_pk_cmp} ? ORDER BY base_pk {dir} LIMIT {remaining}" ) }; - let rows2 = cassandra_util::query_rows( + let rows2 = cassandra_util::query_rows_at( &self.session_arc(), &query2, cdrs_tokio::query_values!(pk_text.as_str(), base_pk_text.as_str()), + consistent_read, "next_base_pk", ) .await?; @@ -633,6 +643,7 @@ impl CassandraEngine { &pk_text, &sk_vals[0], &page_sk, + consistent_read, "query", ) .await? @@ -645,6 +656,7 @@ impl CassandraEngine { &sk_vals[0], &sk_vals[1], &page_sk, + consistent_read, "query", ) .await? @@ -659,6 +671,7 @@ impl CassandraEngine { &query, &pk_text, &sk_vals[0], + consistent_read, "query", ) .await? @@ -670,6 +683,7 @@ impl CassandraEngine { &pk_text, &sk_vals[0], &sk_vals[1], + consistent_read, "query", ) .await? @@ -677,8 +691,15 @@ impl CassandraEngine { } (None, Some(page_sk)) => { // PK-only query with pagination - query_with_pk_sk(&self.session_arc(), &query, &pk_text, &page_sk, "query") - .await? + query_with_pk_sk( + &self.session_arc(), + &query, + &pk_text, + &page_sk, + consistent_read, + "query", + ) + .await? } (None, None) => { // Check if this is hash-only index with pagination @@ -687,13 +708,14 @@ impl CassandraEngine { let base_pk_attr = &key_info.base_key_schema[0].attribute_name; if let Some(base_pk_val) = start_key.get(base_pk_attr) { let base_pk_text = pk_to_text(base_pk_val)?.into_owned(); - cassandra_util::query_rows( + cassandra_util::query_rows_at( &self.session_arc(), &query, cdrs_tokio::query_values!( pk_text.as_str(), base_pk_text.as_str() ), + consistent_read, "query", ) .await? @@ -702,20 +724,22 @@ impl CassandraEngine { } } else { // PK-only query without pagination (original behavior) - cassandra_util::query_rows( + cassandra_util::query_rows_at( &self.session_arc(), &query, cdrs_tokio::query_values!(pk_text.as_str()), + consistent_read, "query", ) .await? } } else { // PK-only query without pagination (original behavior) - cassandra_util::query_rows( + cassandra_util::query_rows_at( &self.session_arc(), &query, cdrs_tokio::query_values!(pk_text.as_str()), + consistent_read, "query", ) .await? diff --git a/crates/storage-cassandra/src/data/query_helpers.rs b/crates/storage-cassandra/src/data/query_helpers.rs index 2d55b83f9..12ab2ba05 100644 --- a/crates/storage-cassandra/src/data/query_helpers.rs +++ b/crates/storage-cassandra/src/data/query_helpers.rs @@ -2,6 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 //! Query execution helpers to reduce code repetition. +//! +//! Every helper reads at +//! [`read_consistency`](crate::cassandra_util::read_consistency)`(consistent_read)`. use crate::cassandra_util; use cdrs_tokio::types::blob::Blob; @@ -16,32 +19,36 @@ pub(super) async fn query_with_pk_sk( query: &str, pk: &str, sk: &SortKeyValue, + consistent_read: bool, label: &str, ) -> Result, StorageError> { match sk { SortKeyValue::S(s) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, s.as_str()), + consistent_read, label, ) .await } SortKeyValue::N(n) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, super::decimal_to_value(n)), + consistent_read, label, ) .await } SortKeyValue::B(b) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, Blob::new(b.clone())), + consistent_read, label, ) .await @@ -56,20 +63,22 @@ pub(super) async fn query_with_pk_sk_sk( pk: &str, sk1: &SortKeyValue, sk2: &SortKeyValue, + consistent_read: bool, label: &str, ) -> Result, StorageError> { match (sk1, sk2) { (SortKeyValue::S(s1), SortKeyValue::S(s2)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, s1.as_str(), s2.as_str()), + consistent_read, label, ) .await } (SortKeyValue::N(n1), SortKeyValue::N(n2)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!( @@ -77,15 +86,17 @@ pub(super) async fn query_with_pk_sk_sk( super::decimal_to_value(n1), super::decimal_to_value(n2) ), + consistent_read, label, ) .await } (SortKeyValue::B(b1), SortKeyValue::B(b2)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, Blob::new(b1.clone()), Blob::new(b2.clone())), + consistent_read, label, ) .await @@ -98,6 +109,7 @@ pub(super) async fn query_with_pk_sk_sk( /// Execute query with index PK, index SK, base PK, and base SK parameters. /// Used for LSI pagination: `WHERE pk=? AND sk_*=? AND base_pk=? AND base_sk_*>?` +#[allow(clippy::too_many_arguments)] pub(super) async fn query_with_pk_sk_pk_sk( session: &Arc, query: &str, @@ -105,48 +117,53 @@ pub(super) async fn query_with_pk_sk_pk_sk( idx_sk: &SortKeyValue, base_pk: &str, base_sk: &SortKeyValue, + consistent_read: bool, label: &str, ) -> Result, StorageError> { use cdrs_tokio::query_values; match (idx_sk, base_sk) { (SortKeyValue::S(isk), SortKeyValue::S(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!(pk, isk.as_str(), base_pk, bsk.as_str()), + consistent_read, label, ) .await } (SortKeyValue::S(isk), SortKeyValue::N(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!(pk, isk.as_str(), base_pk, super::decimal_to_value(bsk)), + consistent_read, label, ) .await } (SortKeyValue::S(isk), SortKeyValue::B(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!(pk, isk.as_str(), base_pk, Blob::new(bsk.clone())), + consistent_read, label, ) .await } (SortKeyValue::N(isk), SortKeyValue::S(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!(pk, super::decimal_to_value(isk), base_pk, bsk.as_str()), + consistent_read, label, ) .await } (SortKeyValue::N(isk), SortKeyValue::N(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!( @@ -155,12 +172,13 @@ pub(super) async fn query_with_pk_sk_pk_sk( base_pk, super::decimal_to_value(bsk) ), + consistent_read, label, ) .await } (SortKeyValue::N(isk), SortKeyValue::B(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!( @@ -169,21 +187,23 @@ pub(super) async fn query_with_pk_sk_pk_sk( base_pk, Blob::new(bsk.clone()) ), + consistent_read, label, ) .await } (SortKeyValue::B(isk), SortKeyValue::S(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!(pk, Blob::new(isk.clone()), base_pk, bsk.as_str()), + consistent_read, label, ) .await } (SortKeyValue::B(isk), SortKeyValue::N(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!( @@ -192,15 +212,17 @@ pub(super) async fn query_with_pk_sk_pk_sk( base_pk, super::decimal_to_value(bsk) ), + consistent_read, label, ) .await } (SortKeyValue::B(isk), SortKeyValue::B(bsk)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, query_values!(pk, Blob::new(isk.clone()), base_pk, Blob::new(bsk.clone())), + consistent_read, label, ) .await @@ -216,32 +238,36 @@ pub(super) async fn query_with_pk_sk_pk( pk: &str, sk: &SortKeyValue, base_pk: &str, + consistent_read: bool, label: &str, ) -> Result, StorageError> { match sk { SortKeyValue::S(s) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, s.as_str(), base_pk), + consistent_read, label, ) .await } SortKeyValue::N(n) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, super::decimal_to_value(n), base_pk), + consistent_read, label, ) .await } SortKeyValue::B(b) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, Blob::new(b.clone()), base_pk), + consistent_read, label, ) .await @@ -256,32 +282,36 @@ pub(super) async fn query_with_pk_pk_sk( pk: &str, base_pk: &str, sk: &SortKeyValue, + consistent_read: bool, label: &str, ) -> Result, StorageError> { match sk { SortKeyValue::S(s) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, base_pk, s.as_str()), + consistent_read, label, ) .await } SortKeyValue::N(n) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, base_pk, super::decimal_to_value(n)), + consistent_read, label, ) .await } SortKeyValue::B(b) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, base_pk, Blob::new(b.clone())), + consistent_read, label, ) .await @@ -290,6 +320,7 @@ pub(super) async fn query_with_pk_pk_sk( } /// Execute query with PK and three SK parameters. +#[allow(clippy::too_many_arguments)] pub(super) async fn query_with_pk_sk_sk_sk( session: &Arc, query: &str, @@ -297,20 +328,22 @@ pub(super) async fn query_with_pk_sk_sk_sk( sk1: &SortKeyValue, sk2: &SortKeyValue, sk3: &SortKeyValue, + consistent_read: bool, label: &str, ) -> Result, StorageError> { match (sk1, sk2, sk3) { (SortKeyValue::S(s1), SortKeyValue::S(s2), SortKeyValue::S(s3)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!(pk, s1.as_str(), s2.as_str(), s3.as_str()), + consistent_read, label, ) .await } (SortKeyValue::N(n1), SortKeyValue::N(n2), SortKeyValue::N(n3)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!( @@ -319,12 +352,13 @@ pub(super) async fn query_with_pk_sk_sk_sk( super::decimal_to_value(n2), super::decimal_to_value(n3) ), + consistent_read, label, ) .await } (SortKeyValue::B(b1), SortKeyValue::B(b2), SortKeyValue::B(b3)) => { - cassandra_util::query_rows( + cassandra_util::query_rows_at( session, query, cdrs_tokio::query_values!( @@ -333,6 +367,7 @@ pub(super) async fn query_with_pk_sk_sk_sk( Blob::new(b2.clone()), Blob::new(b3.clone()) ), + consistent_read, label, ) .await diff --git a/crates/storage-cassandra/src/data/scan.rs b/crates/storage-cassandra/src/data/scan.rs index 6e93d4a30..f1c06cd0f 100644 --- a/crates/storage-cassandra/src/data/scan.rs +++ b/crates/storage-cassandra/src/data/scan.rs @@ -100,30 +100,14 @@ 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> { - let result = session - .query(query) - .await - .map_err(|e| StorageError::Internal(format!("scan query failed: {e}")))?; - let body = result - .response_body() - .map_err(|e| StorageError::Internal(format!("scan parse failed: {e}")))?; - Ok(body.into_rows().unwrap_or_default()) -} - impl crate::CassandraEngine { - /// Implementation of `DataEngine::scan`. + /// Implementation of `DataEngine::scan`. Every read runs at + /// [`read_consistency`](crate::cassandra_util::read_consistency)`(consistent_read)`. /// /// Returns up to `limit` items (the engine layer applies any /// `FilterExpression`, `ProjectionExpression`, and the 1 MB cap) along with /// a `LastEvaluatedKey` when more items remain. + #[allow(clippy::too_many_arguments)] pub(crate) async fn scan_impl( &self, key_info: &TableKeyInfo, @@ -132,6 +116,7 @@ impl crate::CassandraEngine { segment: Option, total_segments: Option, index_name: Option<&str>, + consistent_read: bool, ) -> Result<(Vec, Option), StorageError> { let session = self.session_arc(); @@ -194,6 +179,7 @@ impl crate::CassandraEngine { start_key, token_upper, fetch_limit, + consistent_read, ) .await? } else { @@ -206,18 +192,15 @@ impl crate::CassandraEngine { 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::( - &session, - &query, - QueryValues::SimpleValues(values), - "scan_first_page", - ) - .await? - } + // An unrestricted full scan binds an empty value list. + cassandra_util::query_rows_at::( + &session, + &query, + QueryValues::SimpleValues(values), + consistent_read, + "scan_first_page", + ) + .await? }; // Parse item_data JSON into items. @@ -310,10 +293,13 @@ impl crate::CassandraEngine { // exactly one row, and `token()` is independent of the queried table's // schema, so this needs neither the data table to exist nor a matching // row in it. - let rows = cassandra_util::query_rows::( + // `token(?)` is a pure function of its argument, so the read level does + // not change the answer. + let rows = cassandra_util::query_rows_at::( &self.session_arc(), "SELECT token(?) AS t FROM system.local", QueryValues::SimpleValues(vec![Value::from(pk_text.as_str())]), + false, "scan_key_in_segment", ) .await?; @@ -342,6 +328,7 @@ impl crate::CassandraEngine { start_key: &Item, token_upper: Option, fetch_limit: usize, + consistent_read: bool, ) -> 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)?; @@ -373,10 +360,11 @@ impl crate::CassandraEngine { 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::( + let rows1 = cassandra_util::query_rows_at::( session, &query1, QueryValues::SimpleValues(values), + consistent_read, "scan_finish_partition", ) .await?; @@ -393,10 +381,11 @@ impl crate::CassandraEngine { if let Some(hi) = token_upper { values.push(Value::from(hi)); } - let rows2 = cassandra_util::query_rows::( + let rows2 = cassandra_util::query_rows_at::( session, &query2, QueryValues::SimpleValues(values), + consistent_read, "scan_next_partitions", ) .await?; diff --git a/crates/storage-cassandra/src/data/transaction_ledger.rs b/crates/storage-cassandra/src/data/transaction_ledger.rs index 9068370f9..f9e19a15c 100644 --- a/crates/storage-cassandra/src/data/transaction_ledger.rs +++ b/crates/storage-cassandra/src/data/transaction_ledger.rs @@ -9,7 +9,9 @@ use extenddb_storage::error::StorageError; use uuid::Uuid; use crate::CassandraEngine; -use crate::cassandra_util::{get_column, query_optional, query_rows}; +use crate::cassandra_util::{ + get_column, lwt_params, query_optional_at, query_rows_at, write_params, +}; /// Transaction states (from DynamoDB paper). #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -120,16 +122,16 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( + lwt_params(cdrs_tokio::query_values!( Bytes::new(txn_id.as_bytes().to_vec()), state.as_str(), started_at, client_token, request_fingerprint, items_blob - ), + )), ) .await .map_err(|e| { @@ -167,12 +169,12 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET state = ? WHERE txn_id = ?"); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( + write_params(cdrs_tokio::query_values!( new_state.as_str(), Bytes::new(txn_id.as_bytes().to_vec()) - ), + )), ) .await .map_err(|e| { @@ -198,9 +200,12 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET items_blob = ? WHERE txn_id = ?"); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(blob, Bytes::new(txn_id.as_bytes().to_vec())), + write_params(cdrs_tokio::query_values!( + blob, + Bytes::new(txn_id.as_bytes().to_vec()) + )), ) .await .map_err(|e| { @@ -221,10 +226,11 @@ impl CassandraEngine { FROM {keyspace}.transaction_ledger WHERE txn_id = ?" ); - let row = query_optional::( + let row = query_optional_at::( &self.session, &query, cdrs_tokio::query_values!(Bytes::new(txn_id.as_bytes().to_vec())), + true, "read_ledger_entry", ) .await?; @@ -263,10 +269,11 @@ impl CassandraEngine { FROM {keyspace}.transaction_ledger WHERE started_at < ? ALLOW FILTERING" ); - let rows = query_rows::( + let rows = query_rows_at::( &self.session, &query, cdrs_tokio::query_values!(cutoff_timestamp), + true, "scan_old_transactions", ) .await?; @@ -304,9 +311,11 @@ impl CassandraEngine { let query = format!("DELETE FROM {keyspace}.transaction_ledger WHERE txn_id = ?"); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(Bytes::new(txn_id.as_bytes().to_vec())), + write_params(cdrs_tokio::query_values!(Bytes::new( + txn_id.as_bytes().to_vec() + ))), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/data/transactions.rs b/crates/storage-cassandra/src/data/transactions.rs index 639aad7e4..23eab968c 100644 --- a/crates/storage-cassandra/src/data/transactions.rs +++ b/crates/storage-cassandra/src/data/transactions.rs @@ -3,9 +3,7 @@ //! DynamoDB transaction implementations for Cassandra backend. -use cdrs_tokio::consistency::Consistency; use cdrs_tokio::frame::Envelope; -use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::value::Bytes; use extenddb_core::expression::{self, ExpressionMaps}; @@ -21,7 +19,7 @@ use std::time::Duration; use uuid::Uuid; use crate::CassandraEngine; -use crate::cassandra_util::{get_column, query_optional}; +use crate::cassandra_util::{execute_at, get_column, lwt_params, query_optional_at, read_params}; use crate::data::ddl::data_table_name; use crate::data::transaction_ledger::{LedgerOp, TransactionState}; use crate::data::{ @@ -196,6 +194,7 @@ impl CassandraEngine { pk_text.as_str(), sk.as_ref(), sk_col.as_deref(), + true, ) .await? else { @@ -233,6 +232,7 @@ impl CassandraEngine { pk_text.as_str(), sk.as_ref(), sk_col.as_deref(), + true, ) .await? else { @@ -1069,10 +1069,11 @@ impl CassandraEngine { ); // Fast path: token already present (common on retry). - if let Some(row) = query_optional::( + if let Some(row) = query_optional_at::( &self.session, &select_query, cdrs_tokio::query_values!(account_id, token), + true, "check_idempotency_token", ) .await? @@ -1091,20 +1092,28 @@ impl CassandraEngine { (account_id, \"token\", fingerprint, created_at) VALUES (?, ?, ?, ?) IF NOT EXISTS" ); let now = crate::cassandra_util::now_millis(); - let result = crate::cassandra_util::apply_lwt( - &self.session, - &insert_query, - cdrs_tokio::query_values!(account_id, token, fingerprint, now), - "check_idempotency_token insert", - ) - .await?; + let result = crate::cassandra_util::lwt_applied( + &execute_at::( + &self.session, + &insert_query, + lwt_params(cdrs_tokio::query_values!( + account_id, + token, + fingerprint, + now + )), + "check_idempotency_token insert", + ) + .await?, + )?; if !result { // Lost the LWT race — read back to return the right error. - let row = query_optional::( + let row = query_optional_at::( &self.session, &select_query, cdrs_tokio::query_values!(account_id, token), + true, "check_idempotency_token recheck", ) .await?; @@ -1132,7 +1141,7 @@ impl CassandraEngine { "DELETE FROM {keyspace}.idempotency_tokens_by_account \ WHERE account_id = ? AND \"token\" = ?" ); - if let Err(e) = crate::cassandra_util::execute::( + if let Err(e) = crate::cassandra_util::execute_quorum::( &self.session, &delete_query, cdrs_tokio::query_values!(account_id, token), @@ -1169,6 +1178,7 @@ impl CassandraEngine { pk_text.as_str(), sk.as_ref(), sk_col.as_deref(), + true, ) .await? else { @@ -1243,6 +1253,7 @@ impl CassandraEngine { pk_text.as_str(), sk.as_ref(), sk_col.as_deref(), + true, ) .await .map_err(|e| CancellationReason::validation_error(e.to_string()))?; @@ -1305,7 +1316,10 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_str())) + .query_with_params( + &query, + read_params(true, cdrs_tokio::query_values!(pk_text.as_str())), + ) .await .map_err(|e| { tracing::error!("check_partition_max_delete_timestamp: {e}"); @@ -1370,13 +1384,13 @@ impl CassandraEngine { "INSERT INTO {keyspace}.{ddb_table} (pk, {sk_col}, item_data, prepared_txn_id, prepared_txn_timestamp, created_to_prepare) \ VALUES (?, ?, ?, ?, ?, true) IF NOT EXISTS" ); - query_with_pk_sk_item_txnid_ts(&self.session, &query, pk_text.as_str(), &sk, &item_text, txn_id_bytes, txn_timestamp).await + query_with_pk_sk_item_txnid_ts(&self.session, &query, pk_text.as_str(), &sk, &item_text, txn_id_bytes, txn_timestamp, lwt_params).await } else { let query = format!( "UPDATE {keyspace}.{ddb_table} SET prepared_txn_id = ?, prepared_txn_timestamp = ? \ WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = null" ); - query_with_txnid_ts_pk_sk(&self.session, &query, txn_id_bytes, txn_timestamp, pk_text.as_str(), &sk).await + query_with_txnid_ts_pk_sk(&self.session, &query, txn_id_bytes, txn_timestamp, pk_text.as_str(), &sk, lwt_params).await } } else if is_new_item { let item_text = serde_json::to_value(key) @@ -1387,7 +1401,7 @@ impl CassandraEngine { VALUES (?, ?, ?, ?, true) IF NOT EXISTS" ); self.session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_str(), item_text, txn_id_bytes, txn_timestamp)) + .query_with_params(&query, lwt_params(cdrs_tokio::query_values!(pk_text.as_str(), item_text, txn_id_bytes, txn_timestamp))) .await .map_err(|e| StorageError::Internal(e.to_string())) } else { @@ -1396,7 +1410,7 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = null" ); self.session - .query_with_values(&query, cdrs_tokio::query_values!(txn_id_bytes, txn_timestamp, pk_text.as_str())) + .query_with_params(&query, lwt_params(cdrs_tokio::query_values!(txn_id_bytes, txn_timestamp, pk_text.as_str()))) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -1461,9 +1475,9 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .query_with_params( &update_max_ts_null_query, - cdrs_tokio::query_values!(txn_timestamp, pk_text.as_str()), + lwt_params(cdrs_tokio::query_values!(txn_timestamp, pk_text.as_str())), ) .await .map_err(|e| { @@ -1482,13 +1496,13 @@ impl CassandraEngine { let _result2 = self .session - .query_with_values( + .query_with_params( &update_max_ts_query, - cdrs_tokio::query_values!( + lwt_params(cdrs_tokio::query_values!( txn_timestamp, pk_text.as_str(), txn_timestamp - ), + )), ) .await .map_err(|e| { @@ -1518,6 +1532,7 @@ impl CassandraEngine { pk_text.as_str(), &sk, txn_id_bytes, + lwt_params, ) .await } else { @@ -1525,9 +1540,9 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{ddb_table} WHERE pk = ? IF prepared_txn_id = ?" ); self.session - .query_with_values( + .query_with_params( &delete_query, - cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), + lwt_params(cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -1580,16 +1595,24 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ? \ IF prepared_txn_id = ? AND created_to_prepare = true" ); - query_with_pk_sk_txnid(&self.session, &query, pk_text.as_str(), &sk, txn_id_bytes).await + query_with_pk_sk_txnid( + &self.session, + &query, + pk_text.as_str(), + &sk, + txn_id_bytes, + lwt_params, + ) + .await } else { let query = format!( "DELETE FROM {keyspace}.{ddb_table} WHERE pk = ? \ IF prepared_txn_id = ? AND created_to_prepare = true" ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), + lwt_params(cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -1632,14 +1655,14 @@ impl CassandraEngine { "UPDATE {keyspace}.{ddb_table} SET item_data = ?, prepared_txn_id = NULL, version = version + 1, last_committed_txn_timestamp = ? \ WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?" ); - query_with_item_ts_pk_sk_txnid(&self.session, &query, &item_text, txn_timestamp, pk_text.as_str(), &sk, txn_id_bytes).await + query_with_item_ts_pk_sk_txnid(&self.session, &query, &item_text, txn_timestamp, pk_text.as_str(), &sk, txn_id_bytes, lwt_params).await } else { let query = format!( "UPDATE {keyspace}.{ddb_table} SET item_data = ?, prepared_txn_id = NULL, version = version + 1, last_committed_txn_timestamp = ? \ WHERE pk = ? IF prepared_txn_id = ?" ); self.session - .query_with_values(&query, cdrs_tokio::query_values!(item_text, txn_timestamp, pk_text.as_str(), txn_id_bytes)) + .query_with_params(&query, lwt_params(cdrs_tokio::query_values!(item_text, txn_timestamp, pk_text.as_str(), txn_id_bytes))) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -1683,7 +1706,7 @@ impl CassandraEngine { let sys_delay = self .gsi_default_delay_ms .load(std::sync::atomic::Ordering::Relaxed); - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch_builder(); super::index::sync_indexes( &mut batch, &data_keyspace, @@ -1784,13 +1807,13 @@ impl CassandraEngine { "UPDATE {keyspace}.{ddb_table} SET prepared_txn_id = null WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?" ); - let dr = query_with_pk_sk_txnid(&self.session, &delete_query, pk_text.as_str(), &sk, txn_id_bytes.clone()) + let dr = query_with_pk_sk_txnid(&self.session, &delete_query, pk_text.as_str(), &sk, txn_id_bytes.clone(), lwt_params) .await .map_err(|e| { tracing::error!("rollback delete: {e}"); e })?; if check_lwt_applied(&dr, "rollback delete").is_ok() { return Ok(()); } - query_with_pk_sk_txnid(&self.session, &update_query, pk_text.as_str(), &sk, txn_id_bytes).await + query_with_pk_sk_txnid(&self.session, &update_query, pk_text.as_str(), &sk, txn_id_bytes, lwt_params).await } else { let delete_query = format!( "DELETE FROM {keyspace}.{ddb_table} WHERE pk = ? IF prepared_txn_id = ? AND created_to_prepare = true" @@ -1800,7 +1823,7 @@ impl CassandraEngine { ); let dr = self.session - .query_with_values(&delete_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes.clone())) + .query_with_params(&delete_query, lwt_params(cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes.clone()))) .await .map_err(|e| StorageError::Internal(e.to_string())) .map_err(|e| { tracing::error!("rollback delete: {e}"); e })?; @@ -1808,7 +1831,7 @@ impl CassandraEngine { return Ok(()); } self.session - .query_with_values(&update_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)) + .query_with_params(&update_query, lwt_params(cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes))) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -1927,14 +1950,18 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{table} WHERE pk = ? AND {sk_col} = ? \ IF prepared_txn_id = ? AND created_to_prepare = true", ); - query_with_pk_sk_txnid(&self.session, &dq, &op.pk, sk_val, txn_id_bytes).await + query_with_pk_sk_txnid(&self.session, &dq, &op.pk, sk_val, txn_id_bytes, lwt_params) + .await } else { let dq = format!( "DELETE FROM {keyspace}.{table} WHERE pk = ? \ IF prepared_txn_id = ? AND created_to_prepare = true", ); self.session - .query_with_values(&dq, cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes)) + .query_with_params( + &dq, + lwt_params(cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes)), + ) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -1973,6 +2000,7 @@ impl CassandraEngine { &op.pk, sk_val, txn_id_bytes, + lwt_params, ) .await } else { @@ -1982,14 +2010,14 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( + lwt_params(cdrs_tokio::query_values!( item_data, txn_timestamp, op.pk.as_str(), txn_id_bytes - ), + )), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2011,9 +2039,9 @@ impl CassandraEngine { ); let r1 = self .session - .query_with_values( + .query_with_params( &update_null, - cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str()), + lwt_params(cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str())), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2029,9 +2057,13 @@ impl CassandraEngine { ); let _ = self .session - .query_with_values( + .query_with_params( &update_cmp, - cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str(), txn_timestamp), + lwt_params(cdrs_tokio::query_values!( + txn_timestamp, + op.pk.as_str(), + txn_timestamp + )), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2047,16 +2079,23 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{table} WHERE pk = ? AND {sk_col} = ? \ IF prepared_txn_id = ?", ); - query_with_pk_sk_txnid(&self.session, &query, &op.pk, sk_val, txn_id_bytes) - .await + query_with_pk_sk_txnid( + &self.session, + &query, + &op.pk, + sk_val, + txn_id_bytes, + lwt_params, + ) + .await } else { let query = format!( "DELETE FROM {keyspace}.{table} WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + lwt_params(cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes)), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2104,13 +2143,19 @@ impl CassandraEngine { "UPDATE {keyspace}.{table} SET prepared_txn_id = null \ WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?", ); - let dr = - query_with_pk_sk_txnid(&self.session, &dq, &op.pk, sk_val, txn_id_bytes.clone()) - .await - .map_err(|e| { - tracing::error!("recover_rollback_op delete: {e}"); - StorageError::Internal("Database error".to_owned()) - })?; + let dr = query_with_pk_sk_txnid( + &self.session, + &dq, + &op.pk, + sk_val, + txn_id_bytes.clone(), + lwt_params, + ) + .await + .map_err(|e| { + tracing::error!("recover_rollback_op delete: {e}"); + StorageError::Internal("Database error".to_owned()) + })?; (dr, uq) } else { let dq = format!( @@ -2123,9 +2168,12 @@ impl CassandraEngine { ); let dr = self .session - .query_with_values( + .query_with_params( &dq, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes.clone()), + lwt_params(cdrs_tokio::query_values!( + op.pk.as_str(), + txn_id_bytes.clone() + )), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2142,12 +2190,20 @@ impl CassandraEngine { // Item was pre-existing - clear the transaction marker let result = if let Some((sk_val, _sk_col)) = &sk { - query_with_pk_sk_txnid(&self.session, &update_query, &op.pk, sk_val, txn_id_bytes).await + query_with_pk_sk_txnid( + &self.session, + &update_query, + &op.pk, + sk_val, + txn_id_bytes, + lwt_params, + ) + .await } else { self.session - .query_with_values( + .query_with_params( &update_query, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + lwt_params(cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes)), ) .await .map_err(|e| StorageError::Internal(e.to_string())) diff --git a/crates/storage-cassandra/src/data/ttl.rs b/crates/storage-cassandra/src/data/ttl.rs index e2b2b0fea..b697231aa 100644 --- a/crates/storage-cassandra/src/data/ttl.rs +++ b/crates/storage-cassandra/src/data/ttl.rs @@ -143,7 +143,7 @@ fn same_queue_key(left: &TtlEntry, right: &TtlEntry) -> bool { /// `&mut` needs a swap. Doing that inline at each call site buried the statements /// being built. fn push_query(batch: &mut BatchQueryBuilder, cql: String, values: cdrs_tokio::query::QueryValues) { - let previous = std::mem::replace(batch, BatchQueryBuilder::new()); + let previous = std::mem::replace(batch, crate::cassandra_util::batch_builder()); *batch = previous.add_query(cql, values); } @@ -319,8 +319,7 @@ pub(crate) async fn record_ttl_repair( // account deletion + same-id recreation safe in a multi-host fleet — a // process-lifetime "already registered" cache on any one host would go // stale the moment another host dropped and recreated the keyspace. - let batch = cdrs_tokio::query::BatchQueryBuilder::new() - .with_consistency(cdrs_tokio::consistency::Consistency::LocalQuorum) + let batch = crate::cassandra_util::batch_builder() .add_query( format!( "INSERT INTO {account_keyspace}.ttl_repair_inflight_partitions \ @@ -987,10 +986,11 @@ pub(crate) async fn load_due_ttl_work( "SELECT bucket, shard FROM {account_keyspace}.{TTL_BUCKET_TABLE} \ WHERE table_id = ? AND generation = ? AND bucket <= ?" ); - let bucket_rows = crate::cassandra_util::query_rows( + let bucket_rows = crate::cassandra_util::query_rows_at( &engine.session, &bucket_query, cdrs_tokio::query_values!(table_id, generation_bytes.clone(), current_bucket), + false, "load_due_ttl_buckets", ) .await?; @@ -1276,10 +1276,11 @@ pub(crate) async fn clear_ttl_entries( "SELECT generation, bucket, shard FROM {account_keyspace}.{TTL_BUCKET_TABLE} \ WHERE table_id = ?" ); - let rows = crate::cassandra_util::query_rows( + let rows = crate::cassandra_util::query_rows_at( &engine.session, &bucket_query, cdrs_tokio::query_values!(table_id), + false, "clear_ttl_entries", ) .await?; @@ -1294,14 +1295,14 @@ pub(crate) async fn clear_ttl_entries( ); engine .session - .query_with_values( + .query_with_params( &delete, - cdrs_tokio::query_values!( + crate::cassandra_util::write_params(cdrs_tokio::query_values!( table_id, cdrs_tokio::types::value::Bytes::new(generation.as_bytes().to_vec()), bucket, shard - ), + )), ) .await .map_err(|error| StorageError::Internal(format!("Clear TTL partition: {error}")))?; @@ -1310,7 +1311,10 @@ pub(crate) async fn clear_ttl_entries( format!("DELETE FROM {account_keyspace}.{TTL_BUCKET_TABLE} WHERE table_id = ?"); engine .session - .query_with_values(&delete_buckets, cdrs_tokio::query_values!(table_id)) + .query_with_params( + &delete_buckets, + crate::cassandra_util::write_params(cdrs_tokio::query_values!(table_id)), + ) .await .map_err(|error| StorageError::Internal(format!("Clear TTL buckets: {error}")))?; Ok(()) @@ -1377,7 +1381,7 @@ mod tests { let mut item = Item::new(); item.insert("id".to_owned(), AttributeValue::S("a".to_owned())); item.insert("ttl".to_owned(), AttributeValue::N("123".to_owned())); - let mut batch = BatchQueryBuilder::new(); + let mut batch = crate::cassandra_util::batch_builder(); add_ttl_queue_mutations( &mut batch, "account_keyspace", @@ -1418,7 +1422,7 @@ mod tests { let mut new = old.clone(); new.insert("ttl".to_owned(), AttributeValue::N("456".to_owned())); - let mut batch = BatchQueryBuilder::new(); + let mut batch = crate::cassandra_util::batch_builder(); add_ttl_queue_mutations( &mut batch, "account_keyspace", diff --git a/crates/storage-cassandra/src/data/update_item.rs b/crates/storage-cassandra/src/data/update_item.rs index f90dd4bba..25405eec1 100644 --- a/crates/storage-cassandra/src/data/update_item.rs +++ b/crates/storage-cassandra/src/data/update_item.rs @@ -3,8 +3,6 @@ //! `update_item` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; use extenddb_core::expression::{self, Expr, ExpressionMaps, UpdateAction}; use extenddb_core::types::{Item, KeyType, TableKeyInfo}; use extenddb_core::validation; @@ -15,6 +13,7 @@ use extenddb_storage::util::{parse_sk, pk_to_text, sk_column}; use super::ddl::data_table_name; use super::{json_to_item, query_with_pk_sk}; use crate::CassandraEngine; +use crate::cassandra_util::{lwt_params, query_optional_at, read_params}; use crate::stream_util::stream_record_statement; // 400 KB limit from DynamoDB specification @@ -236,7 +235,9 @@ impl CassandraEngine { )) } - /// Read `item_data`, `version`, and `prepared_txn_id` for OCC. + /// Read `item_data`, `version`, and `prepared_txn_id` for OCC, at + /// `LOCAL_QUORUM`: the update and its condition are evaluated against this + /// image, so the read intersects every acknowledged write. /// /// Returns `(existing_item, version)`. A null `version` column (rows written /// before the OCC protocol was enforced) is treated as `0`. @@ -257,7 +258,10 @@ impl CassandraEngine { let q = format!( "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let result = query_with_pk_sk(&self.session, &q, pk_text, sk).await?; + let result = query_with_pk_sk(&self.session, &q, pk_text, sk, |values| { + read_params(true, values) + }) + .await?; result .response_body() .map_err(|e| StorageError::Internal(format!("occ_read response_body: {e}")))? @@ -269,10 +273,11 @@ impl CassandraEngine { let q = format!( "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ?" ); - crate::cassandra_util::query_optional( + query_optional_at( &self.session, &q, cdrs_tokio::query_values!(pk_text), + true, "occ_read", ) .await? @@ -392,7 +397,7 @@ impl CassandraEngine { // Preserve f997485's Paxos linearization for ordinary writes. let result = self .session - .query_with_values(&lwt_cql, lwt_qv) + .query_with_params(&lwt_cql, lwt_params(lwt_qv)) .await .map_err(|e| StorageError::Internal(format!("occ_write lwt: {e}")))?; if !crate::cassandra_util::lwt_applied(&result)? { @@ -407,7 +412,7 @@ impl CassandraEngine { // claimed row, the exact claim is the fence and the base write joins this // LOGGED BATCH. For an unclaimed row, the LWT above commits first and this // batch durably records all secondary effects and reconciliation work. - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch_builder(); if let Some(timestamp) = mutation_timestamp { batch = batch.with_timestamp(timestamp); } diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 8f49e9664..35d5946a3 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -7,6 +7,12 @@ //! as the underlying database. It provides a DynamoDB-compatible API backed //! by Cassandra's distributed architecture. +// `clippy.toml` disallows the driver calls that run at the driver default +// consistency. The catalog, metadata, backup and bootstrap code outside +// `data/` runs at that default, so the lint is off here and `data/mod.rs` +// turns it back on for the data path. +#![allow(clippy::disallowed_methods)] + pub const CATALOG_VERSION: &str = "0.0.4"; mod admin_store; diff --git a/crates/storage-cassandra/src/metadata_engine.rs b/crates/storage-cassandra/src/metadata_engine.rs index 94c9bfd58..1bd8ca961 100755 --- a/crates/storage-cassandra/src/metadata_engine.rs +++ b/crates/storage-cassandra/src/metadata_engine.rs @@ -617,7 +617,15 @@ impl CassandraEngine { return Ok(None); } let (items, next_key) = self - .scan_impl(&key_info, Some(1_000), start_key.as_ref(), None, None, None) + .scan_impl( + &key_info, + Some(1_000), + start_key.as_ref(), + None, + None, + None, + true, + ) .await?; for item in items { if let Some(entry) = @@ -766,7 +774,15 @@ impl CassandraEngine { return Ok(()); } let (items, next_key) = self - .scan_impl(&key_info, Some(1_000), start_key.as_ref(), None, None, None) + .scan_impl( + &key_info, + Some(1_000), + start_key.as_ref(), + None, + None, + None, + true, + ) .await?; for item in items { if let Some(entry) = @@ -1429,7 +1445,15 @@ impl MetadataEngine for CassandraEngine { let mut start_key = None; loop { let (items, next_key) = self - .scan_impl(&key_info, Some(1_000), start_key.as_ref(), None, None, None) + .scan_impl( + &key_info, + Some(1_000), + start_key.as_ref(), + None, + None, + None, + true, + ) .await?; for item in items { count += 1; diff --git a/crates/storage-cassandra/tests/direct/consistent_read.rs b/crates/storage-cassandra/tests/direct/consistent_read.rs new file mode 100644 index 000000000..239ee5e90 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/consistent_read.rs @@ -0,0 +1,316 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `ReadOptions::consistent_read` reaches every read path of the Cassandra +//! backend: GetItem, Query and Scan return the item with either value, and a +//! keyspace raised to replication factor 3 on the one-node test cluster shows +//! that `true` reads at `LOCAL_QUORUM` and `false` at `LOCAL_ONE`. + +use extenddb_core::expression::{Expr, ExpressionMaps, KeyCondition, PathElement}; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, KeySchemaElement, KeyType, ScalarAttributeType, + TableKeyInfo, +}; +use extenddb_storage::{DataEngine, ReadOptions, TableEngine}; +use std::collections::BTreeMap; + +use crate::helpers::{TestTable, ensure_test_account, setup_engine, unique_test_account}; + +#[tokio::test] +async fn test_get_query_and_scan_return_the_item_with_both_consistent_read_values() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + + // Both table shapes: GetItem binds a sort key or reads by partition only. + for has_sort_key in [true, false] { + let table = TestTable::new(&engine, "ConsistentReadTable", has_sort_key).await; + + let mut item = BTreeMap::new(); + item.insert("id".to_owned(), AttributeValue::S("p1".to_owned())); + if has_sort_key { + item.insert("sort".to_owned(), AttributeValue::S("s1".to_owned())); + } + item.insert("data".to_owned(), AttributeValue::S("v1".to_owned())); + engine + .put_item( + &table.key_info, + item.clone(), + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put_item should succeed"); + + let key = extenddb_core::types::extract_key(&item, &table.key_info.key_schema); + let key_condition = KeyCondition { + pk_path: vec![PathElement::Attribute("id".to_owned())], + pk_value: Expr::Placeholder(":pk".to_owned()), + sk_condition: None, + extra_pk_conditions: vec![], + extra_sk_conditions: vec![], + }; + let mut maps = ExpressionMaps::default(); + maps.values + .insert(":pk".to_owned(), AttributeValue::S("p1".to_owned())); + + for consistent_read in [true, false] { + let opts = ReadOptions::new(consistent_read); + let case = format!("sort key {has_sort_key}, consistent_read {consistent_read}"); + + let got = engine + .get_item(&table.key_info, &key, opts) + .await + .expect("get_item should succeed"); + assert_eq!(got.as_ref(), Some(&item), "get_item, {case}"); + + let (items, last_key) = engine + .query( + &table.key_info, + &key_condition, + &maps, + true, + None, + None, + None, + opts, + ) + .await + .expect("query should succeed"); + assert_eq!(items, vec![item.clone()], "query, {case}"); + assert!(last_key.is_none(), "query, {case}"); + + let (items, last_key) = engine + .scan(&table.key_info, None, None, None, None, None, opts) + .await + .expect("scan should succeed"); + assert_eq!(items, vec![item.clone()], "scan, {case}"); + assert!(last_key.is_none(), "scan, {case}"); + } + } +} + +/// A keyspace with replication factor 3 on a one-node cluster has one live +/// replica, so `LOCAL_ONE` can be met and `LOCAL_QUORUM` (two replicas) +/// cannot. Raising the account keyspace to 3 after the write shows the level +/// each read runs at: with `ConsistentRead: false` GetItem, Query and Scan +/// return the item, and with `true` each one is refused. +#[tokio::test] +async fn test_consistent_read_true_reads_at_local_quorum_and_false_at_local_one() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "QuorumReadTable", true).await; + + let mut item = BTreeMap::new(); + item.insert("id".to_owned(), AttributeValue::S("p1".to_owned())); + item.insert("sort".to_owned(), AttributeValue::S("s1".to_owned())); + engine + .put_item( + &table.key_info, + item.clone(), + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put_item should succeed"); + + let keyspace = engine.account_keyspace(&table.key_info.account_id); + engine + .session_arc() + .query(format!( + "ALTER KEYSPACE {keyspace} WITH replication = \ + {{'class': 'NetworkTopologyStrategy', 'datacenter1': 3}}" + )) + .await + .expect("raise the replication factor"); + + let key = extenddb_core::types::extract_key(&item, &table.key_info.key_schema); + let key_condition = KeyCondition { + pk_path: vec![PathElement::Attribute("id".to_owned())], + pk_value: Expr::Placeholder(":pk".to_owned()), + sk_condition: None, + extra_pk_conditions: vec![], + extra_sk_conditions: vec![], + }; + let mut maps = ExpressionMaps::default(); + maps.values + .insert(":pk".to_owned(), AttributeValue::S("p1".to_owned())); + + let eventual = ReadOptions::new(false); + let got = engine.get_item(&table.key_info, &key, eventual).await; + assert_eq!(got.expect("get_item at LOCAL_ONE"), Some(item.clone())); + let queried = engine + .query( + &table.key_info, + &key_condition, + &maps, + true, + None, + None, + None, + eventual, + ) + .await; + assert_eq!(queried.expect("query at LOCAL_ONE").0, vec![item.clone()]); + let scanned = engine + .scan(&table.key_info, None, None, None, None, None, eventual) + .await; + assert_eq!(scanned.expect("scan at LOCAL_ONE").0, vec![item.clone()]); + + let consistent = ReadOptions::new(true); + let refusals = [ + engine + .get_item(&table.key_info, &key, consistent) + .await + .map(|_| ()), + engine + .query( + &table.key_info, + &key_condition, + &maps, + true, + None, + None, + None, + consistent, + ) + .await + .map(|_| ()), + engine + .scan(&table.key_info, None, None, None, None, None, consistent) + .await + .map(|_| ()), + ]; + for (read, result) in ["get_item", "query", "scan"].iter().zip(refusals) { + // Cassandra answers the read as unavailable; the driver retries it on + // the next node, finds none, and returns that as the error. + assert!(result.is_err(), "{read} with ConsistentRead true succeeded"); + } + + // The node still serves the same reads at `LOCAL_ONE`. + let got = engine.get_item(&table.key_info, &key, eventual).await; + assert_eq!(got.expect("get_item at LOCAL_ONE"), Some(item)); + + // Leave the node as the next test expects it: the keyspace is only + // queued for a drop, so lower it back to replication factor 1. + crate::helpers::ensure_keyspace_rf(&engine, &keyspace) + .await + .expect("restore the replication factor"); +} + +/// A base table whose key has two HASH attributes stores each row under the +/// netstring composite of both parts. GetItem derives the partition key the +/// way the write path does, so it reads the row back with either +/// `ConsistentRead` value; a derivation from the first attribute alone would +/// read `None`. The TTL worker's quorum read shares this derivation. +#[tokio::test] +async fn test_get_item_reads_a_two_part_hash_key_row() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account_id = unique_test_account(); + ensure_test_account(&engine, &account_id) + .await + .expect("test account"); + let key_schema = vec![ + KeySchemaElement { + attribute_name: "tenant".to_owned(), + key_type: KeyType::Hash, + }, + KeySchemaElement { + attribute_name: "id".to_owned(), + key_type: KeyType::Hash, + }, + ]; + let attribute_definitions = vec![ + AttributeDefinition { + attribute_name: "tenant".to_owned(), + attribute_type: ScalarAttributeType::S, + }, + AttributeDefinition { + attribute_name: "id".to_owned(), + attribute_type: ScalarAttributeType::S, + }, + ]; + let input = extenddb_core::types::CreateTableInput { + table_name: "TwoPartHashTable".to_owned(), + key_schema: key_schema.clone(), + attribute_definitions: attribute_definitions.clone(), + local_secondary_indexes: None, + global_secondary_indexes: None, + vector_indexes: None, + billing_mode: None, + table_throughput_mode: None, + provisioned_throughput: None, + on_demand_throughput: None, + stream_specification: None, + sse_specification: None, + tags: None, + table_class: None, + deletion_protection_enabled: None, + }; + let desc = engine + .create_table(&account_id, input) + .await + .expect("create_table"); + let key_info = TableKeyInfo { + table_name: "TwoPartHashTable".to_owned(), + account_id: account_id.clone(), + table_id: desc.table_id, + key_schema: key_schema.clone(), + base_key_schema: key_schema.clone(), + attribute_definitions, + has_lsi: false, + global_secondary_indexes: Vec::new(), + local_secondary_indexes: Vec::new(), + vector_indexes: Vec::new(), + stream_specification: None, + }; + + let mut item = BTreeMap::new(); + item.insert("tenant".to_owned(), AttributeValue::S("t1".to_owned())); + item.insert("id".to_owned(), AttributeValue::S("p1".to_owned())); + item.insert("data".to_owned(), AttributeValue::S("v1".to_owned())); + engine + .put_item( + &key_info, + item.clone(), + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put_item should succeed"); + + let key = extenddb_core::types::extract_key(&item, &key_schema); + for consistent_read in [true, false] { + let got = engine + .get_item(&key_info, &key, ReadOptions::new(consistent_read)) + .await + .expect("get_item should succeed"); + assert_eq!( + got.as_ref(), + Some(&item), + "two-part hash key, consistent_read {consistent_read}" + ); + } + + engine + .delete_table( + &account_id, + extenddb_core::types::DeleteTableInput { + table_name: "TwoPartHashTable".to_owned(), + }, + ) + .await + .expect("delete_table"); +} diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 43eb28b81..4d534702c 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -10,6 +10,10 @@ //! One binary, one module per area, sharing tests/common/mod.rs, which is the //! in-tree descendant of the plug-in repo's helpers.rs. +// The suites set up and inspect Cassandra state with driver calls at the +// driver default; the lint in `clippy.toml` guards `src/data/` only. +#![allow(clippy::disallowed_methods)] + #[path = "common/mod.rs"] mod helpers; @@ -25,6 +29,8 @@ mod authorization_store; mod backup_engine; #[path = "direct/cassandra_engine.rs"] mod cassandra_engine; +#[path = "direct/consistent_read.rs"] +mod consistent_read; #[path = "direct/delete_item.rs"] mod delete_item; #[path = "direct/groups.rs"] diff --git a/crates/storage-cassandra/tests/ttl_bench.rs b/crates/storage-cassandra/tests/ttl_bench.rs index 8a9369dbc..8f147de93 100644 --- a/crates/storage-cassandra/tests/ttl_bench.rs +++ b/crates/storage-cassandra/tests/ttl_bench.rs @@ -15,6 +15,10 @@ //! Reported: put latency on a TTL-enabled vs plain table (the write-path tax), //! and expiration drain throughput (the sweep ceiling). +// The suites set up and inspect Cassandra state with driver calls at the +// driver default; the lint in `clippy.toml` guards `src/data/` only. +#![allow(clippy::disallowed_methods)] + #[path = "common/mod.rs"] mod helpers; diff --git a/crates/storage-cassandra/tests/ttl_integration.rs b/crates/storage-cassandra/tests/ttl_integration.rs index 5934c01ee..570ffc090 100644 --- a/crates/storage-cassandra/tests/ttl_integration.rs +++ b/crates/storage-cassandra/tests/ttl_integration.rs @@ -6,6 +6,10 @@ //! Requires Cassandra on 127.0.0.1:9042. There is no Cassandra CI workflow, so //! these are run locally. +// The suites set up and inspect Cassandra state with driver calls at the +// driver default; the lint in `clippy.toml` guards `src/data/` only. +#![allow(clippy::disallowed_methods)] + #[path = "common/mod.rs"] mod helpers; diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 52a7af299..c165bd0e9 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -176,10 +176,11 @@ pub struct VectorSearch<'a> { /// the read reflects every write acknowledged before it started. `false`: the /// read may miss recently acknowledged writes. A backend that serves every /// read from the copy that took the write meets both by ignoring the value; -/// every in-tree backend does that today. A backend with followers can serve -/// `false` from a follower (a `secondaryPreferred` read on MongoDB, a -/// streaming replica on PostgreSQL); a quorum backend needs read and write -/// levels that intersect for `true`. +/// the SQLite, PostgreSQL and MongoDB backends do that today. A backend with +/// followers can serve `false` from a follower (a `secondaryPreferred` read on +/// MongoDB, a streaming replica on PostgreSQL); a quorum backend needs read +/// and write levels that intersect for `true`, which the Cassandra backend +/// gets from `LOCAL_QUORUM` reads and `LOCAL_QUORUM` writes. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[non_exhaustive] pub struct ReadOptions { diff --git a/docs/adr/0025-cassandra-statement-consistency-levels.md b/docs/adr/0025-cassandra-statement-consistency-levels.md new file mode 100644 index 000000000..6390bc26d --- /dev/null +++ b/docs/adr/0025-cassandra-statement-consistency-levels.md @@ -0,0 +1,123 @@ +# ADR-0025: Cassandra: every data-path statement states its consistency level + +- Status: Accepted +- Date: 2026-10-26 +- Deciders: @lhnng + +## Context + +The Cassandra driver runs a statement with no stated level at `ONE`: one +replica acknowledges a write, one replica answers a read. Before this decision +the data path (`crates/storage-cassandra/src/data/`) ran 105 statements that +way: the reads behind GetItem, Query and Scan, the reads whose result a +following write conditions on, the OCC and put-if-absent lightweight +transactions (their Paxos round at the server default `SERIAL`, their commit +at `ONE`), the plain delete, the transaction prepare and commit statements and +the transaction ledger. The conditional delete, the TTL claims and the +secondary-effects batches already ran at `LOCAL_QUORUM`. + +Each keyspace the backend creates replicates with `NetworkTopologyStrategy` +to the one datacenter named by `datacenter`, with `replication_factor` 3 by +default. A read at `ONE` against a write acknowledged at `ONE` can answer +from a replica the write has not reached, so `ConsistentRead: true` was not +honoured above replication factor 1 (issue #560). ADR-0024 carries the flag +to the backend as `ReadOptions::consistent_read`; this decision is what the +Cassandra backend does with it, and with every other statement it runs. + +## Options Considered + +1. Raise the read level alone: `true` reads at `QUORUM` or `LOCAL_QUORUM`, + writes unchanged at `ONE`. A quorum read and a one-replica write do not + intersect, so the read can still miss the write. Rejected by issue #560 + and here. +2. `SERIAL` reads for `true`. A serial read runs a Paxos round per read; it + answers the same question as a quorum read at several times the cost and + only on tables whose writes are all lightweight transactions. Rejected. +3. `QUORUM` and `SERIAL` for reads, writes and Paxos. The keyspace lives in + one datacenter, where `QUORUM` and `LOCAL_QUORUM` count the same replicas; + the `LOCAL_` forms keep the contract per datacenter if an operator ever + replicates a keyspace to a second one. Rejected in favour of the local + forms. +4. Reads at the level the request names, every write at `LOCAL_QUORUM`, + every lightweight transaction at `LOCAL_QUORUM` with `LOCAL_SERIAL`, and + a lint that refuses a statement at the driver default. Chosen. + +For the guard: per-call `#[allow]` outside `data/` on each of the 225 calls +that run at the default there (catalog, metadata, backup, bootstrap) was +rejected for one crate-level allow with the lint turned back on for `data/`. + +## Decision + +Every statement under `crates/storage-cassandra/src/data/` states its level +through one of four constructors in `cassandra_util`: + +- `read_params(consistent_read, values)`: `LOCAL_QUORUM` for `true`, + `LOCAL_ONE` for `false`. GetItem, Query and Scan pass the request's flag. + A read whose result decides a write (the OCC reads before put, update and + delete, the transaction reads, the idempotency token reads, the ledger + reads the recovery worker acts on) and a table walk (the export scan, the + metadata walks, the global secondary index backfill) pass `true`. Catalog + and queue metadata reads pass `false`. +- `write_params(values)`: `LOCAL_QUORUM`, for every statement without an + `IF` clause. +- `lwt_params(values)`: `LOCAL_QUORUM` with serial `LOCAL_SERIAL`, for every + statement with an `IF` clause. +- `batch_builder()`: a `BatchQueryBuilder` at `LOCAL_QUORUM`, for every + batch. + +The four schema statements in `ddl.rs` stay at the driver default, each with +a statement-level allow. `clippy.toml` disallows `Session::query`, +`query_with_values`, `exec`, `exec_with_values` and `paged`, +`StatementParamsBuilder::new`, `BatchQueryBuilder::new` and the four +`cassandra_util` helpers that run at the default; the crate allows the lint +outside `data/` and `data/mod.rs` turns it back on. A test in +`data/level_pairing_tests.rs` reads the statement sites in `data/` whose CQL +and level it can resolve (121 sites on the tree this record describes) and +checks that a `SELECT` carries a read level, a plain write `write_params` and +an `IF` statement `lwt_params`, and that no `BatchQueryBuilder::new`, +`BatchQueryBuilder::default`, `Default::default()` or `.with_consistency(` +appears under `data/`, so a batch is built by `batch_builder()` or not at all; +the lint cannot see which constructor a call passes. + +## Rationale + +With base-row writes acknowledged by a local quorum, a `LOCAL_QUORUM` read +reaches a majority of the same `replication_factor` replicas the write +reached, and two majorities of one replica set share a replica, so a `true` +read reflects every write acknowledged before it started. `LOCAL_ONE` may +miss a recently acknowledged write, which is the contract for `false`. The +reads that decide a write take the quorum level because the condition is +evaluated against that image before the lightweight transaction runs; a +stale image would make the transaction apply against the wrong state. A +Paxos round at `LOCAL_SERIAL` and a commit at `LOCAL_QUORUM` keep a +lightweight transaction's linearizability within the datacenter. + +## Consequences + +- A `ConsistentRead: true` read, a plain write and a lightweight transaction + need `replication_factor / 2 + 1` replicas up in `datacenter`: two of three + at the default. At replication factor 1 every statement needs the one + replica, as before. The lightweight transactions already needed a Paxos + majority; their commit now waits for a local quorum instead of one replica. + A `ConsistentRead: false` read needs one replica. +- A request that cannot reach its level fails as a storage fault (HTTP 500 + `InternalServerError`; the server log carries the driver's text). The + driver sends statements to every node it discovers, so a coordinator in a + datacenter that holds no replica of the keyspace refuses `LOCAL_QUORUM` and + `LOCAL_ONE` statements; ExtendDB is run against nodes in `datacenter`. + Routing coordinators to `datacenter` and classifying the driver's + unavailable error as transient are tracked separately. +- Reads of catalog and queue metadata stay at one replica; the four of them + that feed a write or a cleanup are tracked separately. +- Before this decision the reads, the OCC and put-if-absent lightweight + transactions, the plain delete and the transaction statements ran at the + driver default `ONE`; the conditional delete, the TTL claims and the + secondary-effects batches already ran at `LOCAL_QUORUM`. +- ADR-0024's Consequences, written before this decision, describe the + Cassandra backend as serving `true` at `ONE`; that sentence is history, and + this record is the current statement. + +## License + +Copyright 2026 ExtendDB contributors. Licensed under the Apache License, +Version 2.0. See [LICENSE](../../LICENSE) for the full text. diff --git a/docs/adr/README.md b/docs/adr/README.md index f5b489b01..42dfb5cff 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -49,4 +49,5 @@ decision, write a new ADR. | [0020](0020-cassandra-occ-update-item.md) | Cassandra: optimistic concurrency control for UpdateItem and PutItem | Accepted | | [0021](0021-cassandra-lwt-delete-atomicity-gap.md) | Cassandra: LWT delete atomicity gap and required worker/saga pattern | Accepted | | [0022](0022-trust-policy-deny-over-allow.md) | Role trust-policy evaluation follows IAM Deny-over-Allow order | Accepted | -| [0024](0024-read-options-parameter.md) | Read consistency reaches storage as a `ReadOptions` parameter | Accepted | \ No newline at end of file +| [0024](0024-read-options-parameter.md) | Read consistency reaches storage as a `ReadOptions` parameter | Accepted | +| [0025](0025-cassandra-statement-consistency-levels.md) | Cassandra: every data-path statement states its consistency level | Accepted | diff --git a/docs/design/04-component-storage.md b/docs/design/04-component-storage.md index 4b59b143d..a5d054c19 100755 --- a/docs/design/04-component-storage.md +++ b/docs/design/04-component-storage.md @@ -144,9 +144,15 @@ widen the three signatures again. The contract is what the read returns: with `true` the read reflects every write acknowledged before it started; with `false` it may miss recently acknowledged writes. A backend that serves every read from the copy that took the write meets both by ignoring the value, which -the SQLite, PostgreSQL and MongoDB backends do today; the Cassandra backend -reads at `ONE` against a keyspace whose replication factor defaults to 3, so -it does not meet `true` (ADR-0024, Consequences; issue #560). A backend with followers can serve `false` +the SQLite, PostgreSQL and MongoDB backends do today. The Cassandra backend +reads `true` at `LOCAL_QUORUM` and `false` at `LOCAL_ONE` and acknowledges +base-row writes at `LOCAL_QUORUM` (ADR-0025). It creates each keyspace with +`NetworkTopologyStrategy` in the one datacenter named by `datacenter`, so a +`LOCAL_QUORUM` read and a `LOCAL_QUORUM` write each reach a majority of the +same `replication_factor` replicas and a `true` read reflects every write +acknowledged before it started; a keyspace altered to replicate to a second +datacenter keeps this only for a read and a write coordinated in the same +datacenter. A backend with followers can serve `false` from a follower (a streaming replica on PostgreSQL, where section 5.3 describes that routing as a proposal; a `secondaryPreferred` read selected per operation on MongoDB); a quorum backend needs read and write levels that intersect for diff --git a/docs/design/11-high-availability.md b/docs/design/11-high-availability.md index 1c958a6cb..9bc5581fc 100755 --- a/docs/design/11-high-availability.md +++ b/docs/design/11-high-availability.md @@ -137,10 +137,19 @@ This is the minimal mechanism needed to honor DynamoDB's consistency model. It w ``` - Storage layer maps DynamoDB consistency to native consistency levels. - - `ConsistentRead = true` → `QUORUM` or `LOCAL_QUORUM` - - `ConsistentRead = false` → `ONE` or `LOCAL_ONE` + - `ConsistentRead = true` → `LOCAL_QUORUM` + - `ConsistentRead = false` → `LOCAL_ONE` + - Base-row writes are acknowledged at `LOCAL_QUORUM` (lightweight + transactions with serial consistency `LOCAL_SERIAL`). The backend creates + each keyspace with `NetworkTopologyStrategy` in the one datacenter named + by `datacenter`, so a `LOCAL_QUORUM` read and a `LOCAL_QUORUM` write each + reach a majority of the same `replication_factor` replicas (ADR-0025). + - The driver sends statements to every node it discovers; a coordinator in + a datacenter that holds no replica of the keyspace refuses `LOCAL_QUORUM` + and `LOCAL_ONE` statements. ExtendDB is run against nodes in `datacenter`. - No separate primary/replica distinction — the storage adapter handles it. -- Suitable for: large-scale deployments, multi-datacenter. +- Suitable for: large-scale deployments within one datacenter; a second + datacenter needs coordinator routing that the backend does not have yet. ### Model 5: Multi-Region (Future) @@ -414,7 +423,9 @@ This avoids adding yet another trait that every storage backend must implement. Status (2026-10-25): done, as `ReadOptions` rather than a bare `bool` and without the `ConsistencyLevel` enum (section 8 status note, ADR-0024). All -four in-tree backends accept the parameter; none routes on it. +four in-tree backends accept the parameter. The Cassandra backend routes on +it since issue #560 (Model 4, ADR-0025); the SQLite, PostgreSQL and MongoDB +backends ignore it. **Deliverable:** Add `consistent_read: bool` parameter to `get_item`, `query`, and `scan` in the `DataEngine` trait. Thread it from the engine layer call sites. The PostgreSQL backend accepts the parameter but ignores it (all reads go to the single connection). All existing tests pass unchanged. @@ -548,7 +559,7 @@ Each frontend attempts to acquire the lock on its worker tick interval. If it ge | Backend | Write Leader | Strong Read Leader | Eventually Consistent Read | |---------|-------------|-------------------|---------------------------| | PostgreSQL (streaming replication) | Primary node | Primary node | Any replica | -| Cassandra | Coordinator (any node) | QUORUM nodes | ONE node | +| Cassandra | Coordinator (any node in `datacenter`), acknowledged at `LOCAL_QUORUM` | `LOCAL_QUORUM` nodes in `datacenter` | `LOCAL_ONE` node in `datacenter` | | MongoDB (replica set) | Primary member | Primary member | Secondary preferred (falls back to primary if no secondaries available) | | Single PostgreSQL (no replicas) | The single node | The single node | The single node (no distinction) | diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 2d6469b7e..f6584f4a5 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -67,6 +67,7 @@ adaptation when switching between ExtendDB and the real service. | Enabling Cassandra TTL on a live table | No application write quiescence required | Writes that began while TTL was disabled must be quiesced until enable and synchronous backfill complete. Prefer enabling TTL before opening a new table to traffic. Once enabled, writes use the durable exact-claim path. | | TTL expiration throughput | Managed by the service | Cassandra: about 1,000 items per table per minute — the sweep processes its batch concurrently across the queue's shard partitions under one per-table lease. Other backends: about 100 per table per minute (a serial 100-item batch per 60-second cycle, with unleased hosts contending for the same rows). A table expiring faster than its backend's rate accumulates backlog. | | Cassandra TTL deployment bounds | Managed by the service | Writes for a table must be served from one Cassandra datacenter — claims and lifecycle LWTs use `LOCAL_QUORUM`/`LOCAL_SERIAL` and are linearizable only within a datacenter. Cassandra coordinators and ExtendDB hosts must remain time-synchronized because request batches use explicit timestamps, and request deadlines must stay well below the 120-second request claim lifetime. A write whose queue mutation loses an internal race is repaired by the background outbox; an ambiguous queue destroy retains a non-dischargeable marker that is rechecked every worker pass. | +| Cassandra read and write consistency | `ConsistentRead: true` reflects every write acknowledged before the read started; `false` may miss recent writes | `true` reads at `LOCAL_QUORUM`, `false` at `LOCAL_ONE`; every item write is acknowledged at `LOCAL_QUORUM` and every conditional write runs its Paxos round at `LOCAL_SERIAL` (ADR-0025). A local quorum is `replication_factor / 2 + 1` replicas in `datacenter`, two of three at the default; a request that cannot reach it fails with HTTP 500 `InternalServerError`. Every keyspace replicates to the one datacenter named by `datacenter`, and the driver sends statements to every node it discovers, so the contact points and their peers must all be in that datacenter. Catalog and queue metadata reads use one replica | | Cassandra TTL lifecycle contention | Not observable | Enabling or disabling TTL, and creating an index that would invalidate a live sweep, take a short lease and retry briefly. Sustained collision reports `ResourceInUseException` with a retry hint. | | TTL modification cooldown | Enforces a cooldown period between enable/disable changes ("Time to live has been modified multiple times within a fixed interval") | No cooldown — TTL can be enabled and disabled immediately. Intentional divergence for faster local development. | diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 23c1cb6f5..65390322a 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -319,6 +319,54 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### Cassandra: reads with `ConsistentRead: true` and every item write need a local quorum + +**What changed.** The Cassandra backend now reads with `ConsistentRead: true` +(GetItem, Query, Scan, and each table of a BatchGetItem that asks for it) at +`LOCAL_QUORUM` and with `ConsistentRead: false` at `LOCAL_ONE`, and every write +of item data is acknowledged at `LOCAL_QUORUM`; conditional writes run their +Paxos round at `LOCAL_SERIAL`. The export scan, the global secondary index +backfill and the reads that decide a write also read at `LOCAL_QUORUM`. Before +this release these reads and writes ran at the driver default, `ONE`, so with a +replication factor above 1 a `ConsistentRead: true` read could return an item +as it was before a write the client had seen succeed (issue #560, ADR-0025). +Catalog and queue reads still read one replica. + +**Who is affected.** Every Cassandra deployment whose keyspaces have a +replication factor above 1. A local quorum is `replication_factor / 2 + 1` +replicas in the datacenter named by `datacenter`: two of three at the default +of 3. + +- A `ConsistentRead: true` read, an export, and a DeleteItem of an item that + does not exist now need a local quorum up, where one replica answered before. + With fewer replicas up the request fails with HTTP 500 + `InternalServerError`, and the server logs the driver error: "Cannot achieve + consistency level LOCAL_QUORUM" on a cluster, "No nodes available in query + plan!" on a single node. A `ConsistentRead: false` read still needs one + replica. +- PutItem, UpdateItem, DeleteItem of an existing item and TransactWriteItems + already needed a quorum for their Paxos round. Their commit now waits for a + local quorum to acknowledge it instead of one replica, which adds the time of + the second acknowledgement to each write. +- A single node whose keyspaces were created at replication factor 3 refuses + every `ConsistentRead: true` read, as it already refused PutItem and + UpdateItem. A configuration file without `replication_factor` uses 3. +- Every keyspace replicates to the one datacenter named by `datacenter`, and + the driver sends statements to every node it discovers. A coordinator in a + datacenter that holds no replica refuses `LOCAL_QUORUM` and `LOCAL_ONE` + statements, and the driver retries once on the next node. Run ExtendDB + against contact points whose peers are all in `datacenter`. + +**Migration.** No catalog migration is required. Before upgrading: + +- On a single node, set `replication_factor = 1`. The setting applies only to + keyspaces created after it changes, so lower each existing keyspace whose + name starts with `_` (the catalog keyspace and one keyspace + per account): + `ALTER KEYSPACE WITH replication = {'class': 'NetworkTopologyStrategy', '': 1};` +- On a cluster at replication factor 3, keep two replicas of every token range + up in `datacenter`: take one node down at a time. + ### v0.1.14 LeadingKeys now enforced on Query, batch and transaction operations **What changed.** `dynamodb:LeadingKeys` is now evaluated on `Query`, diff --git a/docs/manuals/12-extending-extenddb-storage.md b/docs/manuals/12-extending-extenddb-storage.md index ae8abc6c1..8bdd459af 100755 --- a/docs/manuals/12-extending-extenddb-storage.md +++ b/docs/manuals/12-extending-extenddb-storage.md @@ -98,7 +98,7 @@ Key design decisions: - **Items** are `BTreeMap`. A new backend must handle the full `AttributeValue` type (S, N, B, SS, NS, BS, L, M, BOOL, NULL). - **Query** must support forward/reverse sort order, exclusive start key pagination, and routing to secondary index storage. - **Parallel scan** uses `segment` and `total_segments` to partition the keyspace. -- **Read options**: `get_item`, `query` and `scan` take a `ReadOptions` value as their last parameter. Its `consistent_read` field is the request's `ConsistentRead` as the client sent it, `false` when absent and always `false` for a read through a global secondary index (the engine refuses `ConsistentRead: true` on a GSI before storage is called); a local secondary index read carries the client's value. `BatchGetItem` passes each table's own `KeysAndAttributes.ConsistentRead` on its per-key `get_item` calls, and the export scan passes `true` because an export reflects every write acknowledged before the export time. The contract is what the read returns: with `true` the read reflects every write acknowledged before it started; with `false` it may miss recently acknowledged writes. A backend that serves every read from the copy that took the write meets both by ignoring the value, which is what the SQLite, PostgreSQL and MongoDB backends do today; the Cassandra backend reads at `ONE` against a keyspace whose replication factor defaults to 3, so it does not meet `true` (ADR-0024, Consequences; issue #560). A backend with followers can serve `false` from a follower (a `secondaryPreferred` read on MongoDB, a streaming replica on PostgreSQL); a quorum backend needs read and write levels that intersect for `true`. The struct is `#[non_exhaustive]`; build one with `ReadOptions::new(consistent_read)` or `ReadOptions::default()`, which a field added later will not break. +- **Read options**: `get_item`, `query` and `scan` take a `ReadOptions` value as their last parameter. Its `consistent_read` field is the request's `ConsistentRead` as the client sent it, `false` when absent and always `false` for a read through a global secondary index (the engine refuses `ConsistentRead: true` on a GSI before storage is called); a local secondary index read carries the client's value. `BatchGetItem` passes each table's own `KeysAndAttributes.ConsistentRead` on its per-key `get_item` calls, and the export scan passes `true` because an export reflects every write acknowledged before the export time. The contract is what the read returns: with `true` the read reflects every write acknowledged before it started; with `false` it may miss recently acknowledged writes. A backend that serves every read from the copy that took the write meets both by ignoring the value, which is what the SQLite, PostgreSQL and MongoDB backends do today. The Cassandra backend reads `true` at `LOCAL_QUORUM` and `false` at `LOCAL_ONE` and acknowledges base-row writes at `LOCAL_QUORUM` (ADR-0025); it creates each keyspace with `NetworkTopologyStrategy` in the one datacenter named by `datacenter`, so a `LOCAL_QUORUM` read and a `LOCAL_QUORUM` write each reach a majority of the same `replication_factor` replicas, and a `true` read reflects every write acknowledged before it started. A backend with followers can serve `false` from a follower (a `secondaryPreferred` read on MongoDB, a streaming replica on PostgreSQL); a quorum backend needs read and write levels that intersect for `true`. The struct is `#[non_exhaustive]`; build one with `ReadOptions::new(consistent_read)` or `ReadOptions::default()`, which a field added later will not break. ### MetadataEngine From 58280c9b12bb38b10f6796b9b866b203850d00db Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Mon, 26 Oct 2026 01:40:15 +0000 Subject: [PATCH 2/4] test(cassandra): read the node address from EXTENDDB_TEST_CASSANDRA_ADDR The integration suites hardwired 127.0.0.1:9042 in the test configuration and the readiness probe. Both now read EXTENDDB_TEST_CASSANDRA_ADDR as host:port and fall back to 127.0.0.1:9042, so a suite can run against a node on another port beside a node another job uses. The crate docs of the two suites name the variable in place of the port. --- crates/storage-cassandra/tests/common/mod.rs | 29 ++++++++++++++----- .../tests/direct_integration.rs | 7 +++-- .../tests/ttl_integration.rs | 3 +- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/storage-cassandra/tests/common/mod.rs b/crates/storage-cassandra/tests/common/mod.rs index c1fd1e971..a903559b3 100644 --- a/crates/storage-cassandra/tests/common/mod.rs +++ b/crates/storage-cassandra/tests/common/mod.rs @@ -46,10 +46,16 @@ pub async fn flush_pending_drops(session: &Arc) { let _ = session.query(format!("DROP KEYSPACE IF EXISTS {ks}")).await; } } +/// The Cassandra node the suites use, as `host:port`: the value of +/// `EXTENDDB_TEST_CASSANDRA_ADDR`, or `127.0.0.1:9042` when it is unset. +pub fn test_cassandra_addr() -> String { + std::env::var("EXTENDDB_TEST_CASSANDRA_ADDR").unwrap_or_else(|_| "127.0.0.1:9042".to_owned()) +} + /// Returns a standard test configuration for Cassandra. pub fn test_config() -> CassandraStorageConfig { let mut config = CassandraStorageConfig { - contact_points: vec!["127.0.0.1:9042".to_string()], + contact_points: vec![test_cassandra_addr()], username: Some("cassandra".to_string()), password: Some("cassandra".to_string()), keyspace_prefix: "extenddb_ttl_test".to_string(), @@ -715,24 +721,31 @@ pub async fn put_item_then_lock( /// True when the suite should be skipped because no Cassandra is reachable. /// /// The workspace `cargo test` job in test.yml runs with no services, so these -/// suites probe 127.0.0.1:9042 and skip themselves when nothing is listening. +/// suites probe the node [`test_cassandra_addr`] names (`127.0.0.1:9042` +/// unless `EXTENDDB_TEST_CASSANDRA_ADDR` sets another `host:port`) and skip +/// themselves when nothing is listening there. /// The dedicated integration-cassandra workflow provides a service container /// and sets `EXTENDDB_TEST_CASSANDRA=required`, under which this never skips: /// if Cassandra is down there, setup fails loudly rather than the suite /// silently passing with zero tests executed (the failure mode integration.yml /// documents for batch_transact_authz). pub fn skip_without_cassandra() -> bool { + use std::net::ToSocketAddrs as _; + if std::env::var("EXTENDDB_TEST_CASSANDRA").as_deref() == Ok("required") { return false; } - let reachable = std::net::TcpStream::connect_timeout( - &std::net::SocketAddr::from(([127, 0, 0, 1], 9042)), - std::time::Duration::from_secs(2), - ) - .is_ok(); + let addr = test_cassandra_addr(); + let reachable = addr + .to_socket_addrs() + .ok() + .and_then(|mut resolved| resolved.next()) + .is_some_and(|socket| { + std::net::TcpStream::connect_timeout(&socket, std::time::Duration::from_secs(2)).is_ok() + }); if !reachable { eprintln!( - "skipping: no Cassandra at 127.0.0.1:9042 (set EXTENDDB_TEST_CASSANDRA=required to fail instead)" + "skipping: no Cassandra at {addr} (set EXTENDDB_TEST_CASSANDRA=required to fail instead)" ); } !reachable diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 4d534702c..299ff316f 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -3,9 +3,10 @@ //! Direct storage-trait integration tests, ported from the original //! extenddb-cassandra-plugin repository (its tests/rust suite). They exercise -//! the Cassandra engine's trait implementations directly against a live node -//! at 127.0.0.1:9042 — no HTTP server in between — and skip themselves when -//! no Cassandra is reachable (see helpers::skip_without_cassandra). +//! the Cassandra engine's trait implementations directly, with no HTTP server +//! in between, against a live node at 127.0.0.1:9042 or the `host:port` in +//! `EXTENDDB_TEST_CASSANDRA_ADDR`, and skip themselves when no Cassandra is +//! reachable (see helpers::skip_without_cassandra). //! //! One binary, one module per area, sharing tests/common/mod.rs, which is the //! in-tree descendant of the plug-in repo's helpers.rs. diff --git a/crates/storage-cassandra/tests/ttl_integration.rs b/crates/storage-cassandra/tests/ttl_integration.rs index 570ffc090..41fc37484 100644 --- a/crates/storage-cassandra/tests/ttl_integration.rs +++ b/crates/storage-cassandra/tests/ttl_integration.rs @@ -3,7 +3,8 @@ //! Integration tests for Cassandra TTL against a live Cassandra. //! -//! Requires Cassandra on 127.0.0.1:9042. There is no Cassandra CI workflow, so +//! Requires Cassandra on 127.0.0.1:9042, or on the `host:port` that +//! `EXTENDDB_TEST_CASSANDRA_ADDR` names. There is no Cassandra CI workflow, so //! these are run locally. // The suites set up and inspect Cassandra state with driver calls at the From 698d7f6c3d7c4710a113980bc2f91f52e607c355 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Tue, 27 Oct 2026 18:40:17 +0000 Subject: [PATCH 3/4] docs(adr): name ADR-0025's decider by GitHub handle The Deciders line named @lhnng, which is not a GitHub account. ADR-0004, ADR-0005 and ADR-0023 name the same author as @LeeroyHannigan. --- docs/adr/0025-cassandra-statement-consistency-levels.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/adr/0025-cassandra-statement-consistency-levels.md b/docs/adr/0025-cassandra-statement-consistency-levels.md index 6390bc26d..6551108c5 100644 --- a/docs/adr/0025-cassandra-statement-consistency-levels.md +++ b/docs/adr/0025-cassandra-statement-consistency-levels.md @@ -2,7 +2,7 @@ - Status: Accepted - Date: 2026-10-26 -- Deciders: @lhnng +- Deciders: @LeeroyHannigan ## Context From c806636517f5025dc8f5014c234488bc0cfd2af9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:16:50 +0000 Subject: [PATCH 4/4] fix(storage-cassandra): build the restored item batch with batch_builder Main added put_restored_item_at, which starts its batch with BatchQueryBuilder::new() and sets LOCAL_QUORUM on it. This branch builds every data path batch with cassandra_util::batch_builder, which sets the same level, and its lint and level pairing test refuse any other constructor. The batch now comes from batch_builder. It keeps its level and its timestamp. Main also added the warm_throughput field to CreateTableInput. The table literal in the consistent_read integration test sets it to None. --- crates/storage-cassandra/src/data/put_get_item.rs | 3 +-- crates/storage-cassandra/tests/direct/consistent_read.rs | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/storage-cassandra/src/data/put_get_item.rs b/crates/storage-cassandra/src/data/put_get_item.rs index 88a9acd75..c240b1881 100644 --- a/crates/storage-cassandra/src/data/put_get_item.rs +++ b/crates/storage-cassandra/src/data/put_get_item.rs @@ -150,8 +150,7 @@ impl CassandraEngine { }; // The batch carries the timestamp, so the index statements pass none // of their own (Cassandra refuses a batch with both). - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) + let mut batch = crate::cassandra_util::batch_builder() .with_timestamp(stamp) .add_query(cql, cdrs_tokio::query::QueryValues::SimpleValues(values)); if !indexes.is_empty() { diff --git a/crates/storage-cassandra/tests/direct/consistent_read.rs b/crates/storage-cassandra/tests/direct/consistent_read.rs index 239ee5e90..834359726 100644 --- a/crates/storage-cassandra/tests/direct/consistent_read.rs +++ b/crates/storage-cassandra/tests/direct/consistent_read.rs @@ -256,6 +256,7 @@ async fn test_get_item_reads_a_two_part_hash_key_row() { tags: None, table_class: None, deletion_protection_enabled: None, + warm_throughput: None, }; let desc = engine .create_table(&account_id, input)