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/CHANGELOG.md b/CHANGELOG.md index 1b458cee9..50be32159 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added + +- **Allocator startup log**: Proxy logs the memory allocator it uses at startup (`msg="Memory allocator"`), which is glibc for released builds. + Builds made with the opt-in `jemalloc`, `jemalloc-unprefixed` or `mimalloc` Cargo features use that allocator instead, for an allocator trial, and jemalloc builds also export jemalloc's memory counts as [Prometheus metrics](docs/reference/index.md#allocator-metrics-in-jemalloc-builds). + Released images do not change allocator. + ### Changed - **Connection timeout log level**: `Database connection timeout` is now logged at `info` level instead of `warn`. 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/docs/reference/index.md b/docs/reference/index.md index 71194ad09..923bc3225 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -600,6 +600,21 @@ If the proxy is running on a host other than localhost, access on that host. | `cipherstash_proxy_statements_total` | Counter | Total number of SQL statements processed by CipherStash Proxy | | `cipherstash_proxy_statements_unmappable_total` | Counter | Total number of unmappable SQL statements processed by CipherStash Proxy | +#### Allocator metrics in jemalloc builds + +Builds of Proxy made with the `jemalloc` or `jemalloc-unprefixed` Cargo feature also export jemalloc's own memory counts. +Released images and default builds use glibc and do not export them. +Proxy reads the counts afresh from jemalloc on each scrape. + +| Name | Target | Description | +|----------------------------------------------|--------|---------------------------------------------------------------------------------------------------| +| `cipherstash_proxy_jemalloc_allocated_bytes` | Gauge | Bytes in objects Proxy holds, as jemalloc counts them | +| `cipherstash_proxy_jemalloc_active_bytes` | Gauge | Bytes in jemalloc pages that hold objects | +| `cipherstash_proxy_jemalloc_resident_bytes` | Gauge | Bytes in resident pages jemalloc maps, including freed pages it has not returned | +| `cipherstash_proxy_jemalloc_retained_bytes` | Gauge | Bytes of virtual memory jemalloc keeps mapped after returning it to the operating system | + +With prefixed jemalloc (`jemalloc`), these count only Rust allocations: C libraries such as `aws-lc-sys` still allocate from glibc. + ## Troubleshooting ZeroKMS connections ### Recommended log settings 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/README.md b/packages/cipherstash-proxy-burn-in/README.md index 9ea8cd802..bb5716f81 100644 --- a/packages/cipherstash-proxy-burn-in/README.md +++ b/packages/cipherstash-proxy-burn-in/README.md @@ -97,6 +97,12 @@ Pass `--proxy-env NAME=VALUE` to add environment to Proxy, for example `MALLOC_A Pass `--scrape-interval-seconds` to enable Proxy's Prometheus exporter and scrape it from a separate container on the rig network. The scraper reuses the Proxy image for its `curl`, with the entrypoint replaced, and logs one HTTP status per scrape. The report then adds `prometheus_scrapes` to the run and `bytes_per_scrape` to each growth figure, and the run fails if no scrape succeeds after warm-up. + +A jemalloc build of Proxy also exports jemalloc's allocated, active, resident and retained bytes, read on each scrape. +After each successful scrape the scraper logs every `cipherstash_proxy_jemalloc_*` line as ` ` in `scraper.log`, which holds the full series. +The report adds a `jemalloc` section to the run with the number of scrapes, the values at the last scrape and the peak of each gauge. +`allocated` is what Proxy still holds, so `resident` minus `allocated` is memory jemalloc keeps after Proxy frees it, and `retained` is address space jemalloc has already returned to the operating system. +Builds without jemalloc export none of these gauges, and their runs have no `jemalloc` section. For the exporter enabled but never scraped, pass `--proxy-env CS_PROMETHEUS__ENABLED=true` instead. ### Client workloads @@ -113,7 +119,8 @@ The rig process is the client, and reaches Proxy through a port Docker publishes | `pooled-queries` | Keeps the connection open and runs an insert, two selects, an update and a delete over the example `users` table. | query | Proxy 2.2.5 opens its PostgreSQL connection as soon as it accepts a client's TCP connection, so even `tcp-probe` costs Proxy a TLS connect to the database. -`pooled-queries` reads and writes `encrypted_email` and `encrypted_salary`, which the image's example schema configures as EQL v2 encrypted columns, and checks that each row decrypts to what was inserted. +`pooled-queries` reads and writes `encrypted_email` and `encrypted_salary`, which the image's example schema configures as encrypted columns, and checks that each row decrypts to what was inserted. +Proxy 2.2.x images install the EQL v2 schema, where the salary is an `int`, and Proxy 3.x images install the EQL v3 schema, where it is `eql_v3_bigint_ord`, so the workload binds the salary at the integer width Proxy describes. A pooled connection that fails is replaced, so read `errors_total` before reading its slope: a run with errors is partly a `login-churn` run. `--client-interval-millis` (default 1000) is the period of each loop, and `--client-connections` (default 1) is the number of concurrent loops, which is the pool size for `idle-pool` and `pooled-queries`. @@ -148,6 +155,60 @@ COPY cipherstash-proxy /usr/local/bin/cipherstash-proxy The report records the image identifier and the version the binary prints, so the two runs cannot be confused. +`mise run burn-in:image` builds such an image from the current checkout, as the next section describes. + +### Allocator variants + +The allocator trial compares five variants of Proxy, all built from one commit. +`mise run burn-in:image` builds Proxy for a Linux target with the allocator chosen by `--allocator`, then copies only the binary into a release image (`--base`, default `cipherstash/proxy:3.1.0`), and prints the tag to pass to `--image`. + +| Variant | Build | Run | +|---|---|---| +| glibc | `mise run burn-in:image --allocator glibc` | as built | +| glibc, two arenas | the glibc image | add `--proxy-env MALLOC_ARENA_MAX=2` | +| jemalloc | `mise run burn-in:image --allocator jemalloc` | as built | +| jemalloc replacing C `malloc` | `mise run burn-in:image --allocator jemalloc-unprefixed` | as built | +| mimalloc | `mise run burn-in:image --allocator mimalloc` | as built | + +The default tag is `cipherstash-proxy-rig:-`, and `RIG_IMAGE_TAG` overrides it. +For example, to build and measure the jemalloc variant on the host's architecture: + +```bash +mise run burn-in:image --allocator jemalloc +cargo run -p cipherstash-proxy-burn-in -- rss-idle --name jemalloc \ + --image cipherstash-proxy-rig:jemalloc-amd64 --duration-seconds 600 +``` + +`--target` chooses `x86_64-unknown-linux-gnu` or `aarch64-unknown-linux-gnu`, and defaults to the host's architecture. +Measure each image on a host of its own architecture, as [Measuring on another host](#measuring-on-another-host) explains. +Cross-compiling from Linux needs the target's GNU toolchain, for example `gcc-aarch64-linux-gnu` and `g++-aarch64-linux-gnu` on Debian or Ubuntu. +`build:binary` gives jemalloc a 64 KiB page size for aarch64 (`JEMALLOC_SYS_WITH_LG_PAGE=16`), so the binary runs on kernels with 4, 16 or 64 KiB pages. + +The variants differ as follows: + +- `jemalloc` makes jemalloc the Rust global allocator with prefixed symbols. + C libraries that call `malloc` directly, such as `aws-lc-sys` for rustls and `openssl-sys`, keep using glibc, so the process has two heaps. +- `jemalloc-unprefixed` makes jemalloc replace C `malloc` as well, and turns on jemalloc's background purging threads (`background_thread:true`). +- `mimalloc` makes mimalloc the Rust global allocator. + C libraries keep using glibc. + +Each build logs its allocator at startup, and the rig records it in the run's `allocator` section: + +```text +INFO cipherstash_proxy: msg="Memory allocator" allocator="jemalloc-unprefixed" c_malloc="jemalloc" version="5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8" runtime_settings_env="MALLOC_CONF" +``` + +`c_malloc` names the allocator behind C `malloc`. +Pass allocator runtime settings to Proxy with `--proxy-env`: + +- prefixed jemalloc reads `_RJEM_MALLOC_CONF`, not `MALLOC_CONF`, for example `--proxy-env _RJEM_MALLOC_CONF=dirty_decay_ms:1000`; +- `jemalloc-unprefixed` reads `MALLOC_CONF`; +- mimalloc reads one `MIMALLOC_