From bbda7d7bc0c76942d4d1eef84ef52c3c55e648bd Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 23:34:01 +0000 Subject: [PATCH 1/6] feat(proxy): allocator trial builds with jemalloc and mimalloc Add off-by-default Cargo features that swap Proxy's Rust global allocator on Linux for the allocator trial (CIP-5738, CIP-5739): `jemalloc` (prefixed), `jemalloc-unprefixed` (also replaces C malloc, with background threads) and `mimalloc`. Default builds keep glibc and gain no dependency. Proxy logs the allocator it uses at startup. `mise run burn-in:image` builds a variant for a Linux target and copies only the binary into a release image for the RSS rig. `build:binary` takes `--features`, can cross-compile between Linux architectures, and gives jemalloc 64 KiB pages on aarch64. CI builds and tests each allocator feature on both Linux targets. The rig's pooled-queries workload binds the salary at the width Proxy describes, since the EQL v3 example schema makes it bigint. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Q6HAPvwBTmnJX6YikJ9N8 --- .github/workflows/test.yml | 46 ++++ Cargo.lock | 56 ++++ mise.toml | 84 +++++- packages/cipherstash-proxy-burn-in/Cargo.toml | 1 + .../cipherstash-proxy-burn-in/src/client.rs | 139 ++++++++-- packages/cipherstash-proxy/Cargo.toml | 30 +++ packages/cipherstash-proxy/src/allocator.rs | 249 ++++++++++++++++++ packages/cipherstash-proxy/src/lib.rs | 1 + packages/cipherstash-proxy/src/main.rs | 15 ++ 9 files changed, 599 insertions(+), 22 deletions(-) create mode 100644 packages/cipherstash-proxy/src/allocator.rs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 109237192..f6108cdf6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -120,6 +120,52 @@ jobs: fi cargo build --locked --release --package cipherstash-proxy + # Allocator trial: the release binary builds with each allocator feature on + # both Linux targets, and the allocator and metrics tests pass with it. The + # aarch64 builds give jemalloc a 64 KiB page size, as `build:binary` does. + allocators: + name: Build (allocator ${{ matrix.allocator }}, ${{ matrix.target }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + env: + # Read only when building for aarch64, by tikv-jemalloc-sys. + AARCH64_UNKNOWN_LINUX_GNU_JEMALLOC_SYS_WITH_LG_PAGE: "16" + strategy: + fail-fast: false + matrix: + os: [blacksmith-16vcpu-ubuntu-2204, linux-arm64-public] + allocator: [jemalloc, jemalloc-unprefixed, mimalloc] + include: + - os: blacksmith-16vcpu-ubuntu-2204 + target: x86_64-unknown-linux-gnu + - os: linux-arm64-public + target: aarch64-unknown-linux-gnu + + steps: + - uses: actions/checkout@v7 + + - name: Install rust + shell: /bin/bash -l {0} + run: rustup toolchain install --no-self-update + + - name: Setup Rust cache + uses: Swatinem/rust-cache@v2 + with: + key: allocator-${{ matrix.allocator }} + + - uses: jdx/mise-action@v2 + with: + version: 2026.1.6 + install: false + + - name: Build the release binary + shell: /bin/bash -l {0} + run: mise run build:binary --target ${{ matrix.target }} --features ${{ matrix.allocator }} + + - name: Allocator and metrics tests + shell: /bin/bash -l {0} + run: cargo test --locked -p cipherstash-proxy --lib --features ${{ matrix.allocator }} -- allocator prometheus + # Latest stable: early warning that a new Rust release breaks the build or # adds Clippy lints, before the pinned toolchain is bumped to it. stable: diff --git a/Cargo.lock b/Cargo.lock index d3078f61d..2a7cdfcff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -856,9 +856,13 @@ dependencies = [ "eql-mapper", "exitcode", "hex", + "http-body-util", + "hyper", + "hyper-util", "md-5 0.10.6", "metrics", "metrics-exporter-prometheus", + "mimalloc", "moka", "pg-proto", "postgres-protocol", @@ -878,6 +882,8 @@ dependencies = [ "sqltk", "temp-env", "thiserror 2.0.18", + "tikv-jemalloc-ctl", + "tikv-jemallocator", "tokio", "tokio-postgres", "tokio-postgres-rustls", @@ -893,6 +899,7 @@ name = "cipherstash-proxy-burn-in" version = "0.1.0" dependencies = [ "anyhow", + "bytes", "clap", "serde", "serde_json", @@ -2690,6 +2697,15 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + [[package]] name = "libredox" version = "0.1.24" @@ -2863,6 +2879,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + [[package]] name = "mime" version = "0.3.17" @@ -4881,6 +4906,37 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tikv-jemalloc-ctl" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a184c43b8ab2f41df2733b55556e3f5f632f4aeaa205b1bb018f574b7f5f142" +dependencies = [ + "libc", + "paste", + "tikv-jemalloc-sys", +] + +[[package]] +name = "tikv-jemalloc-sys" +version = "0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a2825c78386b4ae0314074867860ba9577875de945f05992c38815cbec327f0" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "tikv-jemallocator" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "249f09e49ab1609436f34c776e84231bead18d6a955f119f939bdc1d847561bd" +dependencies = [ + "libc", + "tikv-jemalloc-sys", +] + [[package]] name = "time" version = "0.3.47" diff --git a/mise.toml b/mise.toml index 86c722a91..df67ca5bc 100644 --- a/mise.toml +++ b/mise.toml @@ -204,6 +204,61 @@ cargo run --locked -p cipherstash-proxy-burn-in -- \ --output target/burn-in/rss-idle-report.json """ +[tasks."burn-in:image"] +description = "Build a rig-ready Proxy image with a chosen allocator (glibc, jemalloc, jemalloc-unprefixed, mimalloc): a release image with only its binary replaced" +run = """ +#!/bin/bash +set -euo pipefail + +{% set default_target_arch = arch() | replace(from="arm64", to="aarch64") | replace(from="x64", to="x86_64") %} +{% set allocator = option(name="allocator", default="jemalloc") %} +{% set target = option(name="target", default=default_target_arch ~ "-unknown-linux-gnu") %} +{# The release image the binary replaces the Proxy binary of #} +{% set base = option(name="base", default="cipherstash/proxy:3.1.0") %} + +case "{{ allocator }}" in + glibc) features="" ;; + jemalloc|jemalloc-unprefixed|mimalloc) features="{{ allocator }}" ;; + *) + echo "error: unknown allocator '{{ allocator }}': expected glibc, jemalloc, jemalloc-unprefixed or mimalloc" + exit 2 + ;; +esac + +case "{{ target }}" in + x86_64-unknown-linux-gnu) platform="linux/amd64" ;; + aarch64-unknown-linux-gnu) platform="linux/arm64" ;; + *) + echo "error: unsupported target '{{ target }}': expected x86_64-unknown-linux-gnu or aarch64-unknown-linux-gnu" + exit 2 + ;; +esac + +if [[ -n "${features}" ]]; then + mise run build:binary --target {{ target }} --features "${features}" +else + mise run build:binary --target {{ target }} +fi + +# The build context holds only the binary, so nothing else in the base image changes. +context="$(mktemp -d)" +trap 'rm -rf "${context}"' EXIT +cp {{ config_root }}/target/{{ target }}/release/cipherstash-proxy "${context}/" + +tag="${RIG_IMAGE_TAG:-cipherstash-proxy-rig:{{ allocator }}-${platform#linux/}}" +docker build "${context}" \ + --tag "${tag}" \ + --platform "${platform}" \ + --label "org.cipherstash.proxy.allocator={{ allocator }}" \ + --label "org.cipherstash.proxy.base-image={{ base }}" \ + --file - < /dev/null; then + echo "error: cross-compiling to {{ target }} needs ${cross}-gcc and ${cross}-g++" + echo "error: on Debian or Ubuntu, install gcc-${target_arch//_/-}-linux-gnu and g++-${target_arch//_/-}-linux-gnu" + exit 1 + fi + target_env="$(echo "{{ target }}" | tr '[:lower:]-' '[:upper:]_')" + export "CARGO_TARGET_${target_env}_LINKER=${cross}-gcc" + export "CC_$(echo "{{ target }}" | tr '-' '_')=${cross}-gcc" + export "CXX_$(echo "{{ target }}" | tr '-' '_')=${cross}-g++" +fi +{% endif %} + +{# jemalloc fixes its page size when it is built. arm64 Linux kernels use 4, 16 #} +{# or 64 KiB pages, and a jemalloc built for 64 KiB pages runs on all three. #} +{# Only tikv-jemalloc-sys reads this, so builds without jemalloc are unchanged. #} +if [[ "{{ target }}" == aarch64-* ]]; then + export JEMALLOC_SYS_WITH_LG_PAGE="${JEMALLOC_SYS_WITH_LG_PAGE:-16}" +fi + # set a user agent if [[ -n "${GITHUB_REF_NAME}" ]]; then export BUILD_VERSION="${GITHUB_REF_NAME}" @@ -692,7 +774,7 @@ export CIPHERSTASH_CLIENT_SECONDARY_USER_AGENT="cipherstash-proxy/${BUILD_VERSIO rustup toolchain install --no-self-update rustup target add {{ target }} -cargo build --locked --target {{ target }} --release --package cipherstash-proxy +cargo build --locked --target {{ target }} --release --package cipherstash-proxy{% if features %} --features {{ features }}{% endif %} cp -v {{config_root}}/target/{{ target }}/release/cipherstash-proxy {{config_root}}/ """ diff --git a/packages/cipherstash-proxy-burn-in/Cargo.toml b/packages/cipherstash-proxy-burn-in/Cargo.toml index 29f4f2355..53f5691fe 100644 --- a/packages/cipherstash-proxy-burn-in/Cargo.toml +++ b/packages/cipherstash-proxy-burn-in/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] anyhow = "1" +bytes = "1" clap = { version = "4.5", features = ["derive", "env"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/packages/cipherstash-proxy-burn-in/src/client.rs b/packages/cipherstash-proxy-burn-in/src/client.rs index 599b21eb0..f82b29671 100644 --- a/packages/cipherstash-proxy-burn-in/src/client.rs +++ b/packages/cipherstash-proxy-burn-in/src/client.rs @@ -10,9 +10,12 @@ //! why the churn workloads stop at different points of the handshake. //! //! The pooled workload uses the `users` table that the image's entrypoint -//! installs with `CS_DATABASE__INSTALL_EXAMPLE_SCHEMA`. That table is the EQL -//! v2 fixture: `encrypted_email` and `encrypted_salary` are encrypted columns -//! with unique, match and ORE SEM terms. +//! installs with `CS_DATABASE__INSTALL_EXAMPLE_SCHEMA`, in which +//! `encrypted_email` and `encrypted_salary` are encrypted columns that support +//! equality and range queries. Proxy 2.2.x images install the EQL v2 fixture, +//! where the salary is an `int`. Proxy 3.x images install the EQL v3 fixture, +//! where it is `eql_v3_bigint_ord`, so the workload binds the salary at the +//! width Proxy describes. use std::{ net::SocketAddr, @@ -32,7 +35,10 @@ use tokio::{ task::JoinSet, time::{timeout, MissedTickBehavior}, }; -use tokio_postgres::{Client, NoTls}; +use tokio_postgres::{ + types::{to_sql_checked, IsNull, ToSql, Type}, + Client, NoTls, +}; /// Bounds one connect or one query, so a stalled Proxy shows up as errors /// rather than as a workload that silently stops. @@ -435,8 +441,8 @@ impl Row { format!("{}-{}-burn-in@example.com", self.cycle, self.connection) } - fn salary(&self) -> i32 { - 30_000 + i32::try_from(self.cycle % 100_000).unwrap_or_default() + fn salary(&self) -> i64 { + 30_000 + i64::try_from(self.cycle % 100_000).unwrap_or_default() } async fn step(&mut self, client: &Client) -> Result<()> { @@ -470,11 +476,13 @@ impl Row { match self.phase { 0 => { self.insert_sent = true; + let insert = client + .prepare("INSERT INTO users (encrypted_email, encrypted_salary) VALUES ($1, $2) RETURNING id") + .await + .context("prepare insert")?; + let salary = Salary::for_param(salary, &insert, 1)?; let inserted = client - .query_one( - "INSERT INTO users (encrypted_email, encrypted_salary) VALUES ($1, $2) RETURNING id", - &[&email, &salary], - ) + .query_one(&insert, &[&email, &salary]) .await .context("insert")?; self.id = Some(inserted.get(0)); @@ -490,9 +498,9 @@ impl Row { .context("select by email")?; // Proxy 2.2.5 can return other rows with similar emails, so the // check is that this connection's row is among them. - let found = rows - .iter() - .any(|row| row.get::<_, String>(1) == email && row.get::<_, i32>(2) == salary); + let found = rows.iter().any(|row| { + row.get::<_, String>(1) == email && read_salary(row, 2).ok() == Some(salary) + }); anyhow::ensure!( found, "select by email returned {} rows, none of which decrypts to ({email}, {salary})", @@ -500,21 +508,25 @@ impl Row { ); } 2 => { + let select = client + .prepare("SELECT id, encrypted_salary FROM users WHERE encrypted_salary >= $1 LIMIT 10") + .await + .context("prepare select by salary range")?; + let salary = Salary::for_param(salary, &select, 0)?; client - .query( - "SELECT id, encrypted_salary FROM users WHERE encrypted_salary >= $1 LIMIT 10", - &[&salary], - ) + .query(&select, &[&salary]) .await .context("select by salary range")?; } 3 => { let id = self.id.context("update without an inserted row")?; + let update = client + .prepare("UPDATE users SET encrypted_salary = $1 WHERE id = $2") + .await + .context("prepare update")?; + let salary = Salary::for_param(salary + 1, &update, 0)?; let updated = client - .execute( - "UPDATE users SET encrypted_salary = $1 WHERE id = $2", - &[&(salary + 1), &id], - ) + .execute(&update, &[&salary, &id]) .await .context("update")?; anyhow::ensure!(updated == 1, "update changed {updated} rows"); @@ -534,6 +546,61 @@ impl Row { } } +/// A salary bound at the integer width Proxy describes for its parameter: +/// `int4` for the EQL v2 example schema, `int8` for the EQL v3 one. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Salary { + Int4(i32), + Int8(i64), +} + +impl Salary { + fn for_type(value: i64, ty: &Type) -> Result { + match *ty { + Type::INT4 => Ok(Self::Int4(i32::try_from(value)?)), + Type::INT8 => Ok(Self::Int8(value)), + _ => anyhow::bail!("Proxy describes the salary parameter as {ty}, not an integer"), + } + } + + /// The salary for parameter `index` of a statement Proxy has described. + fn for_param(value: i64, statement: &tokio_postgres::Statement, index: usize) -> Result { + let ty = statement + .params() + .get(index) + .with_context(|| format!("statement has no parameter {}", index + 1))?; + Self::for_type(value, ty) + } +} + +impl ToSql for Salary { + fn to_sql( + &self, + ty: &Type, + out: &mut bytes::BytesMut, + ) -> Result> { + match self { + Self::Int4(value) => value.to_sql(ty, out), + Self::Int8(value) => value.to_sql(ty, out), + } + } + + fn accepts(ty: &Type) -> bool { + matches!(*ty, Type::INT4 | Type::INT8) + } + + to_sql_checked!(); +} + +/// Reads a salary column at whichever integer width Proxy returns it. +fn read_salary(row: &tokio_postgres::Row, index: usize) -> Result { + match row.columns().get(index).map(tokio_postgres::Column::type_) { + Some(&Type::INT4) => Ok(i64::from(row.try_get::<_, i32>(index)?)), + Some(&Type::INT8) => Ok(row.try_get::<_, i64>(index)?), + other => anyhow::bail!("salary column has type {other:?}, not an integer"), + } +} + #[cfg(test)] mod tests { use super::*; @@ -606,6 +673,36 @@ mod tests { assert_eq!(row.email(), "0-3-burn-in@example.com"); } + #[test] + fn a_salary_binds_as_the_integer_width_proxy_describes() { + // EQL v3 example schema: `encrypted_salary eql_v3_bigint_ord`. + assert_eq!( + Salary::for_type(30_001, &Type::INT8).unwrap(), + Salary::Int8(30_001) + ); + // EQL v2 example schema of Proxy 2.2.x: `cast_as` `int`. + assert_eq!( + Salary::for_type(30_001, &Type::INT4).unwrap(), + Salary::Int4(30_001) + ); + assert!(Salary::for_type(30_001, &Type::TEXT).is_err()); + } + + #[test] + fn a_salary_serialises_at_its_width() { + let mut buffer = bytes::BytesMut::new(); + Salary::Int8(30_001) + .to_sql_checked(&Type::INT8, &mut buffer) + .unwrap(); + assert_eq!(buffer.as_ref(), 30_001_i64.to_be_bytes()); + + let mut buffer = bytes::BytesMut::new(); + Salary::Int4(30_001) + .to_sql_checked(&Type::INT4, &mut buffer) + .unwrap(); + assert_eq!(buffer.as_ref(), 30_001_i32.to_be_bytes()); + } + #[test] fn held_connections_are_counted_while_open() { let counters = Counters::default(); diff --git a/packages/cipherstash-proxy/Cargo.toml b/packages/cipherstash-proxy/Cargo.toml index 8c620ade8..0d7428ccb 100644 --- a/packages/cipherstash-proxy/Cargo.toml +++ b/packages/cipherstash-proxy/Cargo.toml @@ -58,6 +58,36 @@ tracing-subscriber = { workspace = true } uuid = { version = "1.11.0", features = ["serde", "v4"] } vitaminc-protected = "0.1.0-pre4.2" +# Allocators for the allocator trial. Each is optional and Linux-only, so a +# default build stays on the system allocator (glibc) with no new dependency. +[target.'cfg(target_os = "linux")'.dependencies] +http-body-util = { version = "0.1", optional = true } +hyper = { version = "1", features = ["http1", "server"], optional = true } +hyper-util = { version = "0.1", features = ["tokio"], optional = true } +mimalloc = { version = "0.1", optional = true } +tikv-jemalloc-ctl = { version = "0.7", features = ["stats"], optional = true } +tikv-jemallocator = { version = "0.7", optional = true } + +[features] +default = [] +# jemalloc as the Rust global allocator, with prefixed symbols. C libraries +# such as aws-lc-sys keep calling glibc `malloc`. +jemalloc = [ + "dep:tikv-jemallocator", + "dep:tikv-jemalloc-ctl", + "dep:hyper", + "dep:hyper-util", + "dep:http-body-util", +] +# jemalloc that also replaces C `malloc`, with background purging threads. +jemalloc-unprefixed = [ + "jemalloc", + "tikv-jemallocator/unprefixed_malloc_on_supported_platforms", + "tikv-jemallocator/background_threads", +] +# mimalloc as the Rust global allocator. jemalloc wins if both are enabled. +mimalloc = ["dep:mimalloc"] + [dev-dependencies] proptest = "1.7" diff --git a/packages/cipherstash-proxy/src/allocator.rs b/packages/cipherstash-proxy/src/allocator.rs new file mode 100644 index 000000000..e464862fa --- /dev/null +++ b/packages/cipherstash-proxy/src/allocator.rs @@ -0,0 +1,249 @@ +//! The memory allocator this build of Proxy uses. +//! +//! Default builds use the system allocator, which is glibc `malloc` on the +//! Linux release targets. The allocator trial adds Cargo features that swap +//! the Rust global allocator on Linux: +//! +//! - `jemalloc`: jemalloc with prefixed symbols. Rust allocations go to +//! jemalloc, and C libraries that call `malloc` directly (`aws-lc-sys`, +//! `openssl-sys`) keep using glibc, so the process runs two heaps. +//! - `jemalloc-unprefixed`: jemalloc that also replaces C `malloc`, with +//! background purging threads on. +//! - `mimalloc`: mimalloc as the Rust global allocator. +//! +//! If more than one is enabled, as `cargo clippy --all-features` does, +//! `jemalloc-unprefixed` wins over `jemalloc`, which wins over `mimalloc`. +//! The startup log names the allocator the binary actually uses. + +#[cfg(all(target_os = "linux", feature = "jemalloc"))] +#[global_allocator] +static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; + +#[cfg(all(target_os = "linux", feature = "mimalloc", not(feature = "jemalloc")))] +#[global_allocator] +static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; + +// With both features on, as under `--all-features`, jemalloc wins and mimalloc +// is linked but unused. +#[cfg(all(target_os = "linux", feature = "mimalloc", feature = "jemalloc"))] +use mimalloc as _; + +/// An allocator Proxy can be built with. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Allocator { + /// The platform allocator: glibc `malloc` on Linux. + System, + /// jemalloc for Rust allocations only. + Jemalloc, + /// jemalloc for Rust allocations and C `malloc`. + JemallocUnprefixed, + /// mimalloc for Rust allocations only. + Mimalloc, +} + +impl Allocator { + /// The allocator this binary was built with. + pub const fn active() -> Self { + if cfg!(all(target_os = "linux", feature = "jemalloc-unprefixed")) { + Self::JemallocUnprefixed + } else if cfg!(all(target_os = "linux", feature = "jemalloc")) { + Self::Jemalloc + } else if cfg!(all(target_os = "linux", feature = "mimalloc")) { + Self::Mimalloc + } else { + Self::System + } + } + + /// The trial variant name, as the Cargo feature spells it. + pub const fn name(self) -> &'static str { + match self { + Self::System => system_allocator_name(), + Self::Jemalloc => "jemalloc", + Self::JemallocUnprefixed => "jemalloc-unprefixed", + Self::Mimalloc => "mimalloc", + } + } + + /// The allocator behind C `malloc`, which the C libraries Proxy links use. + pub const fn c_malloc(self) -> &'static str { + match self { + Self::JemallocUnprefixed => "jemalloc", + Self::System | Self::Jemalloc | Self::Mimalloc => system_allocator_name(), + } + } + + /// The environment variable that holds the allocator's runtime settings, + /// where it reads them from a single variable. + /// + /// Prefixed jemalloc reads `_RJEM_MALLOC_CONF`, not `MALLOC_CONF`. + /// mimalloc reads one `MIMALLOC_