From 2801d54ea3f4dda80d1f9f037723ebd2f9c03d84 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 00:08:56 +0000 Subject: [PATCH 1/5] chore: raise MSRV to Rust 1.100.0 Lets the workspace use standard library APIs stabilized in 1.100, such as trim_prefix/trim_suffix, Vec::from_fn and core::mem::DropGuard, which the following commits adopt. The MSRV now matches the pinned toolchain. The Build (Rust MSRV) job reads rust-version from Cargo.toml, so it moves to 1.100.0 without workflow changes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- Cargo.toml | 2 +- DEVELOPMENT.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3c74243..2d966b22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **Database errors logged at debug level**: errors that PostgreSQL returns to a client are now logged concisely at `debug` level (`CS_LOG__PROTOCOL_LEVEL=debug` shows them), instead of in full at `error` level. Errors that Proxy itself generates are still logged. -- **Minimum supported Rust version**: building Proxy from source now requires Rust 1.89.0 or later, declared as `rust-version` in `Cargo.toml` so Cargo reports an older compiler clearly instead of failing deep in a dependency. CI builds the production binary on Rust 1.89.0 to keep that minimum from rising by accident. Development, tests, and release binaries use the Rust version pinned in `rust-toolchain.toml` (currently 1.100.0). See [Supported Rust versions](DEVELOPMENT.md#supported-rust-versions). +- **Minimum supported Rust version**: building Proxy from source now requires Rust 1.100.0 or later, declared as `rust-version` in `Cargo.toml` so Cargo reports an older compiler clearly instead of failing deep in a dependency. Proxy uses standard library APIs stabilized in Rust 1.100. CI builds the production binary on Rust 1.100.0 to keep that minimum from rising by accident. Development, tests, and release binaries use the Rust version pinned in `rust-toolchain.toml` (currently 1.100.0). See [Supported Rust versions](DEVELOPMENT.md#supported-rust-versions). - **PostgreSQL execution lifecycle ownership**: Proxy now tracks prepared statements, portals, Describe operations, execution outcomes, and execution metrics as one connection-local protocol lifecycle. Suspended executions retain their original metrics scope until completion, repeated portal executions receive distinct scopes, and terminal errors replace upstream responses atomically while schema outcomes are reported exactly once. diff --git a/Cargo.toml b/Cargo.toml index 91d8d148..5d1ab2d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ edition = "2021" # Minimum supported Rust version (MSRV). CI builds the production binary on # exactly this toolchain. See "Supported Rust versions" in DEVELOPMENT.md # before changing it. -rust-version = "1.89.0" +rust-version = "1.100.0" [profile.dev] incremental = true diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index eab6fc65..975340bf 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -145,19 +145,19 @@ CI uses three Rust toolchains: |---|---|---| | **Pinned** (currently 1.100.0) | `rust-toolchain.toml` | Formatting, Clippy, unit and integration tests across the full PostgreSQL matrix, burn-in, benchmarks, and release binaries (`mise run build:binary`). | | **Latest stable** | floating `stable` channel | `Lint (Rust stable)`: formatting and Clippy only. | -| **Minimum supported (MSRV)** (currently 1.89.0) | `rust-version` under `[workspace.package]` in `Cargo.toml` | `Build (Rust MSRV)`: builds the production binary with `cargo build --locked --release --package cipherstash-proxy`. | +| **Minimum supported (MSRV)** (currently 1.100.0) | `rust-version` under `[workspace.package]` in `Cargo.toml` | `Build (Rust MSRV)`: builds the production binary with `cargo build --locked --release --package cipherstash-proxy`. | The MSRV build and stable lint jobs need no PostgreSQL or credentials. Locally, rustup selects the pinned toolchain automatically from `rust-toolchain.toml`. -Rust 1.88 cannot build Proxy: a transitive dependency (`stack-profile`, via `cipherstash-client`) uses `std::fs::File::lock`, which stabilized in 1.89, without declaring that requirement. +The MSRV is 1.100.0 because Proxy uses standard library APIs stabilized in that release, such as `str::trim_prefix`, `Vec::from_fn` and `core::mem::DropGuard`. The MSRV and the pinned toolchain are currently the same version, so the two jobs differ only in what they run. To run those checks locally: ```shell cargo +stable clippy --all --no-deps --all-targets --all-features -- -D warnings -rustup toolchain install 1.89.0 --profile minimal -cargo +1.89.0 build --locked --release --package cipherstash-proxy +rustup toolchain install 1.100.0 --profile minimal +cargo +1.100.0 build --locked --release --package cipherstash-proxy ``` #### Bumping the pinned toolchain From 6446bb0b758309a599de2a5cee7a4368b75ef956 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 00:09:20 +0000 Subject: [PATCH 2/5] refactor: use trim_prefix and trim_suffix Replaces strip_prefix/strip_suffix followed by unwrap_or(original) with the trim_* methods stabilized in Rust 1.100, which state the intent directly: remove the affix if present, otherwise keep the input. Behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/postgresql/middleware/backend.rs | 4 ++-- packages/eql-mapper/src/inference/unifier/types.rs | 8 ++------ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs index 4cf92d41..33d31230 100644 --- a/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs +++ b/packages/cipherstash-proxy/src/postgresql/middleware/backend.rs @@ -761,13 +761,13 @@ impl PostgreSqlErrorHandler for Backend { /// Whether a `CommandComplete` tag confirms a `DEALLOCATE` or `DISCARD ALL` pub(super) fn is_deallocation(tag: &[u8]) -> bool { - let tag = tag.strip_suffix(b"\0").unwrap_or(tag); + let tag = tag.trim_suffix(b"\0"); matches!(tag, b"DEALLOCATE" | b"DEALLOCATE ALL" | b"DISCARD ALL") } /// Whether a deallocation command tag removes every prepared statement fn removes_all_statements(tag: &[u8]) -> bool { - let tag = tag.strip_suffix(b"\0").unwrap_or(tag); + let tag = tag.trim_suffix(b"\0"); matches!(tag, b"DEALLOCATE ALL" | b"DISCARD ALL") } diff --git a/packages/eql-mapper/src/inference/unifier/types.rs b/packages/eql-mapper/src/inference/unifier/types.rs index a5ced6b4..9f435501 100644 --- a/packages/eql-mapper/src/inference/unifier/types.rs +++ b/packages/eql-mapper/src/inference/unifier/types.rs @@ -434,7 +434,7 @@ impl DomainIdentity { self.domain .value .get(prefix_len..) - .map(|rest| rest.strip_prefix('_').unwrap_or(rest)) + .map(|rest| rest.trim_prefix('_')) .unwrap_or("") } @@ -515,11 +515,7 @@ impl DomainIdentity { if self.token == TokenType::Json { return ("eql_v3", "query_json".to_string()); } - let bare = self - .domain - .value - .strip_prefix("eql_v3_") - .unwrap_or(&self.domain.value); + let bare = self.domain.value.trim_prefix("eql_v3_"); ("eql_v3", format!("query_{bare}")) } From fa408c8c823efcaf81ea38e439bb93f346b090d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 00:11:21 +0000 Subject: [PATCH 3/5] refactor: use Vec::from_fn Builds vectors of None for non-Clone element types with Vec::from_fn, stabilized in Rust 1.100, instead of mapping over a range or repeat_with/take and collecting. interleaved_indices becomes a closed form over the index, with a unit test pinning its order. Co-Authored-By: Claude Opus 5.5 --- .../src/common.rs | 31 ++++++++++--------- .../src/pipeline.rs | 2 +- .../src/postgresql/context/mod.rs | 4 +-- .../src/proxy/zerokms/zerokms.rs | 8 ++--- 4 files changed, 22 insertions(+), 23 deletions(-) diff --git a/packages/cipherstash-proxy-integration/src/common.rs b/packages/cipherstash-proxy-integration/src/common.rs index 685ced4c..34ab0803 100644 --- a/packages/cipherstash-proxy-integration/src/common.rs +++ b/packages/cipherstash-proxy-integration/src/common.rs @@ -588,21 +588,8 @@ where /// Returns indices in zigzag order so insertion is never accidentally sorted. /// For len=5: [4, 0, 3, 1, 2] pub fn interleaved_indices(len: usize) -> Vec { - let mut indices = Vec::with_capacity(len); - let mut lo = 0; - let mut hi = len; - let mut take_hi = true; - while lo < hi { - if take_hi { - hi -= 1; - indices.push(hi); - } else { - indices.push(lo); - lo += 1; - } - take_hi = !take_hi; - } - indices + // Even positions count down from the end, odd positions count up from 0. + Vec::from_fn(len, |i| if i % 2 == 0 { len - 1 - i / 2 } else { i / 2 }) } /// Asserts that `result` failed with a PostgreSQL `ErrorResponse` carrying @@ -709,3 +696,17 @@ impl ServerCertVerifier for DangerousTestCertVerifier { .supported_schemes() } } + +#[cfg(test)] +mod tests { + use super::interleaved_indices; + + #[test] + fn interleaved_indices_alternate_from_the_ends() { + assert_eq!(interleaved_indices(0), Vec::::new()); + assert_eq!(interleaved_indices(1), vec![0]); + assert_eq!(interleaved_indices(2), vec![1, 0]); + assert_eq!(interleaved_indices(5), vec![4, 0, 3, 1, 2]); + assert_eq!(interleaved_indices(6), vec![5, 0, 4, 1, 3, 2]); + } +} diff --git a/packages/cipherstash-proxy-integration/src/pipeline.rs b/packages/cipherstash-proxy-integration/src/pipeline.rs index 00877700..a0a8651a 100644 --- a/packages/cipherstash-proxy-integration/src/pipeline.rs +++ b/packages/cipherstash-proxy-integration/src/pipeline.rs @@ -190,7 +190,7 @@ mod tests { .iter() .map(|sql| Box::pin(client.simple_query(sql)) as Pending<'_>) .collect(); - let mut results = (0..pending.len()).map(|_| None).collect::>(); + let mut results = Vec::from_fn(pending.len(), |_| None); // Poll every query in order on each wake, so all requests are written // in order before any response arrives. diff --git a/packages/cipherstash-proxy/src/postgresql/context/mod.rs b/packages/cipherstash-proxy/src/postgresql/context/mod.rs index 44077828..3cda8a9a 100644 --- a/packages/cipherstash-proxy/src/postgresql/context/mod.rs +++ b/packages/cipherstash-proxy/src/postgresql/context/mod.rs @@ -1650,9 +1650,7 @@ where columns: &[Option], ) -> Result>, Error> { if plaintexts.iter().all(Option::is_none) { - return Ok(std::iter::repeat_with(|| None) - .take(plaintexts.len()) - .collect()); + return Ok(Vec::from_fn(plaintexts.len(), |_| None)); } let keyset_id = self.keyset_identifier()?; diff --git a/packages/cipherstash-proxy/src/proxy/zerokms/zerokms.rs b/packages/cipherstash-proxy/src/proxy/zerokms/zerokms.rs index ef9ea98f..013b406e 100644 --- a/packages/cipherstash-proxy/src/proxy/zerokms/zerokms.rs +++ b/packages/cipherstash-proxy/src/proxy/zerokms/zerokms.rs @@ -338,12 +338,12 @@ impl EncryptionService for ZeroKms { // If no plaintexts to encrypt, return all None. // - // Built by iteration rather than `vec![None; n]`: that needs `Clone`, - // and `EqlOutputV3` does not derive it (neither does the v2 + // Built with `Vec::from_fn` rather than `vec![None; n]`: that needs + // `Clone`, and `EqlOutputV3` does not derive it (neither does the v2 // `EqlOutput` — the ciphertext types are `Clone`, the output wrappers // are not). if prepared_plaintexts.is_empty() { - return Ok((0..plaintexts.len()).map(|_| None).collect()); + return Ok(Vec::from_fn(plaintexts.len(), |_| None)); } // Use default opts since cipher is already initialized with the correct keyset @@ -506,7 +506,7 @@ fn place_ciphertexts( } .into()); } - let mut result: Vec> = (0..len).map(|_| None).collect(); + let mut result: Vec> = Vec::from_fn(len, |_| None); for (idx, ciphertext) in indices.into_iter().zip(ciphertexts) { result[idx] = Some(ciphertext); } From 547fc966825ded9aed350d17fd98cb62572a9b24 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 00:12:57 +0000 Subject: [PATCH 4/5] refactor: use core::mem::DropGuard for cleanup guards Replaces the hand-rolled CancellationRegistrationGuard with core::mem::DropGuard, stabilized in Rust 1.100. Also uses a DropGuard for the active-connections gauge. It was decremented only after pg::handler returned, so a panicking handler, or a task dropped at shutdown, left the gauge permanently incremented. The guard decrements on every exit path; on the normal path it is dropped right after the handler returns, as before. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ packages/cipherstash-proxy/src/main.rs | 8 ++++- .../src/postgresql/driver.rs | 31 +++++++++---------- 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d966b22..ed07e517 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **Active connections metric**: `cipherstash_proxy_clients_active_connections` now goes down when a client connection ends because of a panic or because Proxy is shutting down. It previously went down only when the connection ended normally, so the gauge could drift upwards over time. + - **`--db-user`**: the flag now sets the database username. It previously set an unused variable, so it had no effect. - **Unknown column error message**: the type-checking error for a column a table does not have now names the column and the table the right way round, for example `Column: email not found for table: users`. It previously swapped them. diff --git a/packages/cipherstash-proxy/src/main.rs b/packages/cipherstash-proxy/src/main.rs index efb25a4c..9921f46f 100644 --- a/packages/cipherstash-proxy/src/main.rs +++ b/packages/cipherstash-proxy/src/main.rs @@ -7,6 +7,7 @@ use cipherstash_proxy::{cli, log, postgresql as pg, prometheus, Args}; use clap::Parser; use metrics::gauge; use std::io::IsTerminal; +use std::mem::DropGuard; use tokio::signal::unix::{signal, SignalKind}; use tokio_util::task::TaskTracker; use tracing::{error, info, warn}; @@ -112,9 +113,14 @@ fn main() -> Result<(), Box> { tracker.spawn(async move { gauge!(CLIENTS_ACTIVE_CONNECTIONS).increment(1); + // Decrements even if the handler panics or the task + // is dropped, so the gauge cannot drift upwards. + let active_connection = DropGuard::new((), |()| { + gauge!(CLIENTS_ACTIVE_CONNECTIONS).decrement(1); + }); let result = pg::handler(client_stream,context).await; - gauge!(CLIENTS_ACTIVE_CONNECTIONS).decrement(1); + drop(active_connection); match result { Ok(_) => (), diff --git a/packages/cipherstash-proxy/src/postgresql/driver.rs b/packages/cipherstash-proxy/src/postgresql/driver.rs index b5dfb440..e9420d1f 100644 --- a/packages/cipherstash-proxy/src/postgresql/driver.rs +++ b/packages/cipherstash-proxy/src/postgresql/driver.rs @@ -15,6 +15,7 @@ use pg_proto::{ }; use std::{ convert::Infallible, + mem::DropGuard, sync::{Arc, LazyLock}, }; use tokio::net::TcpStream; @@ -25,23 +26,20 @@ use tracing::info; static CANCELLATION_REGISTRY: LazyLock = LazyLock::new(InMemoryCancellationRegistry::default); -struct CancellationRegistrationGuard { +/// A session's cancellation key and the registry it is attached to. +type CancellationRegistration = (InMemoryCancellationRegistry, Option); + +/// Detaches a session's cancellation key from the registry when dropped, so a +/// closed session can no longer be cancelled through its old key. +fn cancellation_registration_guard( registry: InMemoryCancellationRegistry, key: Option, -} - -impl CancellationRegistrationGuard { - fn new(registry: InMemoryCancellationRegistry, key: Option) -> Self { - Self { registry, key } - } -} - -impl Drop for CancellationRegistrationGuard { - fn drop(&mut self) { - if let Some(key) = self.key.take() { - let _ = self.registry.detach(&key); +) -> DropGuard { + DropGuard::new((registry, key), |(registry, key)| { + if let Some(key) = key { + let _ = registry.detach(&key); } - } + }) } #[derive(Clone)] @@ -122,7 +120,7 @@ where pg_proto::IntermediaryAccept::Session(session) => session, pg_proto::IntermediaryAccept::CancellationForwarded => return Ok(()), }; - let _cancellation_guard = CancellationRegistrationGuard::new( + let _cancellation_guard = cancellation_registration_guard( CANCELLATION_REGISTRY.clone(), session.cancellation_key().cloned(), ); @@ -422,8 +420,7 @@ mod tests { ); { - let _guard = - CancellationRegistrationGuard::new(registry.clone(), Some(key.clone())); + let _guard = cancellation_registration_guard(registry.clone(), Some(key.clone())); let _ = result; } assert_eq!(registry.register(route), Ok(key)); From 9f52749cabf9d98c3c74bdc3a7952d669c8f1f64 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 00:23:25 +0000 Subject: [PATCH 5/5] docs: address review feedback on MSRV and gauge wording The gauge entry now claims only the panic case: a task dropped at shutdown happens as the process exits, so the metric is never scraped again. Splits a DEVELOPMENT.md line to one sentence per line. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- DEVELOPMENT.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed07e517..42be271a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,7 +47,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed -- **Active connections metric**: `cipherstash_proxy_clients_active_connections` now goes down when a client connection ends because of a panic or because Proxy is shutting down. It previously went down only when the connection ended normally, so the gauge could drift upwards over time. +- **Active connections metric**: `cipherstash_proxy_clients_active_connections` now goes down when a client connection's handler panics. It previously went down only when the handler returned, so a panic left the gauge permanently higher. - **`--db-user`**: the flag now sets the database username. It previously set an unused variable, so it had no effect. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 975340bf..94f665d5 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -149,7 +149,8 @@ CI uses three Rust toolchains: The MSRV build and stable lint jobs need no PostgreSQL or credentials. Locally, rustup selects the pinned toolchain automatically from `rust-toolchain.toml`. -The MSRV is 1.100.0 because Proxy uses standard library APIs stabilized in that release, such as `str::trim_prefix`, `Vec::from_fn` and `core::mem::DropGuard`. The MSRV and the pinned toolchain are currently the same version, so the two jobs differ only in what they run. +The MSRV is 1.100.0 because Proxy uses standard library APIs stabilized in that release, such as `str::trim_prefix`, `Vec::from_fn` and `core::mem::DropGuard`. +The MSRV and the pinned toolchain are currently the same version, so the two jobs differ only in what they run. To run those checks locally: