Skip to content

The only tool you need to know what is happening and how to fix it.

benchmarks progress

dduxcc0d68d4b621
diff --git a/.github/workflows/benchmark-hardware.yml b/.github/workflows/benchmark-hardware.yml
index e8f5974d..945db4ef 100644
--- a/.github/workflows/benchmark-hardware.yml
+++ b/.github/workflows/benchmark-hardware.yml
@@ -10,9 +10,21 @@ on:
required: true
default: 'ccx13,ccx23,ccx33'
modes:
- description: 'Comma-separated DB modes (sqlite,pgch)'
+ description: 'Comma-separated DB modes (sqlite,pgch,managed-ch). managed-ch points at an external ClickHouse and requires the BENCH_CH_* repository secrets.'
required: true
default: 'sqlite,pgch'
+ signals:
+ description: 'Comma-separated OTLP signals to benchmark (spans,metrics,logs). Each is a separate fresh VM pair.'
+ required: true
+ default: 'spans,metrics,logs'
+ scenario:
+ description: 'Benchmark scenario: throughput (two-phase ingest ramp, default) or read-probe (ingest to fill levels, probe a read, fail above 5s).'
+ required: true
+ type: choice
+ options:
+ - throughput
+ - read-probe
+ default: 'throughput'
duration:
description: 'Per-matrix-entry loadgen duration (e.g. 30m, 5m)'
required: true
@@ -41,10 +53,18 @@ jobs:
set -euo pipefail
tiers="${{ github.event.inputs.tiers }}"
modes="${{ github.event.inputs.modes }}"
+ signals="${{ github.event.inputs.signals }}"
jq -nc \
--arg tiers "${tiers}" \
--arg modes "${modes}" \
- '{include: [($tiers | split(",")) as $T | ($modes | split(",")) as $M | $T[] as $t | $M[] as $m | {tier: $t, mode: $m}]}' \
+ --arg signals "${signals}" \
+ '{include: [
+ ($tiers | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(. != ""))) as $T |
+ ($modes | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(. != ""))) as $M |
+ ($signals | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(. != ""))) as $S |
+ $T[] as $t | $M[] as $m | $S[] as $s |
+ {tier: $t, mode: $m, signal: $s}
+ ]}' \
> matrix.json
cat matrix.json
echo "matrix=$(cat matrix.json)" >> "$GITHUB_OUTPUT"
@@ -62,6 +82,15 @@ jobs:
env:
HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN }}
BENCH_LOCATION: ${{ github.event.inputs.location }}
+ BENCH_SCENARIO: ${{ github.event.inputs.scenario }}
+ # Managed-ClickHouse credentials. Used only when modes contains
+ # managed-ch; empty for sqlite/pgch entries (harmless — sut-bootstrap
+ # only validates them when MODE=managed-ch).
+ CLICKHOUSE_SERVER: ${{ secrets.BENCH_CH_SERVER }}
+ CLICKHOUSE_USERNAME: ${{ secrets.BENCH_CH_USERNAME }}
+ CLICKHOUSE_PASSWORD: ${{ secrets.BENCH_CH_PASSWORD }}
+ CLICKHOUSE_DATABASE: ${{ secrets.BENCH_CH_DATABASE }}
+ BENCH_CH_HTTPS_PORT: ${{ secrets.BENCH_CH_HTTPS_PORT }}
steps:
- uses: actions/checkout@v4
@@ -85,15 +114,17 @@ jobs:
go-version: '1.25'
- name: Preflight
+ env:
+ BENCH_MODES_PLAN: ${{ matrix.mode }}
run: ./benchmarks/scripts/preflight.sh
- - name: Run matrix entry (${{ matrix.tier }} / ${{ matrix.mode }})
- run: ./benchmarks/scripts/run-matrix-entry.sh "${{ matrix.tier }}" "${{ matrix.mode }}" "${{ github.event.inputs.duration }}" benchmarks/results/_artifact
+ - name: Run matrix entry (${{ matrix.tier }} / ${{ matrix.mode }} / ${{ matrix.signal }})
+ run: ./benchmarks/scripts/run-matrix-entry.sh "${{ matrix.tier }}" "${{ matrix.mode }}" "${{ matrix.signal }}" "${{ github.event.inputs.duration }}" benchmarks/results/_artifact
- uses: actions/upload-artifact@v4
if: always()
with:
- name: result-${{ matrix.tier }}-${{ matrix.mode }}
+ name: result-${{ matrix.tier }}-${{ matrix.mode }}-${{ matrix.signal }}
path: benchmarks/results/_artifact/*.json
if-no-files-found: warn
diff --git a/benchmarks/LOCAL.md b/benchmarks/LOCAL.md
index 64fe6f75..04c29a99 100644
--- a/benchmarks/LOCAL.md
+++ b/benchmarks/LOCAL.md
@@ -42,22 +42,42 @@ The rest of this doc assumes option B, so swap `/tmp/bench-venv` for
## Pick a backend mode
-Two compose stacks, each pinned to one of the project's existing Dockerfiles:
+Three compose stacks, each pinned to one of the project's existing Dockerfiles:
| Mode | Compose file | Image | What it tests |
|------|--------------|-------|---------------|
| `sqlite` | `benchmarks/compose/docker-compose.sqlite.yml` | `Dockerfile.sqlite` | Single-binary backend with embedded SQLite. Fast to bring up, lower ceiling. |
| `pgch` | `benchmarks/compose/docker-compose.pgch.yml` | `Dockerfile.minimal` + clickhouse + postgres | Full prod-shape stack. Slower first build, much higher ceiling. |
+| `managed-ch` | `benchmarks/compose/docker-compose.managed-ch.yml` | `Dockerfile.minimal` + postgres (CH is external) | Same `Dockerfile.minimal` as pgch but pointed at an external managed ClickHouse via env vars. |
-Both expose port **8087** on the host (override with `BENCH_PORT=8088 docker
+All expose port **8087** on the host (override with `BENCH_PORT=8088 docker
compose -f ... up`).
First-time builds:
- `sqlite` mode: ~3–6 min (npm install + Go build).
- `pgch` mode: ~6–10 min (above + ClickHouse + Postgres image pulls).
+- `managed-ch` mode: ~3–5 min (same as pgch without the CH pull).
Subsequent runs reuse the Docker layer cache and start in seconds.
+### Extra setup for `managed-ch`
+
+Before running `--mode managed-ch`, export the ClickHouse credentials in your
+shell (preflight will fail loudly if they're missing):
+
+```bash
+export CLICKHOUSE_SERVER='your-cluster.region.aws.clickhouse.cloud:9440'
+export CLICKHOUSE_USERNAME='bench'
+export CLICKHOUSE_PASSWORD='••••••'
+# Optional:
+export CLICKHOUSE_DATABASE='traceway' # default: traceway
+export BENCH_CH_HTTPS_PORT='8443' # default: 8443 (CH Cloud); some hosts 8123
+```
+
+The orchestrator wipes (`DROP DATABASE IF EXISTS` + `CREATE DATABASE`) the
+configured database before each matrix entry — **use a dedicated database**
+or other tables in the same DB will be lost.
+
---
## The 6-step run
@@ -94,69 +114,90 @@ If this loops for more than ~3 min, something is wrong. Inspect:
docker compose -f benchmarks/compose/docker-compose.sqlite.yml logs --tail=80 traceway
```
-### 3. Register a fresh user + project; capture creds
+### 3. Register a fresh user + project; capture the project token
```bash
eval "$(benchmarks/scripts/seed-project.sh http://localhost:8087 \
- | jq -r '"export JWT=\(.jwt) PROJECT_TOKEN=\(.projectToken) PROJECT_ID=\(.projectId)"')"
-echo "PROJECT_ID=$PROJECT_ID"
+ | jq -r '"export PROJECT_TOKEN=\(.projectToken)"')"
+echo "PROJECT_TOKEN=$PROJECT_TOKEN"
```
`seed-project.sh` hits `/api/register`. On self-hosted backends only one
-organization is allowed, so this only works on a **fresh** DB — step 1's `down
--v` is what guarantees that.
+organization is allowed, so this only works on a **fresh** DB — step 1's
+`down -v` is what guarantees that. The OTLP-only loadgen no longer needs the
+JWT or project ID, so we extract only the project token.
-### 4. Run the loadgen
+### 4. Build and run the loadgen, one signal at a time
-Pick numbers appropriate for the mode you booted in step 1:
+```bash
+(cd benchmarks/loadgen && go build -o loadgen .)
+mkdir -p /tmp/bench-localhost && rm -f /tmp/bench-localhost/*.json
+```
+
+Pick numbers appropriate for the mode you booted in step 1. The two-phase
+ramp first grows batch size at a fixed low request rate, then grows request
+rate at the winning batch size.
-**SQLite (laptop):**
+**SQLite (laptop) — quick smoke per signal:**
```bash
-mkdir -p /tmp/bench-localhost && rm -f /tmp/bench-localhost/*.json
-benchmarks/loadgen/loadgen \
- --target http://localhost:8087 \
- --token "$PROJECT_TOKEN" --jwt "$JWT" --project-id "$PROJECT_ID" \
- --duration 5m --step-duration 45s \
- --initial-eps 100 --max-eps 800 \
- --report-out /tmp/bench-localhost/local-sqlite.json \
- --tier local --mode sqlite
+for sig in spans metrics logs; do
+ benchmarks/loadgen/loadgen \
+ --target http://localhost:8087 \
+ --token "$PROJECT_TOKEN" \
+ --signal "$sig" \
+ --duration 5m --step-duration 30s \
+ --phase1-batch-sizes 256,1024,4096 \
+ --phase2-request-rates 1,5,20 \
+ --report-out "/tmp/bench-localhost/local-sqlite-${sig}.json" \
+ --tier local --mode sqlite
+done
```
**pgch (laptop):**
```bash
-benchmarks/loadgen/loadgen \
- --target http://localhost:8087 \
- --token "$PROJECT_TOKEN" --jwt "$JWT" --project-id "$PROJECT_ID" \
- --duration 5m --step-duration 45s \
- --initial-eps 500 --max-eps 4000 \
- --report-out /tmp/bench-localhost/local-pgch.json \
- --tier local --mode pgch
+for sig in spans metrics logs; do
+ benchmarks/loadgen/loadgen \
+ --target http://localhost:8087 \
+ --token "$PROJECT_TOKEN" \
+ --signal "$sig" \
+ --duration 8m --step-duration 45s \
+ --phase1-batch-sizes 256,1024,4096,8192 \
+ --phase2-request-rates 1,5,20,50 \
+ --report-out "/tmp/bench-localhost/local-pgch-${sig}.json" \
+ --tier local --mode pgch
+done
```
-On stderr you'll see one line per step like:
+On stderr you'll see two-phase progress like:
```
-step 1: target=300 actual=306 ingest_p99=92ms ingest_err=0.00% passed=true
-step 2: target=600 actual=600 ingest_p99=17ms ingest_err=0.00% passed=false read endpoint "endpoints_grouped" p99 = 3268ms > 3000ms threshold
-wrote /tmp/bench-localhost/local-sqlite.json: max sustainable EPS = 306 (2 step(s))
+phase1 step 1: batch=256 rate=5.0 items/s=1280 p99=12ms err=0.00% passed=true
+phase1 step 2: batch=1024 rate=5.0 items/s=5120 p99=18ms err=0.00% passed=true
+phase1 step 3: batch=4096 rate=5.0 items/s=20480 p99=42ms err=0.00% passed=true
+phase2 step 1: batch=4096 rate=1.0 items/s=4096 p99=15ms err=0.00% passed=true
+phase2 step 2: batch=4096 rate=5.0 items/s=20480 p99=21ms err=0.00% passed=true
+phase2 step 3: batch=4096 rate=20.0 items/s=81920 p99=180ms err=0.00% passed=true
+wrote /tmp/bench-localhost/local-sqlite-spans.json: signal=spans max sustainable spans/sec = 81920
```
-The run finishes when either (a) a step fails the breaking-point check, (b)
-`--max-eps` is exceeded, or (c) `--duration` expires.
+A run finishes when either (a) a step fails the error threshold, (b) all
+configured steps pass, or (c) `--duration` expires.
-### 5. Render the chart + summary
+### 5. Render the charts + summary
```bash
.venv-bench/bin/python benchmarks/scripts/chart.py /tmp/bench-localhost/
-open /tmp/bench-localhost/chart.png
-open /tmp/bench-localhost/chart-detail.png
+open /tmp/bench-localhost/chart-spans.png
+open /tmp/bench-localhost/chart-metrics.png
+open /tmp/bench-localhost/chart-logs.png
cat /tmp/bench-localhost/summary.md
```
A one-entry result renders fine; it just won't have multiple bars/lines to
-compare against.
+compare against. Old pre-OTLP-split JSONs (without a `signal` field) are
+skipped with a log line.
### 6. Tear down
@@ -170,127 +211,68 @@ The `-v` deletes the named volume so the next run is guaranteed clean.
## Reading the output
-Each step record in the JSON looks like:
+Each result JSON has two phases:
```json
{
- "step": 1,
- "targetEps": 300, // Synthetic event units the ramp asked for. NOT requests/sec — see "What an EPS is" below.
- "actualEps": 306.6, // What the loadgen actually pushed on the wire (same unit).
- "ingest": { // Latency/errors for /api/report + OTLP combined
- "p50": 3.8, "p95": 12.5, "p99": 92.3,
- "ok": 1380, "errors": 0, "errRate": 0
+ "tier": "local", "mode": "sqlite", "signal": "spans",
+ "startedAt": "2026-05-15T...", "endedAt": "...",
+ "phase1": {
+ "kind": "batch-size-ramp",
+ "fixedRequestRate": 5,
+ "steps": [
+ {
+ "step": 1, "batchSize": 256, "requestRate": 5,
+ "attemptedItemsPerSec": 1280, "actualItemsPerSec": 1280, "rejected": 0,
+ "ingest": { "p50": 8, "p95": 14, "p99": 22, "ok": 150, "errors": 0, "errRate": 0 },
+ "passed": true
+ }
+ ],
+ "maxBatchSize": 8192
},
- "reads": { // Per dashboard read endpoint
- "endpoints_grouped": { "p50": 1120, "p95": 1462, "p99": 1509, "ok": 36, ... },
- "dashboard_overview": { ... },
- "exceptions_grouped": { ... },
- "logs": { ... },
- "session_recording": { ... }
+ "phase2": {
+ "kind": "request-rate-ramp",
+ "fixedBatchSize": 8192,
+ "steps": [ ... ],
+ "maxRequestRate": 100
},
- "passed": true,
- "failReason": "" // populated when passed=false
+ "maxSustainableItemsPerSec": 819200
}
```
-**A step passes** when *all three* hold:
-1. Ingest error rate ≤ 5% (5xx, timeouts).
-2. Every read endpoint p99 < 3000 ms.
-3. SUT was reachable for the whole step.
-
-`maxSustainableEps` in the JSON is the `actualEps` of the **last passing
-step** — that's the headline number for this configuration.
+**A step passes** when the combined error rate (HTTP failures + OTLP
+`PartialSuccess` rejected items) is ≤ `--ingest-err-threshold` (default 5%).
+Read endpoints are not probed in this benchmark.
-If `target` and `actual` diverge a lot on a passing step, the backend is
-already saturated even though it's not erroring yet. The next step usually
-fails.
-
-If reads degrade before ingest, that's expected: aggregation reads
-(`endpoints_grouped`, `dashboard_overview`) compete with write locks/IO and
-will be the first to cliff on SQLite. Point lookups (`logs`,
-`session_recording`, `exceptions_grouped`) typically stay fast right up until
-the SUT gives up.
+`maxSustainableItemsPerSec = phase2.fixedBatchSize × phase2.maxRequestRate`,
+where `maxRequestRate` is the rate of the last passing Phase 2 step.
---
-## What an EPS is (and isn't)
+## What an "item" is
-`EPS` in the loadgen is **synthetic event units**, not requests/sec and not
-DB rows/sec. The conversion:
+Each signal counts a different unit:
-```
-requests/sec = EPS / 10 # because tracesPerFrame = 10
-```
-
-So `--max-eps 800` actually means "push up to 80 HTTP requests/sec." The
-factor-of-10 fudge keeps the rate-limiter math clean (each `/api/report`
-frame carries 10 traces; the loadgen counts EPS as traces).
-
-### What goes in each request
-
-Each "frame" the loadgen sends is one HTTP POST, routed by `--report-share`
-(default 0.7 → 70 % go to `/api/report`, 30 % to OTLP).
-
-**`/api/report` frame** — gzipped JSON, built by `buildFrame()` in
-`benchmarks/loadgen/report.go`:
-
-| Field | Count per request | Notes |
-|---|---|---|
-| `traces` | **10 (fixed)** | One row per `transactions` |
-| `spans` (nested in traces) | **20–50** (each trace gets 2–5) | Random duration 1–200 ms, name from `{db.query, http.call, cache.get, render, json.encode}` |
-| `metrics` | **5 (fixed)** | `bench.metric.{cpu,mem,qps,lat,errs}`, random value 0–100 |
-| `sessions` | 0 / 1 — 5 % with recording, 16 % session-only | Random uuid + StartedAt |
-| `sessionRecordings` | 0 / 1 — 5 % chance | ~100 KB synthetic rrweb-shaped blob |
-| `stackTraces` | 0 / 1 — 2 % chance | Hardcoded short stack trace |
-
-Trace fields: random endpoint from a fixed 13-item list (`GET /api/users`,
-`POST /api/orders`, `GET /api/products/:id`, …), duration 10–1000 ms, random
-status code, body size 200–8200 bytes.
-
-**OTLP frame** — protobuf, built by `sendOTLPTraces()` in
-`benchmarks/loadgen/otlp.go`:
-
-| Field | Count per request | Notes |
+| Signal | Unit | OTLP request |
|---|---|---|
-| `spans` | **20 (fixed, `otlpSpansPerRequest`)** | Random 16-byte traceId + 8-byte spanId, http.method=GET, status code, route from the same 13-endpoint pool |
-
-No metrics, sessions, or exceptions on this path.
-
-### Row growth per second at 400 EPS
+| `spans` | one span (one row in `spans` / one trace fan-out) | `POST /api/otel/v1/traces` with `ExportTraceServiceRequest` |
+| `metrics` | one Gauge data point (one row in `metric_points`) | `POST /api/otel/v1/metrics` with `ExportMetricsServiceRequest` |
+| `logs` | one `LogRecord` (one row in `log_records`) | `POST /api/otel/v1/logs` with `ExportLogsServiceRequest` |
-At 400 EPS the loadgen fires **40 requests/sec total**: ~28 to `/api/report`,
-~12 to OTLP. That fans out into:
-
-| Table | Rows/sec |
-|---|---|
-| `transactions` | ~280 (28 × 10) |
-| `spans` (from `/api/report`) | ~980 (28 × ~35) |
-| `spans` (from OTLP) | ~240 (12 × 20) |
-| `metric_points` | ~140 (28 × 5) |
-| `sessions` | ~6 (28 × 21 %) |
-| `session_recordings` | ~1.4 (28 × 5 %) |
-| `exception_stack_traces` | ~0.56 (28 × 2 %) |
-
-So **"400 EPS" ≈ 1,500 rows/sec** across the database, not 400. Keep this
-mapping in mind when comparing the chart's headline number to your real
-workload.
+All bodies are protobuf, gzipped. The loadgen is OTLP-only — no `/api/report`.
### Data variety
Everything is uniform random within bounded ranges — deliberately flat:
-- 13 distinct endpoint paths → `GROUP BY endpoint` aggregations always
- produce ~13 groups
-- 5 span names, 5 metric names
-- All UUIDs are fresh per record (no hash clustering)
-- Durations: uniform 10–1000 ms → percentile queries hit a smooth
- distribution
-- No diurnal traffic, no power-law endpoint skew, no correlated bursts
+- **Spans:** 13 endpoint paths, status codes 200/201/404/500, durations 10–1000 ms
+- **Metrics:** 10 metric names (`bench.metric.{cpu,mem,qps,lat,errs,disk,net,heap,gc,fd}`), Gauge type, low-cardinality `host` attr
+- **Logs:** severity INFO/WARN/ERROR (weighted toward INFO), random 120-char body, 5 attrs incl. synthetic trace_id
-This isolates the backend's raw throughput from traffic-shape noise. It is
-**not** representative of real production telemetry; don't read the numbers
-as "this is what users will experience" — they're "this is the floor the
-backend can sustain on synthetic, evenly-distributed load."
+This isolates raw throughput from traffic-shape noise. It is **not**
+representative of real production telemetry; don't read the numbers as "this
+is what users will experience" — they're "this is the floor the backend can
+sustain on synthetic, evenly-distributed load."
---
@@ -298,18 +280,18 @@ backend can sustain on synthetic, evenly-distributed load."
| Flag | Default | When to change |
|------|---------|----------------|
-| `--initial-eps` | 100 | Raise close to the expected ceiling so you don't waste the first few steps far below saturation. |
-| `--max-eps` | 50000 | Lower it to bound runtime; raise to find the ceiling on a beefier box. |
-| `--step-duration` | 2m | Shorten for smoke checks (45s), keep at 2m for real measurements. |
+| `--signal` | (required) | One of `spans`, `metrics`, `logs`. |
+| `--phase1-batch-sizes` | `256,1024,4096,8192,16384` | Drop the lower steps on beefy boxes to save time; raise the cap to find the per-request decode/insert ceiling. |
+| `--phase2-request-rates` | `1,5,25,100,400` | Raise the cap to find the request-rate ceiling on big boxes; lower for cheap smoke tests. |
+| `--phase1-fixed-rate` | 5 | Per-second request rate held constant during Phase 1. Small enough that batch size is the only variable. |
+| `--phase2-batch-cap` | 8192 | Cap on Phase 2 batch size (matches OTel collector default `send_batch_size`). Phase 2 uses `min(this, Phase 1 winner)`. |
+| `--step-duration` | 2m | Shorten for smoke checks (15–30s), keep at 2m for real measurements. |
| `--duration` | 30m | Hard cap on total wall time. |
-| `--report-share` | 0.7 | Fraction of ingest sent via `/api/report` vs OTLP. Lower it to test OTLP-heavy workloads. |
-| `--read-rps` | 1 | Read traffic per endpoint per second. Raise to model a busier dashboard. |
-| `--ingest-err-threshold` | 0.05 | Allowed ingest error rate before a step fails. |
-| `--read-p99-threshold-ms` | 3000 | The dashboard latency budget. |
+| `--ingest-err-threshold` | 0.05 | Combined HTTP error + OTLP rejected rate that fails a step. |
-The ramp doubles target each step (100→200→400→800→…), so the cliff
-resolution is coarse by design — for a precise number, run a second pass with
-`--initial-eps` set near the known cliff and shorter steps.
+The ramp is geometric (256 → 1024 → 4096 → …), so cliff resolution is coarse
+by design — for a precise number, run a second pass with a narrower band of
+values around the known cliff.
---
@@ -319,11 +301,9 @@ resolution is coarse by design — for a precise number, run a second pass with
Previous run was killed mid-write and the SQLite WAL didn't recover. Run
step 1 again with `down -v`.
-- **`actual` is ~10× lower than `target` on every step.**
- You're running an older loadgen binary. Rebuild:
- ```bash
- (cd benchmarks/loadgen && go build -o loadgen .)
- ```
+- **`actualItemsPerSec` is much lower than `batchSize × requestRate`.**
+ Items are being dropped — either HTTP failures or OTLP `PartialSuccess`
+ rejections. Check `rejected` and `ingest.errors` for the culprit.
- **`seed-project.sh` returns `409 Conflict: organization already exists`.**
The DB isn't fresh — go back to step 1 with `down -v`.
@@ -349,11 +329,14 @@ Once the local run works end-to-end, move to the Hetzner ladder:
# Validate Hetzner credentials, no money spent
./benchmarks/scripts/run-local.sh --dry-run
-# ~5 min, ~€0.02 — one tier, one mode, on real Hetzner
+# ~5 min, ~€0.02 — one tier, one mode, one signal, on real Hetzner
./benchmarks/scripts/run-local.sh --smoke
-# Full matrix — 4 tiers x 2 modes, ~1 h, ~€1.20
+# Full matrix — 4 tiers x 2 modes x 3 signals, ~3 h, ~€3.60
./benchmarks/scripts/run-local.sh
+
+# Subset: one signal only across all tiers/modes
+./benchmarks/scripts/run-local.sh --signal spans
```
Prereqs and detail in [README.md](./README.md). The same `run-matrix-entry.sh`
diff --git a/benchmarks/README.md b/benchmarks/README.md
index f6cd550d..a289a80e 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -1,21 +1,28 @@
# benchmarks/
-Hardware-vs-breaking-point benchmark for the Traceway backend. Provisions
-Hetzner Cloud servers, hammers the backend with realistic ingest while
-measuring read latency, and produces a chart of sustainable throughput per
-hardware tier and DB mode.
+Hardware-vs-throughput benchmark for the Traceway backend. Provisions
+Hetzner Cloud servers, runs OTLP ingest in realistic batch shapes (one signal
+per matrix entry), and produces per-signal charts of sustainable throughput
+per hardware tier and DB mode.
## What it answers
-> On hardware tier **X** with DB config **Y**, you can sustain **N** traces +
-> spans + session-replays per second while reads remain responsive.
+> On hardware tier **X** with DB config **Y**, you can sustain **N** spans/sec,
+> **M** metric data points/sec, and **P** log records/sec via OTLP under
+> collector-shaped batch traffic (gzipped protobuf, batches up to 8192).
-Two DB modes are tested:
+Three signals are tested in separate matrix entries:
+- **spans** → `POST /api/otel/v1/traces` (`ExportTraceServiceRequest`)
+- **metrics** → `POST /api/otel/v1/metrics` (`ExportMetricsServiceRequest`, Gauge data points)
+- **logs** → `POST /api/otel/v1/logs` (`ExportLogsServiceRequest`)
+
+Three DB modes are supported:
- **sqlite** — single-binary Traceway with embedded SQLite (`Dockerfile.sqlite`).
-- **pgch** — full ClickHouse + Postgres stack (`Dockerfile.minimal`).
+- **pgch** — full ClickHouse + Postgres stack, all in Docker on the SUT (`Dockerfile.minimal`).
+- **managed-ch** — `Dockerfile.minimal` pointed at an externally-hosted ClickHouse (ClickHouse Cloud, Aiven, Altinity, etc.) via env vars. Postgres still runs locally in the SUT's Docker. See [Running against managed ClickHouse](#running-against-managed-clickhouse).
Four hardware tiers, all Hetzner CCX (dedicated vCPU) so neighbor noise doesn't
-pollute the read-latency signal:
+pollute the latency signal:
| Tier | vCPU | RAM | Disk |
|-------|------|-------|-------------|
@@ -24,26 +31,42 @@ pollute the read-latency signal:
| CCX33 | 8 | 32 GB | 240 GB NVMe |
| CCX43 | 16 | 64 GB | 360 GB NVMe |
+## Not measured here
+
+This benchmark is **ingest-only** — it does not probe dashboard read latency.
+A separate future benchmark will pre-load N events (100k, 1M, 10M, 100M) and
+measure read endpoint P99 at each fill level. Don't read the numbers here as
+"the dashboard stays usable at N items/sec" — they're "the SUT keeps swallowing
+items at N items/sec without erroring or rejecting."
+
## How a run works
-Per matrix entry (one tier × one mode):
+Per matrix entry (one tier × one mode × one signal):
1. `hetzner-up.sh` provisions a SUT box + a CAX11 loadgen box on a private network (override with `LOADGEN_TIER`).
2. `sut-bootstrap.sh` rsyncs the repo, installs Docker, brings up the right
`docker-compose.<mode>.yml`, waits for `/health`.
-3. `seed-project.sh` registers a fresh user + project, captures the JWT and
- project token.
-4. `loadgen-bootstrap.sh` cross-compiles the loadgen for linux/amd64, pushes
- it to the loadgen box, runs it against the SUT's *private* IP.
-5. The loadgen ramps target ingest in doubling steps (100 -> 200 -> 400 -> ...)
- while a constant read mix probes the dashboard endpoints. Each step holds
- for `--step-duration` (default 2 min).
-6. A step "fails" when ingest error rate > 5%, OR any read endpoint P99 > 3000ms.
- Max sustainable EPS is the actual rate of the last passing step.
+3. `seed-project.sh` registers a fresh user + project, captures the project
+ bearer token.
+4. `loadgen-bootstrap.sh` cross-compiles the loadgen, pushes it to the
+ loadgen box, runs it with `--signal <spans|metrics|logs>` against the
+ SUT's *private* IP.
+5. The loadgen runs a two-phase ramp:
+ - **Phase 1 — batch-size ramp.** Single client at a fixed 5 req/sec.
+ Batch sizes step through `256,1024,4096,8192,16384`. Each step holds for
+ `--step-duration` (default 2 min). Stops at the first failing step.
+ - **Phase 2 — request-rate ramp.** Batch size fixed at
+ `min(Phase 1 winner, --phase2-batch-cap=8192)`. Request rates step
+ through `1,5,25,100,400`.
+6. A step "fails" when combined error rate (HTTP failures + OTLP
+ `PartialSuccess` rejected items) exceeds `--ingest-err-threshold`
+ (default 5%). The headline is
+ `maxSustainableItemsPerSec = batchSize × maxRequestRate`.
7. `hetzner-down.sh` deletes everything via a bash `trap` — even on Ctrl-C.
-After all matrix entries finish, `chart.py` renders `chart.png` (bar) +
-`chart-detail.png` (line: read P99 vs ingest EPS) + `summary.md`.
+After all matrix entries finish, `chart.py` renders three bar charts
+(`chart-spans.png`, `chart-metrics.png`, `chart-logs.png`), three detail
+charts (`chart-detail-<signal>.png`), and a combined `summary.md`.
## Running from your laptop
@@ -76,16 +99,16 @@ After all matrix entries finish, `chart.py` renders `chart.png` (bar) +
./benchmarks/scripts/run-local.sh --smoke
```
-One tier (ccx13), one mode (sqlite), short steps. If this works the full
-matrix works.
+One tier (ccx13), one mode (sqlite), one signal (spans), short steps. If this
+works, the full matrix works.
-### Full matrix (~1 h, ~€1.20)
+### Full matrix (~3 h, ~€3.60)
```bash
./benchmarks/scripts/run-local.sh
```
-4 tiers × 2 modes, default `--duration 30m`. Output goes to
+4 tiers × 2 modes × 3 signals, default `--duration 30m`. Output goes to
`benchmarks/results/<YYYY-MM-DD>-local/` — the `-local` suffix exists so
dev runs never get confused with CI runs and never get accidentally committed.
@@ -95,9 +118,15 @@ dev runs never get confused with CI runs and never get accidentally committed.
# Validate environment without provisioning anything (free)
./benchmarks/scripts/run-local.sh --dry-run
-# Re-run just one tier with default duration
+# Re-run just one tier/mode across all signals
./benchmarks/scripts/run-local.sh --tier ccx23 --mode pgch
+# One signal only across all tiers/modes
+./benchmarks/scripts/run-local.sh --signal spans
+
+# A single matrix cell
+./benchmarks/scripts/run-local.sh --tier ccx13 --mode sqlite --signal logs
+
# Override the per-entry runtime
./benchmarks/scripts/run-local.sh --tier ccx13 --duration 10m
@@ -122,6 +151,49 @@ After the matrix completes, an `aggregate` job downloads all artifacts, runs
`chart.py`, and commits `benchmarks/results/<YYYY-MM-DD>/` to `main` via a bot
commit. No PR — it's a generated artifact.
+## Running against managed ClickHouse
+
+Setting `modes=managed-ch` in the workflow dispatch (or `--mode managed-ch`
+locally) points the SUT's Traceway container at an externally-hosted
+ClickHouse. Postgres still runs locally in the SUT's Docker — this benchmark
+is about ClickHouse characteristics.
+
+Required GitHub repository secrets (Settings → Secrets and variables → Actions):
+
+| Secret | Example | Notes |
+|---|---|---|
+| `BENCH_CH_SERVER` | `your-cluster.us-east-1.aws.clickhouse.cloud:9440` | Native TCP endpoint with TLS port (usually `9440`) |
+| `BENCH_CH_USERNAME` | `default` | A dedicated bench user is wiser than `default` |
+| `BENCH_CH_PASSWORD` | `••••••` | |
+| `BENCH_CH_DATABASE` | `traceway` | Optional, defaults to `traceway` |
+| `BENCH_CH_HTTPS_PORT` | `8443` | Optional, defaults to `8443` (CH Cloud); some hosts use `8123` for plain HTTP |
+
+The bench user needs `DROP DATABASE` and `CREATE DATABASE` privileges — between
+every matrix entry the orchestrator runs `reset-managed-ch.sh`, which wipes and
+recreates the bench database via the HTTPS interface so each (tier × signal ×
+scenario) cell starts on an empty cluster. ~5–10s of overhead per entry. If
+you're running on a shared cluster, **point the bench at a dedicated database**
+or you will lose other data.
+
+Locally: export the same vars (`CLICKHOUSE_SERVER`, `CLICKHOUSE_USERNAME`,
+`CLICKHOUSE_PASSWORD`, optional `CLICKHOUSE_DATABASE`, `BENCH_CH_HTTPS_PORT`)
+before invoking `run-local.sh --mode managed-ch`. Preflight will fail early if
+they're missing.
+
+### Caveats specific to managed CH
+
+- **Network RTT dominates.** Hetzner `nbg1` to ClickHouse Cloud `us-east-1` is
+ ~100ms each way; that's a wall the cluster can't climb. Match regions
+ (`nbg1`/`fsn1`/`hel1` → CH Cloud EU; `ash`/`hil` → CH Cloud US) for numbers
+ comparable to local-CH `pgch`.
+- **Bandwidth matters too.** At 8192-span gzipped OTLP batches × 400 req/sec
+ you push ~30–80 MB/s outbound from the SUT. Hetzner's egress is generous;
+ the managed cluster's ingress quota is the more likely cap.
+- **Read-probe is the more interesting scenario on managed CH.** Throughput
+ often gets bottlenecked on the SUT→cluster pipe before the cluster's actual
+ ingest path. Read-probe surfaces the cluster's read scaling, which is what
+ you actually buy from a managed offering.
+
## Layout
```
@@ -129,13 +201,15 @@ benchmarks/
compose/ # SUT-side docker compose, one per mode
docker-compose.sqlite.yml
docker-compose.pgch.yml
- loadgen/ # The Go binary that generates load
+ docker-compose.managed-ch.yml # External CH; Postgres still local
+ loadgen/ # The Go binary that generates load (OTLP-only)
main.go # CLI + orchestration
- ingest.go # Stream A — stepped ingest worker pool
- report.go # /api/report JSON+gzip sender
- otlp.go # OTLP/HTTP protobuf sender
- reads.go # Stream B — constant read mix
- ramp.go # Step controller + breaking-point logic
+ ingest.go # Worker pool driving the selected signal sender
+ otlp_common.go # Shared OTLP helpers + signalSender interface
+ otlp_spans.go # ExportTraceServiceRequest builder
+ otlp_metrics.go # ExportMetricsServiceRequest builder (Gauge)
+ otlp_logs.go # ExportLogsServiceRequest builder
+ ramp.go # Two-phase ramp (batch size, then request rate)
stats.go # Latency tracker (percentiles via sort)
util.go, log.go # Misc helpers
scripts/
@@ -145,9 +219,10 @@ benchmarks/
hetzner-up.sh # hcloud server create
hetzner-down.sh # hcloud server delete (idempotent)
sut-bootstrap.sh # Installs Docker, brings up backend
+ reset-managed-ch.sh # Wipes the managed CH DB between matrix entries
loadgen-bootstrap.sh # Cross-compiles + runs loadgen
seed-project.sh # /api/register -> JWT + project token JSON
- chart.py # matplotlib renderer
+ chart.py # matplotlib renderer (per-signal charts)
_ssh.sh # Shared ssh/rsync helpers
results/ # Committed bench results live here
```
@@ -167,6 +242,7 @@ benchmarks/
up --build` on a CCX13 takes 5–8 minutes (npm install + Go build).
`sut-bootstrap.sh` waits up to 10 minutes for `/health` before giving up.
Subsequent runs reuse the Docker layer cache via the persistent volumes.
-- **All steps pass on the highest tier.** Increase `--max-eps` (default 50000)
+- **All steps pass on the highest tier.** Raise the upper end of
+ `--phase2-request-rates` (default `1,5,25,100,400`) — e.g. add `1000,2000` —
if you want to find the ceiling on big boxes. The default is meant to keep
- one-tier runs bounded; on CCX43 with PG/CH the ceiling can be well above 10k EPS.
+ one-tier runs bounded.
diff --git a/benchmarks/compose/docker-compose.managed-ch.yml b/benchmarks/compose/docker-compose.managed-ch.yml
new file mode 100644
index 00000000..5ee27523
--- /dev/null
+++ b/benchmarks/compose/docker-compose.managed-ch.yml
@@ -0,0 +1,50 @@
+services:
+ traceway:
+ build:
+ context: ../..
+ dockerfile: Dockerfile.minimal
+ ports:
+ - "${BENCH_PORT:-8087}:80"
+ environment:
+ CLICKHOUSE_SERVER: "${CLICKHOUSE_SERVER}"
+ CLICKHOUSE_DATABASE: "${CLICKHOUSE_DATABASE:-traceway}"
+ CLICKHOUSE_USERNAME: "${CLICKHOUSE_USERNAME}"
+ CLICKHOUSE_PASSWORD: "${CLICKHOUSE_PASSWORD}"
+ CLICKHOUSE_TLS: "${CLICKHOUSE_TLS:-true}"
+ POSTGRES_HOST: "postgres"
+ POSTGRES_PORT: "5432"
+ POSTGRES_DATABASE: "traceway"
+ POSTGRES_USERNAME: "traceway"
+ POSTGRES_PASSWORD: "traceway"
+ POSTGRES_SSLMODE: "disable"
+ JWT_SECRET: "bench-jwt-secret-not-for-production-use-only-32chars+"
+ GIN_MODE: "release"
+ depends_on:
+ postgres:
+ condition: service_healthy
+ restart: "no"
+ healthcheck:
+ test: ["CMD", "wget", "-qO-", "http://localhost/health"]
+ interval: 5s
+ timeout: 3s
+ start_period: 10s
+ retries: 20
+
+ postgres:
+ image: postgres:17
+ environment:
+ POSTGRES_USER: traceway
+ POSTGRES_PASSWORD: traceway
+ POSTGRES_DB: traceway
+ volumes:
+ - postgres-bench-data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U traceway"]
+ interval: 5s
+ timeout: 3s
+ start_period: 10s
+ retries: 20
+ restart: "no"
+
+volumes:
+ postgres-bench-data:
diff --git a/benchmarks/loadgen/go.mod b/benchmarks/loadgen/go.mod
index 7b72cd8a..67e001a1 100644
--- a/benchmarks/loadgen/go.mod
+++ b/benchmarks/loadgen/go.mod
@@ -3,7 +3,6 @@ module bench-loadgen
go 1.25
require (
- github.com/google/uuid v1.6.0
go.opentelemetry.io/proto/otlp v1.5.0
golang.org/x/time v0.7.0
google.golang.org/protobuf v1.36.1
diff --git a/benchmarks/loadgen/ingest.go b/benchmarks/loadgen/ingest.go
index 7adfc625..8191f854 100644
--- a/benchmarks/loadgen/ingest.go
+++ b/benchmarks/loadgen/ingest.go
@@ -10,87 +10,143 @@ import (
"golang.org/x/time/rate"
)
-const (
- // One frame carries 10 traces, so frame rate = targetEPS / tracesPerFrame.
- // Matches Go SDK behavior where frames rotate every ~5s with whatever has
- // accumulated; benchmark uses a fixed batch size for predictable accounting.
- tracesPerFrame = 10
- ingestWorkers = 256
- recordingChance = 0.05 // 5% of frames carry a session recording segment
- exceptionChance = 0.02 // 2% of frames carry an exception
-)
-
type ingester struct {
cfg config
client *http.Client
stats *latencyTracker
+ sender signalSender
limiter *rate.Limiter
+
+ batchSize atomic.Int64
+ requestRate atomic.Int64 // requests/sec, scaled by 1e3 so we keep fractional resolution
+ attemptedItems atomic.Int64
+ rejectedItems atomic.Int64
+
// rng pool: each worker grabs one to avoid contending on the global source
rngPool sync.Pool
- // sessionsCreated counts sessions sent via /api/report so the reader can
- // query a real session ID for the recording playback endpoint.
- sessionsCreated atomic.Int64
- sampleSession atomic.Value // string — most recently seeded session id
+
+ // workerWg + workerCancel let the ramp resize the pool between steps.
+ workerWg *sync.WaitGroup
+ workerCancel context.CancelFunc
}
-func newIngester(cfg config, client *http.Client, stats *latencyTracker) *ingester {
- framesPerSec := cfg.initialEPS / tracesPerFrame
- if framesPerSec < 1 {
- framesPerSec = 1
+func newIngester(cfg config, client *http.Client, stats *latencyTracker) (*ingester, error) {
+ sender, err := pickSender(cfg.signal)
+ if err != nil {
+ return nil, err
}
return &ingester{
cfg: cfg,
client: client,
stats: stats,
- limiter: rate.NewLimiter(rate.Limit(framesPerSec), int(framesPerSec)+1),
+ sender: sender,
+ limiter: rate.NewLimiter(rate.Limit(1), 1),
rngPool: sync.Pool{New: func() any { return rand.New(rand.NewSource(rand.Int63())) }},
+ }, nil
+}
+
+func pickSender(signal string) (signalSender, error) {
+ switch signal {
+ case "spans":
+ return spansSender{}, nil
+ case "metrics":
+ return metricsSender{}, nil
+ case "logs":
+ return logsSender{}, nil
+ default:
+ return nil, errUnknownSignal(signal)
}
}
-func (i *ingester) SetRate(eps float64) {
- fps := eps / tracesPerFrame
- if fps < 1 {
- fps = 1
+type errUnknownSignal string
+
+func (e errUnknownSignal) Error() string {
+ return "unknown signal: " + string(e) + " (expected spans|metrics|logs)"
+}
+
+func (i *ingester) Name() string {
+ return i.sender.Name()
+}
+
+func (i *ingester) SetBatchSize(b int) {
+ if b < 1 {
+ b = 1
}
- i.limiter.SetLimit(rate.Limit(fps))
- i.limiter.SetBurst(int(fps) + 1)
+ i.batchSize.Store(int64(b))
}
-func (i *ingester) SampleSessionId() string {
- v := i.sampleSession.Load()
- if v == nil {
- return ""
+func (i *ingester) SetRequestRate(rps float64) {
+ if rps < 0.001 {
+ rps = 0.001
}
- return v.(string)
+ i.limiter.SetLimit(rate.Limit(rps))
+ burst := int(rps) + 1
+ if burst < 1 {
+ burst = 1
+ }
+ i.limiter.SetBurst(burst)
+ i.requestRate.Store(int64(rps * 1000))
+}
+
+func (i *ingester) RequestRate() float64 {
+ return float64(i.requestRate.Load()) / 1000.0
}
-func (i *ingester) run(ctx context.Context) {
- var wg sync.WaitGroup
- wg.Add(ingestWorkers)
- for w := 0; w < ingestWorkers; w++ {
+// SnapshotAndResetItems returns attempted/rejected since the last call and
+// resets them. Called at step boundaries alongside latencyTracker.
+func (i *ingester) SnapshotAndResetItems() (attempted, rejected int64) {
+ attempted = i.attemptedItems.Swap(0)
+ rejected = i.rejectedItems.Swap(0)
+ return
+}
+
+// Start launches the worker pool sized for the current request rate. Call Stop
+// before changing the worker count via another Start.
+func (i *ingester) Start(ctx context.Context) {
+ workerCtx, cancel := context.WithCancel(ctx)
+ wg := &sync.WaitGroup{}
+ i.workerCancel = cancel
+ i.workerWg = wg
+
+ workers := workerCountFor(i.RequestRate())
+ wg.Add(workers)
+ for w := 0; w < workers; w++ {
go func() {
defer wg.Done()
rng := i.rngPool.Get().(*rand.Rand)
defer i.rngPool.Put(rng)
for {
- if err := i.limiter.Wait(ctx); err != nil {
+ if err := i.limiter.Wait(workerCtx); err != nil {
return
}
- i.sendOne(ctx, rng)
+ batchSize := int(i.batchSize.Load())
+ sendOneOTLP(workerCtx, i.client, i.cfg, i.sender, rng, batchSize, i.stats, &i.attemptedItems, &i.rejectedItems)
}
}()
}
- wg.Wait()
}
-func (i *ingester) sendOne(ctx context.Context, rng *rand.Rand) {
- if rng.Float64() < i.cfg.reportShare {
- sessionId := sendReportFrame(ctx, i.client, i.cfg, rng, i.stats)
- if sessionId != "" {
- i.sampleSession.Store(sessionId)
- i.sessionsCreated.Add(1)
- }
- } else {
- sendOTLPTraces(ctx, i.client, i.cfg, rng, i.stats)
+func (i *ingester) Stop() {
+ if i.workerCancel != nil {
+ i.workerCancel()
+ }
+ if i.workerWg != nil {
+ i.workerWg.Wait()
+ }
+ i.workerCancel = nil
+ i.workerWg = nil
+}
+
+// workerCountFor scales worker count with request rate. 256 workers idling on
+// a 5 req/sec limiter is wasteful; on the other hand, a 400 req/sec target
+// with 8 workers + a 200ms p99 leaves the limiter starved.
+func workerCountFor(rps float64) int {
+ n := int(rps * 2)
+ if n < 8 {
+ n = 8
+ }
+ if n > 256 {
+ n = 256
}
+ return n
}
diff --git a/benchmarks/loadgen/main.go b/benchmarks/loadgen/main.go
index 6fa92e7f..cf6d0ac3 100644
--- a/benchmarks/loadgen/main.go
+++ b/benchmarks/loadgen/main.go
@@ -5,58 +5,113 @@ import (
"encoding/json"
"flag"
"fmt"
- "log"
"net/http"
"os"
"os/signal"
+ "strconv"
+ "strings"
"syscall"
"time"
)
type config struct {
- target string
- projectToken string
- jwt string
- projectId string
- duration time.Duration
- stepDuration time.Duration
- initialEPS float64
- maxEPS float64
- reportShare float64
- readRPS float64
- ingestErrThreshold float64
- readP99ThresholdMs float64
- reportOut string
- tier string
- mode string
+ target string
+ projectToken string
+ jwt string
+ projectId string
+ signal string
+ scenario string
+ duration time.Duration
+ stepDuration time.Duration
+ phase1BatchSizes []int
+ phase2RequestRates []float64
+ phase1FixedRate float64
+ phase2BatchCap int
+ ingestErrThreshold float64
+ fillLevels []int64
+ readThresholdMs int
+ settleSeconds time.Duration
+ fillBatchSize int
+ fillRequestRate float64
+ reportOut string
+ tier string
+ mode string
}
func main() {
- var cfg config
+ var (
+ cfg config
+ phase1BatchesStr string
+ phase2RatesStr string
+ fillLevelsStr string
+ )
flag.StringVar(&cfg.target, "target", "", "Base URL of the system under test (e.g. http://10.0.0.2 or http://localhost:8087)")
- flag.StringVar(&cfg.projectToken, "token", "", "Project bearer token for /api/report + OTLP")
- flag.StringVar(&cfg.jwt, "jwt", "", "JWT for dashboard read endpoints")
- flag.StringVar(&cfg.projectId, "project-id", "", "Project UUID (passed as ?projectId= on read endpoints)")
+ flag.StringVar(&cfg.projectToken, "token", "", "Project bearer token for OTLP ingest endpoints")
+ flag.StringVar(&cfg.jwt, "jwt", "", "JWT for read endpoints (required when --scenario=read-probe)")
+ flag.StringVar(&cfg.projectId, "project-id", "", "Project UUID for read endpoints (required when --scenario=read-probe)")
+ flag.StringVar(&cfg.signal, "signal", "", "Which signal to benchmark: spans | metrics | logs (required)")
+ flag.StringVar(&cfg.scenario, "scenario", "throughput", "Scenario: throughput (default, two-phase ingest ramp) | read-probe (ingest to fill levels and probe a read)")
flag.DurationVar(&cfg.duration, "duration", 30*time.Minute, "Total run duration cap")
- flag.DurationVar(&cfg.stepDuration, "step-duration", 2*time.Minute, "Per-step hold time")
- flag.Float64Var(&cfg.initialEPS, "initial-eps", 100, "Starting target traces/sec")
- flag.Float64Var(&cfg.maxEPS, "max-eps", 50000, "Hard cap on target traces/sec")
- flag.Float64Var(&cfg.reportShare, "report-share", 0.7, "Fraction of ingest sent via /api/report (rest via OTLP)")
- flag.Float64Var(&cfg.readRPS, "read-rps", 1.0, "Read RPS per endpoint")
- flag.Float64Var(&cfg.ingestErrThreshold, "ingest-err-threshold", 0.05, "Step fails if ingest error rate exceeds this")
- flag.Float64Var(&cfg.readP99ThresholdMs, "read-p99-threshold-ms", 3000, "Step fails if any read endpoint p99 (ms) exceeds this")
+ flag.DurationVar(&cfg.stepDuration, "step-duration", 2*time.Minute, "Per-step hold time (throughput scenario only)")
+ flag.StringVar(&phase1BatchesStr, "phase1-batch-sizes", "256,1024,4096,8192,16384", "Comma-separated batch sizes for Phase 1 (throughput scenario)")
+ flag.StringVar(&phase2RatesStr, "phase2-request-rates", "1,5,25,100,400", "Comma-separated request rates for Phase 2 (throughput scenario)")
+ flag.Float64Var(&cfg.phase1FixedRate, "phase1-fixed-rate", 5, "Fixed request rate during Phase 1 (req/sec)")
+ flag.IntVar(&cfg.phase2BatchCap, "phase2-batch-cap", 8192, "Cap on Phase 2 batch size; Phase 2 uses min(this, Phase 1 winner)")
+ flag.Float64Var(&cfg.ingestErrThreshold, "ingest-err-threshold", 0.05, "Step fails if combined (HTTP error + OTLP rejected) item rate exceeds this")
+ flag.StringVar(&fillLevelsStr, "fill-levels", "100000,1000000,10000000,100000000", "Comma-separated row counts to fill before probing a read (read-probe scenario)")
+ flag.IntVar(&cfg.readThresholdMs, "read-threshold-ms", 5000, "Read latency threshold in ms; step fails if a probe exceeds it (read-probe scenario)")
+ flag.DurationVar(&cfg.settleSeconds, "settle-seconds", 10*time.Second, "Wait between finishing ingest and probing the read (read-probe scenario)")
+ flag.IntVar(&cfg.fillBatchSize, "fill-batch-size", 8192, "OTLP batch size used during the fill phase (read-probe scenario)")
+ flag.Float64Var(&cfg.fillRequestRate, "fill-request-rate", 100, "OTLP request rate (req/sec) during the fill phase (read-probe scenario)")
flag.StringVar(&cfg.reportOut, "report-out", "", "Path to write JSON results (required)")
flag.StringVar(&cfg.tier, "tier", "local", "Hardware tier label embedded in output (e.g. ccx13)")
flag.StringVar(&cfg.mode, "mode", "unknown", "DB mode label embedded in output (sqlite | pgch)")
flag.Parse()
- if cfg.target == "" || cfg.projectToken == "" || cfg.reportOut == "" {
- fmt.Fprintln(os.Stderr, "missing required flag: --target, --token, --report-out")
+ if cfg.target == "" || cfg.projectToken == "" || cfg.reportOut == "" || cfg.signal == "" {
+ fmt.Fprintln(os.Stderr, "missing required flag: --target, --token, --signal, --report-out")
flag.Usage()
os.Exit(2)
}
+ batches, err := parseInts(phase1BatchesStr)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "invalid --phase1-batch-sizes: %v\n", err)
+ os.Exit(2)
+ }
+ rates, err := parseFloats(phase2RatesStr)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "invalid --phase2-request-rates: %v\n", err)
+ os.Exit(2)
+ }
+ cfg.phase1BatchSizes = batches
+ cfg.phase2RequestRates = rates
+
+ fillLevels, err := parseInt64s(fillLevelsStr)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "invalid --fill-levels: %v\n", err)
+ os.Exit(2)
+ }
+ cfg.fillLevels = fillLevels
+
+ if _, err := pickSender(cfg.signal); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(2)
+ }
+
+ switch cfg.scenario {
+ case "throughput":
+ case "read-probe":
+ if cfg.jwt == "" || cfg.projectId == "" {
+ fmt.Fprintln(os.Stderr, "--scenario=read-probe requires --jwt and --project-id")
+ os.Exit(2)
+ }
+ default:
+ fmt.Fprintf(os.Stderr, "unknown --scenario %q (expected throughput|read-probe)\n", cfg.scenario)
+ os.Exit(2)
+ }
+
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
@@ -65,50 +120,121 @@ func main() {
defer cancelDeadline()
httpClient := &http.Client{
- Timeout: 15 * time.Second,
+ Timeout: 30 * time.Second,
Transport: &http.Transport{
- MaxIdleConns: 200,
- MaxIdleConnsPerHost: 100,
+ MaxIdleConns: 500,
+ MaxIdleConnsPerHost: 200,
IdleConnTimeout: 60 * time.Second,
},
}
+ startedAt := time.Now().UTC()
ingestStats := newLatencyTracker()
- readStats := map[string]*latencyTracker{
- "endpoints_grouped": newLatencyTracker(),
- "exceptions_grouped": newLatencyTracker(),
- "dashboard_overview": newLatencyTracker(),
- "session_recording": newLatencyTracker(),
- "logs": newLatencyTracker(),
+ ing, err := newIngester(cfg, httpClient, ingestStats)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(2)
}
- ingester := newIngester(cfg, httpClient, ingestStats)
- reader := newReader(cfg, httpClient, readStats)
- reader.attachIngester(ingester)
-
- go ingester.run(ctx)
- go reader.run(ctx)
-
- results := runRamp(ctx, cfg, ingester, ingestStats, readStats)
-
out := finalReport{
Tier: cfg.tier,
Mode: cfg.mode,
- StartedAt: time.Now().UTC().Add(-cfg.duration).Format(time.RFC3339),
- EndedAt: time.Now().UTC().Format(time.RFC3339),
- Steps: results,
+ Signal: cfg.signal,
+ Scenario: cfg.scenario,
+ StartedAt: startedAt.Format(time.RFC3339),
+ }
+
+ switch cfg.scenario {
+ case "throughput":
+ phase1 := runBatchSizeRamp(ctx, cfg, ing, ingestStats)
+ phase2 := runRequestRateRamp(ctx, cfg, ing, ingestStats, phase1)
+ out.Phase1 = &phase1
+ out.Phase2 = &phase2
+ case "read-probe":
+ probe := runReadProbe(ctx, cfg, ing, ingestStats, httpClient)
+ out.ReadProbe = &probe
}
- out.computeBreakingPoint()
+ out.EndedAt = time.Now().UTC().Format(time.RFC3339)
+ out.computeHeadline()
f, err := os.Create(cfg.reportOut)
if err != nil {
- log.Fatalf("create %s: %v", cfg.reportOut, err)
+ fmt.Fprintf(os.Stderr, "create %s: %v\n", cfg.reportOut, err)
+ os.Exit(1)
}
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err := enc.Encode(&out); err != nil {
- log.Fatalf("write %s: %v", cfg.reportOut, err)
+ fmt.Fprintf(os.Stderr, "write %s: %v\n", cfg.reportOut, err)
+ os.Exit(1)
+ }
+ switch cfg.scenario {
+ case "throughput":
+ fmt.Fprintf(os.Stderr, "wrote %s: signal=%s max sustainable %s/sec = %.0f\n",
+ cfg.reportOut, cfg.signal, cfg.signal, out.MaxSustainableItemsPerSec)
+ case "read-probe":
+ fmt.Fprintf(os.Stderr, "wrote %s: signal=%s max fill level passed = %d rows\n",
+ cfg.reportOut, cfg.signal, out.MaxFillLevelPassed)
+ }
+}
+
+func parseInt64s(s string) ([]int64, error) {
+ parts := strings.Split(s, ",")
+ out := make([]int64, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ continue
+ }
+ v, err := strconv.ParseInt(p, 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("parse %q: %w", p, err)
+ }
+ out = append(out, v)
+ }
+ if len(out) == 0 {
+ return nil, fmt.Errorf("empty list")
+ }
+ return out, nil
+}
+
+func parseInts(s string) ([]int, error) {
+ parts := strings.Split(s, ",")
+ out := make([]int, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ continue
+ }
+ v, err := strconv.Atoi(p)
+ if err != nil {
+ return nil, fmt.Errorf("parse %q: %w", p, err)
+ }
+ out = append(out, v)
+ }
+ if len(out) == 0 {
+ return nil, fmt.Errorf("empty list")
+ }
+ return out, nil
+}
+
+func parseFloats(s string) ([]float64, error) {
+ parts := strings.Split(s, ",")
+ out := make([]float64, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ continue
+ }
+ v, err := strconv.ParseFloat(p, 64)
+ if err != nil {
+ return nil, fmt.Errorf("parse %q: %w", p, err)
+ }
+ out = append(out, v)
+ }
+ if len(out) == 0 {
+ return nil, fmt.Errorf("empty list")
}
- fmt.Fprintf(os.Stderr, "wrote %s: max sustainable EPS = %.0f (%d step(s))\n", cfg.reportOut, out.MaxSustainableEPS, len(out.Steps))
+ return out, nil
}
diff --git a/benchmarks/loadgen/otlp_common.go b/benchmarks/loadgen/otlp_common.go
new file mode 100644
index 00000000..a2a2d9e1
--- /dev/null
+++ b/benchmarks/loadgen/otlp_common.go
@@ -0,0 +1,111 @@
+package main
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "fmt"
+ "io"
+ "math/rand"
+ "net/http"
+ "sync/atomic"
+ "time"
+
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
+)
+
+// signalSender abstracts per-signal payload generation. The ingester does the
+// HTTP plumbing once and delegates only the signal-specific bits — building the
+// protobuf body and parsing the partial-success response — to implementations.
+type signalSender interface {
+ Name() string
+ Path() string
+ BuildBody(rng *rand.Rand, batchSize int) ([]byte, error)
+ ParseRejected(respBody []byte) int
+}
+
+func strAttr(k, v string) *commonpb.KeyValue {
+ return &commonpb.KeyValue{Key: k, Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: v}}}
+}
+
+func intAttr(k string, v int64) *commonpb.KeyValue {
+ return &commonpb.KeyValue{Key: k, Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_IntValue{IntValue: v}}}
+}
+
+func gzipCompress(data []byte) ([]byte, error) {
+ var buf bytes.Buffer
+ w := gzip.NewWriter(&buf)
+ if _, err := w.Write(data); err != nil {
+ return nil, err
+ }
+ if err := w.Close(); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+func randomString(rng *rand.Rand, n int) string {
+ const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = charset[rng.Intn(len(charset))]
+ }
+ return string(b)
+}
+
+// sendOneOTLP performs one POST cycle for a generic signalSender. The ingester
+// calls this in its worker loop. attemptedItems is bumped before the request
+// goes out so that drops on the wire still count toward "attempted"; rejected
+// (server-reported partial-success) is bumped only on successful 2xx.
+func sendOneOTLP(
+ ctx context.Context,
+ client *http.Client,
+ cfg config,
+ sender signalSender,
+ rng *rand.Rand,
+ batchSize int,
+ stats *latencyTracker,
+ attemptedItems *atomic.Int64,
+ rejectedItems *atomic.Int64,
+) {
+ body, err := sender.BuildBody(rng, batchSize)
+ if err != nil {
+ stats.Record(0, err)
+ return
+ }
+ gz, err := gzipCompress(body)
+ if err != nil {
+ stats.Record(0, err)
+ return
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.target+sender.Path(), bytes.NewReader(gz))
+ if err != nil {
+ stats.Record(0, err)
+ return
+ }
+ req.Header.Set("Content-Type", "application/x-protobuf")
+ req.Header.Set("Content-Encoding", "gzip")
+ req.Header.Set("Authorization", "Bearer "+cfg.projectToken)
+
+ attemptedItems.Add(int64(batchSize))
+
+ start := time.Now()
+ resp, err := client.Do(req)
+ elapsed := time.Since(start)
+ if err != nil {
+ stats.Record(elapsed.Seconds()*1000, err)
+ return
+ }
+ defer resp.Body.Close()
+ respBody, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode >= 400 {
+ stats.Record(elapsed.Seconds()*1000, fmt.Errorf("status %d", resp.StatusCode))
+ return
+ }
+
+ if rej := sender.ParseRejected(respBody); rej > 0 {
+ rejectedItems.Add(int64(rej))
+ }
+ stats.Record(elapsed.Seconds()*1000, nil)
+}
diff --git a/benchmarks/loadgen/otlp_logs.go b/benchmarks/loadgen/otlp_logs.go
new file mode 100644
index 00000000..174c5761
--- /dev/null
+++ b/benchmarks/loadgen/otlp_logs.go
@@ -0,0 +1,90 @@
+package main
+
+import (
+ "crypto/rand"
+ mathrand "math/rand"
+ "time"
+
+ collogspb "go.opentelemetry.io/proto/otlp/collector/logs/v1"
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
+ logspb "go.opentelemetry.io/proto/otlp/logs/v1"
+ resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
+ "google.golang.org/protobuf/proto"
+)
+
+var severityChoices = []struct {
+ number logspb.SeverityNumber
+ text string
+}{
+ {logspb.SeverityNumber_SEVERITY_NUMBER_INFO, "INFO"},
+ {logspb.SeverityNumber_SEVERITY_NUMBER_INFO, "INFO"},
+ {logspb.SeverityNumber_SEVERITY_NUMBER_INFO, "INFO"},
+ {logspb.SeverityNumber_SEVERITY_NUMBER_WARN, "WARN"},
+ {logspb.SeverityNumber_SEVERITY_NUMBER_ERROR, "ERROR"},
+}
+
+type logsSender struct{}
+
+func (logsSender) Name() string { return "logs" }
+func (logsSender) Path() string { return "/api/otel/v1/logs" }
+
+func (logsSender) BuildBody(rng *mathrand.Rand, batchSize int) ([]byte, error) {
+ now := time.Now().UTC()
+ resourceAttrs := []*commonpb.KeyValue{
+ strAttr("service.name", "bench-loadgen"),
+ strAttr("service.version", "1.0.0"),
+ strAttr("deployment.environment", "bench"),
+ }
+
+ records := make([]*logspb.LogRecord, batchSize)
+ for i := range records {
+ ts := now.Add(-time.Duration(rng.Intn(5000)) * time.Millisecond).UnixNano()
+ sev := severityChoices[rng.Intn(len(severityChoices))]
+ traceId := make([]byte, 16)
+ spanId := make([]byte, 8)
+ _, _ = rand.Read(traceId)
+ _, _ = rand.Read(spanId)
+
+ records[i] = &logspb.LogRecord{
+ TimeUnixNano: uint64(ts),
+ ObservedTimeUnixNano: uint64(ts),
+ SeverityNumber: sev.number,
+ SeverityText: sev.text,
+ Body: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: randomString(rng, 120)}},
+ Attributes: []*commonpb.KeyValue{
+ strAttr("logger.name", "bench-loadgen"),
+ strAttr("thread.name", "worker-1"),
+ strAttr("code.namespace", "bench.handler"),
+ intAttr("retry.count", int64(rng.Intn(3))),
+ strAttr("user.id", randomString(rng, 16)),
+ },
+ TraceId: traceId,
+ SpanId: spanId,
+ }
+ }
+
+ req := &collogspb.ExportLogsServiceRequest{
+ ResourceLogs: []*logspb.ResourceLogs{{
+ Resource: &resourcepb.Resource{Attributes: resourceAttrs},
+ ScopeLogs: []*logspb.ScopeLogs{{
+ Scope: &commonpb.InstrumentationScope{Name: "bench-loadgen", Version: "1.0.0"},
+ LogRecords: records,
+ }},
+ }},
+ }
+ return proto.Marshal(req)
+}
+
+func (logsSender) ParseRejected(respBody []byte) int {
+ if len(respBody) == 0 {
+ return 0
+ }
+ var resp collogspb.ExportLogsServiceResponse
+ if err := proto.Unmarshal(respBody, &resp); err != nil {
+ return 0
+ }
+ if resp.PartialSuccess == nil {
+ return 0
+ }
+ return int(resp.PartialSuccess.RejectedLogRecords)
+}
diff --git a/benchmarks/loadgen/otlp_metrics.go b/benchmarks/loadgen/otlp_metrics.go
new file mode 100644
index 00000000..b9e0dfa4
--- /dev/null
+++ b/benchmarks/loadgen/otlp_metrics.go
@@ -0,0 +1,92 @@
+package main
+
+import (
+ mathrand "math/rand"
+ "time"
+
+ colmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
+ metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
+ resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
+ "google.golang.org/protobuf/proto"
+)
+
+// metricNames is intentionally low cardinality. The backend auto-registers
+// metrics in metric_registry on first sight; bench traffic with 10 stable
+// names exercises that path once per name per project and otherwise lets the
+// hot path stay hot.
+var metricNames = []string{
+ "bench.metric.cpu", "bench.metric.mem", "bench.metric.qps", "bench.metric.lat", "bench.metric.errs",
+ "bench.metric.disk", "bench.metric.net", "bench.metric.heap", "bench.metric.gc", "bench.metric.fd",
+}
+
+type metricsSender struct{}
+
+func (metricsSender) Name() string { return "metrics" }
+func (metricsSender) Path() string { return "/api/otel/v1/metrics" }
+
+func (metricsSender) BuildBody(rng *mathrand.Rand, batchSize int) ([]byte, error) {
+ now := time.Now().UTC()
+ resourceAttrs := []*commonpb.KeyValue{
+ strAttr("service.name", "bench-loadgen"),
+ strAttr("service.version", "1.0.0"),
+ strAttr("deployment.environment", "bench"),
+ }
+
+ // Distribute batchSize data points across the 10 unique metric names so
+ // each batch exercises all of them. Trailing points go on the last metric.
+ perMetric := batchSize / len(metricNames)
+ remainder := batchSize % len(metricNames)
+
+ metrics := make([]*metricspb.Metric, 0, len(metricNames))
+ for i, name := range metricNames {
+ n := perMetric
+ if i == len(metricNames)-1 {
+ n += remainder
+ }
+ if n <= 0 {
+ continue
+ }
+ points := make([]*metricspb.NumberDataPoint, n)
+ for p := 0; p < n; p++ {
+ pointTime := now.Add(-time.Duration(rng.Intn(1000)) * time.Millisecond).UnixNano()
+ points[p] = &metricspb.NumberDataPoint{
+ TimeUnixNano: uint64(pointTime),
+ Value: &metricspb.NumberDataPoint_AsDouble{AsDouble: rng.Float64() * 100},
+ Attributes: []*commonpb.KeyValue{
+ strAttr("host", "bench-host-1"),
+ },
+ }
+ }
+ metrics = append(metrics, &metricspb.Metric{
+ Name: name,
+ Unit: "1",
+ Data: &metricspb.Metric_Gauge{Gauge: &metricspb.Gauge{DataPoints: points}},
+ })
+ }
+
+ req := &colmetricspb.ExportMetricsServiceRequest{
+ ResourceMetrics: []*metricspb.ResourceMetrics{{
+ Resource: &resourcepb.Resource{Attributes: resourceAttrs},
+ ScopeMetrics: []*metricspb.ScopeMetrics{{
+ Scope: &commonpb.InstrumentationScope{Name: "bench-loadgen", Version: "1.0.0"},
+ Metrics: metrics,
+ }},
+ }},
+ }
+ return proto.Marshal(req)
+}
+
+func (metricsSender) ParseRejected(respBody []byte) int {
+ if len(respBody) == 0 {
+ return 0
+ }
+ var resp colmetricspb.ExportMetricsServiceResponse
+ if err := proto.Unmarshal(respBody, &resp); err != nil {
+ return 0
+ }
+ if resp.PartialSuccess == nil {
+ return 0
+ }
+ return int(resp.PartialSuccess.RejectedDataPoints)
+}
diff --git a/benchmarks/loadgen/otlp.go b/benchmarks/loadgen/otlp_spans.go
similarity index 51%
rename from benchmarks/loadgen/otlp.go
rename to benchmarks/loadgen/otlp_spans.go
index 4f3933e3..3819f94a 100644
--- a/benchmarks/loadgen/otlp.go
+++ b/benchmarks/loadgen/otlp_spans.go
@@ -1,29 +1,30 @@
package main
import (
- "bytes"
- "context"
"crypto/rand"
- "fmt"
- "net/http"
mathrand "math/rand"
"time"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
- resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1"
+ resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
"google.golang.org/protobuf/proto"
)
-const otlpSpansPerRequest = 20
+var endpointPaths = []string{
+ "GET /api/users", "POST /api/users", "GET /api/orders", "POST /api/orders",
+ "GET /api/products/:id", "PUT /api/products/:id", "GET /api/search",
+ "POST /api/checkout", "GET /api/cart", "DELETE /api/cart/:id",
+ "GET /api/auth/me", "POST /api/auth/login", "GET /api/health",
+}
+
+type spansSender struct{}
+
+func (spansSender) Name() string { return "spans" }
+func (spansSender) Path() string { return "/api/otel/v1/traces" }
-// sendOTLPTraces marshals an ExportTraceServiceRequest with otlpSpansPerRequest
-// spans into protobuf, POSTs to /api/otel/v1/traces, and records latency.
-// Protobuf (not protojson) because that's what production exporters send — it
-// exercises the backend's protobuf decode path which is non-trivial CPU work
-// that would be hidden if we sent JSON.
-func sendOTLPTraces(ctx context.Context, client *http.Client, cfg config, rng *mathrand.Rand, stats *latencyTracker) {
+func (spansSender) BuildBody(rng *mathrand.Rand, batchSize int) ([]byte, error) {
now := time.Now().UTC()
resourceAttrs := []*commonpb.KeyValue{
strAttr("service.name", "bench-loadgen"),
@@ -31,7 +32,7 @@ func sendOTLPTraces(ctx context.Context, client *http.Client, cfg config, rng *m
strAttr("deployment.environment", "bench"),
}
- spans := make([]*tracepb.Span, otlpSpansPerRequest)
+ spans := make([]*tracepb.Span, batchSize)
for i := range spans {
traceId := make([]byte, 16)
spanId := make([]byte, 8)
@@ -67,41 +68,33 @@ func sendOTLPTraces(ctx context.Context, client *http.Client, cfg config, rng *m
}},
}},
}
+ return proto.Marshal(req)
+}
- body, err := proto.Marshal(req)
- if err != nil {
- stats.Record(0, err)
- return
- }
-
- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.target+"/api/otel/v1/traces", bytes.NewReader(body))
- if err != nil {
- stats.Record(0, err)
- return
+func (spansSender) ParseRejected(respBody []byte) int {
+ if len(respBody) == 0 {
+ return 0
}
- httpReq.Header.Set("Content-Type", "application/x-protobuf")
- httpReq.Header.Set("Authorization", "Bearer "+cfg.projectToken)
-
- start := time.Now()
- resp, err := client.Do(httpReq)
- elapsed := time.Since(start)
- if err != nil {
- stats.Record(elapsed.Seconds()*1000, err)
- return
+ var resp coltracepb.ExportTraceServiceResponse
+ if err := proto.Unmarshal(respBody, &resp); err != nil {
+ return 0
}
- defer resp.Body.Close()
- _, _ = readAndDiscard(resp.Body)
- if resp.StatusCode >= 400 {
- stats.Record(elapsed.Seconds()*1000, fmt.Errorf("status %d", resp.StatusCode))
- return
+ if resp.PartialSuccess == nil {
+ return 0
}
- stats.Record(elapsed.Seconds()*1000, nil)
+ return int(resp.PartialSuccess.RejectedSpans)
}
-func strAttr(k, v string) *commonpb.KeyValue {
- return &commonpb.KeyValue{Key: k, Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: v}}}
-}
-
-func intAttr(k string, v int64) *commonpb.KeyValue {
- return &commonpb.KeyValue{Key: k, Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_IntValue{IntValue: v}}}
+func pickStatus(rng *mathrand.Rand) int {
+ r := rng.Float64()
+ switch {
+ case r < 0.92:
+ return 200
+ case r < 0.95:
+ return 201
+ case r < 0.98:
+ return 404
+ default:
+ return 500
+ }
}
diff --git a/benchmarks/loadgen/ramp.go b/benchmarks/loadgen/ramp.go
index 6d5ac620..52ca08eb 100644
--- a/benchmarks/loadgen/ramp.go
+++ b/benchmarks/loadgen/ramp.go
@@ -7,118 +7,196 @@ import (
)
type stepResult struct {
- Step int `json:"step"`
- TargetEPS float64 `json:"targetEps"`
- ActualEPS float64 `json:"actualEps"`
- Ingest latencySnapshot `json:"ingest"`
- Reads map[string]latencySnapshot `json:"reads"`
- Passed bool `json:"passed"`
- FailReason string `json:"failReason,omitempty"`
+ Step int `json:"step"`
+ BatchSize int `json:"batchSize"`
+ RequestRate float64 `json:"requestRate"`
+ AttemptedItemsPerSec float64 `json:"attemptedItemsPerSec"`
+ ActualItemsPerSec float64 `json:"actualItemsPerSec"`
+ Rejected int64 `json:"rejected"`
+ Ingest latencySnapshot `json:"ingest"`
+ Passed bool `json:"passed"`
+ FailReason string `json:"failReason,omitempty"`
+}
+
+type phaseResult struct {
+ Kind string `json:"kind"`
+ FixedRequestRate float64 `json:"fixedRequestRate,omitempty"`
+ FixedBatchSize int `json:"fixedBatchSize,omitempty"`
+ Steps []stepResult `json:"steps"`
+ MaxBatchSize int `json:"maxBatchSize,omitempty"`
+ MaxRequestRate float64 `json:"maxRequestRate,omitempty"`
}
type finalReport struct {
- Tier string `json:"tier"`
- Mode string `json:"mode"`
- StartedAt string `json:"startedAt"`
- EndedAt string `json:"endedAt"`
- MaxSustainableEPS float64 `json:"maxSustainableEps"`
- Steps []stepResult `json:"steps"`
+ Tier string `json:"tier"`
+ Mode string `json:"mode"`
+ Signal string `json:"signal"`
+ Scenario string `json:"scenario"`
+ StartedAt string `json:"startedAt"`
+ EndedAt string `json:"endedAt"`
+ Phase1 *phaseResult `json:"phase1,omitempty"`
+ Phase2 *phaseResult `json:"phase2,omitempty"`
+ ReadProbe *readProbeResult `json:"readProbe,omitempty"`
+ MaxSustainableItemsPerSec float64 `json:"maxSustainableItemsPerSec,omitempty"`
+ MaxFillLevelPassed int64 `json:"maxFillLevelPassed,omitempty"`
}
-func (r *finalReport) computeBreakingPoint() {
- for i := len(r.Steps) - 1; i >= 0; i-- {
- if r.Steps[i].Passed {
- r.MaxSustainableEPS = r.Steps[i].ActualEPS
+func (r *finalReport) computeHeadline() {
+ if r.Phase2 != nil {
+ if r.Phase2.FixedBatchSize > 0 && r.Phase2.MaxRequestRate > 0 {
+ r.MaxSustainableItemsPerSec = float64(r.Phase2.FixedBatchSize) * r.Phase2.MaxRequestRate
return
}
+ // Fall back to the best actual measured throughput from any passing Phase 2
+ // step — useful when Phase 2 had to round down or skipped steps.
+ var best float64
+ for _, s := range r.Phase2.Steps {
+ if s.Passed && s.ActualItemsPerSec > best {
+ best = s.ActualItemsPerSec
+ }
+ }
+ r.MaxSustainableItemsPerSec = best
+ }
+ if r.ReadProbe != nil {
+ r.MaxFillLevelPassed = r.ReadProbe.MaxFillLevelPassed
}
}
-// runRamp drives the EPS ramp: hold a target rate for stepDuration, snapshot
-// stats, evaluate the breaking-point criteria, and either advance or stop.
-// Doubling cadence (100 -> 200 -> 400 -> ...) gets us to the cliff in <10 steps
-// for any realistic SUT, keeping total runtime bounded.
-func runRamp(
- ctx context.Context,
- cfg config,
- ingester *ingester,
- ingest *latencyTracker,
- reads map[string]*latencyTracker,
-) []stepResult {
- results := []stepResult{}
- target := cfg.initialEPS
-
- for stepNo := 1; target <= cfg.maxEPS; stepNo++ {
- ingester.SetRate(target)
-
- // Reset trackers at start of step so we measure only the new rate's
- // steady state, not the ramp-up transient from the previous step.
- ingest.SnapshotAndReset()
- for _, t := range reads {
- t.SnapshotAndReset()
- }
+// runBatchSizeRamp holds requestRate fixed (phase1FixedRate) and grows batch
+// size step by step. Stops at the first failing step. Returns a phaseResult
+// whose MaxBatchSize is the largest batch that passed.
+func runBatchSizeRamp(ctx context.Context, cfg config, ing *ingester, ingest *latencyTracker) phaseResult {
+ res := phaseResult{
+ Kind: "batch-size-ramp",
+ FixedRequestRate: cfg.phase1FixedRate,
+ }
- stepCtx, cancel := context.WithTimeout(ctx, cfg.stepDuration)
- start := time.Now()
- <-stepCtx.Done()
- cancel()
- elapsed := time.Since(start)
+ ing.SetRequestRate(cfg.phase1FixedRate)
- ingestSnap := ingest.SnapshotAndReset()
- readSnaps := map[string]latencySnapshot{}
- for name, t := range reads {
- readSnaps[name] = t.SnapshotAndReset()
+ for idx, batch := range cfg.phase1BatchSizes {
+ if ctx.Err() != nil {
+ break
}
-
- // Both target and actual must be in the same unit (traces/sec).
- // Rate limiter ticks per request (= per frame), so requests/sec × the
- // batch size gives the trace throughput on the wire. OTLP requests
- // carry spans rather than traces; we count them at the same rate
- // because the user-facing question is "events/sec the system swallowed"
- // regardless of which protocol carried them.
- actualEPS := 0.0
- if elapsed > 0 {
- actualEPS = float64(ingestSnap.OK+ingestSnap.Errors) / elapsed.Seconds() * tracesPerFrame
+ ing.SetBatchSize(batch)
+ s := runOneStep(ctx, cfg, ing, ingest, idx+1, batch, cfg.phase1FixedRate)
+ res.Steps = append(res.Steps, s)
+ fmt.Fprintf(stderrPrefix(), "phase1 step %d: batch=%d rate=%.1f items/s=%.0f p99=%.0fms err=%.2f%% passed=%t %s\n",
+ s.Step, s.BatchSize, s.RequestRate, s.ActualItemsPerSec, s.Ingest.P99, s.Ingest.ErrRate*100, s.Passed, s.FailReason)
+ if !s.Passed {
+ break
}
+ res.MaxBatchSize = batch
+ }
+
+ return res
+}
+
+// runRequestRateRamp holds batchSize fixed at min(phase1.MaxBatchSize, cfg.phase2BatchCap)
+// and grows request rate step by step.
+func runRequestRateRamp(ctx context.Context, cfg config, ing *ingester, ingest *latencyTracker, phase1 phaseResult) phaseResult {
+ batch := phase1.MaxBatchSize
+ if batch <= 0 {
+ batch = cfg.phase2BatchCap
+ }
+ if batch > cfg.phase2BatchCap {
+ batch = cfg.phase2BatchCap
+ }
+
+ res := phaseResult{
+ Kind: "request-rate-ramp",
+ FixedBatchSize: batch,
+ }
+ if batch <= 0 {
+ return res
+ }
- passed, reason := evaluate(cfg, ingestSnap, readSnaps)
+ ing.SetBatchSize(batch)
- res := stepResult{
- Step: stepNo,
- TargetEPS: target,
- ActualEPS: actualEPS,
- Ingest: ingestSnap,
- Reads: readSnaps,
- Passed: passed,
- FailReason: reason,
+ for idx, rate := range cfg.phase2RequestRates {
+ if ctx.Err() != nil {
+ break
}
- results = append(results, res)
- fmt.Fprintf(stderrPrefix(), "step %d: target=%.0f actual=%.0f ingest_p99=%.0fms ingest_err=%.2f%% passed=%t %s\n",
- stepNo, target, actualEPS, ingestSnap.P99, ingestSnap.ErrRate*100, passed, reason)
+ ing.SetRequestRate(rate)
+ s := runOneStep(ctx, cfg, ing, ingest, idx+1, batch, rate)
+ res.Steps = append(res.Steps, s)
+ fmt.Fprintf(stderrPrefix(), "phase2 step %d: batch=%d rate=%.1f items/s=%.0f p99=%.0fms err=%.2f%% passed=%t %s\n",
+ s.Step, s.BatchSize, s.RequestRate, s.ActualItemsPerSec, s.Ingest.P99, s.Ingest.ErrRate*100, s.Passed, s.FailReason)
+ if !s.Passed {
+ break
+ }
+ res.MaxRequestRate = rate
+ }
+
+ return res
+}
+
+// runOneStep resizes the worker pool for the new rate, holds the step for
+// stepDuration, then snapshots latency + item counters. The worker pool is
+// torn down between steps so worker count tracks the current rate.
+func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyTracker, stepNo, batchSize int, requestRate float64) stepResult {
+ ingest.SnapshotAndReset()
+ ing.SnapshotAndResetItems()
+
+ ing.Start(ctx)
+
+ stepCtx, cancel := context.WithTimeout(ctx, cfg.stepDuration)
+ start := time.Now()
+ <-stepCtx.Done()
+ cancel()
+ elapsed := time.Since(start)
+
+ ing.Stop()
- if !passed || ctx.Err() != nil {
- return results
+ snap := ingest.SnapshotAndReset()
+ attempted, rejected := ing.SnapshotAndResetItems()
+
+ var attemptedIps, actualIps float64
+ if elapsed > 0 {
+ attemptedIps = float64(attempted) / elapsed.Seconds()
+ actualItems := attempted - rejected
+ // Discount failed HTTP requests too — their items never made it in.
+ if attempted > 0 {
+ httpFailItems := int64(float64(snap.Errors) / float64(snap.OK+snap.Errors) * float64(attempted))
+ actualItems -= httpFailItems
+ }
+ if actualItems < 0 {
+ actualItems = 0
}
+ actualIps = float64(actualItems) / elapsed.Seconds()
+ }
+
+ passed, reason := evaluateStep(cfg, snap, attempted, rejected)
- target *= 2
+ return stepResult{
+ Step: stepNo,
+ BatchSize: batchSize,
+ RequestRate: requestRate,
+ AttemptedItemsPerSec: attemptedIps,
+ ActualItemsPerSec: actualIps,
+ Rejected: rejected,
+ Ingest: snap,
+ Passed: passed,
+ FailReason: reason,
}
- return results
}
-func evaluate(cfg config, ingest latencySnapshot, reads map[string]latencySnapshot) (bool, string) {
- if ingest.ErrRate > cfg.ingestErrThreshold {
- return false, fmt.Sprintf("ingest error rate %.2f%% > %.2f%% threshold", ingest.ErrRate*100, cfg.ingestErrThreshold*100)
+// evaluateStep combines HTTP-level error rate with OTLP partial-success
+// rejections. A SUT that returns 200 OK but rejects half the items is failing
+// just as surely as one that 500s.
+func evaluateStep(cfg config, snap latencySnapshot, attempted, rejected int64) (bool, string) {
+ totalReq := snap.OK + snap.Errors
+ if totalReq == 0 {
+ return false, "no requests completed"
}
- for name, s := range reads {
- // If a read endpoint never returned a single OK response during this
- // step the SUT is effectively unavailable for reads; treat that as a
- // hard fail even though P99 reads as 0 from the empty histogram.
- if s.OK == 0 && s.Errors > 0 {
- return false, fmt.Sprintf("read endpoint %q served zero OK responses", name)
- }
- if s.P99 > cfg.readP99ThresholdMs {
- return false, fmt.Sprintf("read endpoint %q p99 = %.0fms > %.0fms threshold", name, s.P99, cfg.readP99ThresholdMs)
- }
+ httpErrRate := float64(snap.Errors) / float64(totalReq)
+ var rejectRate float64
+ if attempted > 0 {
+ rejectRate = float64(rejected) / float64(attempted)
+ }
+ combined := httpErrRate + rejectRate
+ if combined > cfg.ingestErrThreshold {
+ return false, fmt.Sprintf("combined error rate %.2f%% (http %.2f%% + rejected %.2f%%) > %.2f%% threshold",
+ combined*100, httpErrRate*100, rejectRate*100, cfg.ingestErrThreshold*100)
}
return true, ""
}
diff --git a/benchmarks/loadgen/read_probe.go b/benchmarks/loadgen/read_probe.go
new file mode 100644
index 00000000..1775ff01
--- /dev/null
+++ b/benchmarks/loadgen/read_probe.go
@@ -0,0 +1,224 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+type readProbeStep struct {
+ FillLevelTarget int64 `json:"fillLevelTarget"`
+ RowsIngested int64 `json:"rowsIngested"`
+ IngestSecondsElapsed float64 `json:"ingestSecondsElapsed"`
+ ReadLatencyMs float64 `json:"readLatencyMs"`
+ ReadOk bool `json:"readOk"`
+ Passed bool `json:"passed"`
+ FailReason string `json:"failReason,omitempty"`
+}
+
+type readProbeResult struct {
+ ReadPath string `json:"readPath"`
+ ReadThresholdMs int `json:"readThresholdMs"`
+ SettleSeconds int `json:"settleSeconds"`
+ FillBatchSize int `json:"fillBatchSize"`
+ FillRequestRate float64 `json:"fillRequestRate"`
+ Steps []readProbeStep `json:"steps"`
+ MaxFillLevelPassed int64 `json:"maxFillLevelPassed"`
+}
+
+// runReadProbe walks the configured fill levels. For each level it ingests
+// rows until totalIngested >= target, settles for cfg.settleSeconds, then
+// issues one read probe. If the probe times out, errors, or exceeds
+// cfg.readThresholdMs, the step fails and the loop stops without ingesting
+// further.
+func runReadProbe(ctx context.Context, cfg config, ing *ingester, ingestStats *latencyTracker, client *http.Client) readProbeResult {
+ res := readProbeResult{
+ ReadPath: readPathForSignal(cfg.signal),
+ ReadThresholdMs: cfg.readThresholdMs,
+ SettleSeconds: int(cfg.settleSeconds.Seconds()),
+ FillBatchSize: cfg.fillBatchSize,
+ FillRequestRate: cfg.fillRequestRate,
+ }
+
+ ing.SetBatchSize(cfg.fillBatchSize)
+ ing.SetRequestRate(cfg.fillRequestRate)
+
+ // Reset the ingester counters before starting so totalIngested reflects
+ // only what this scenario sent.
+ ing.SnapshotAndResetItems()
+ ingestStats.SnapshotAndReset()
+
+ var totalIngested int64
+
+ for _, target := range cfg.fillLevels {
+ if ctx.Err() != nil {
+ break
+ }
+ step := readProbeStep{FillLevelTarget: target}
+
+ if totalIngested < target {
+ fillStart := time.Now()
+ ing.Start(ctx)
+ pollFillProgress(ctx, ing, &totalIngested, target)
+ ing.Stop()
+ step.IngestSecondsElapsed = time.Since(fillStart).Seconds()
+ }
+ step.RowsIngested = totalIngested
+
+ // Drain whatever bumped between Stop and Snapshot.
+ extraAttempted, _ := ing.SnapshotAndResetItems()
+ totalIngested += extraAttempted
+ step.RowsIngested = totalIngested
+
+ fmt.Fprintf(stderrPrefix(), "read-probe fill=%d rows reached in %.1fs (signal=%s) — settling %ds\n",
+ step.RowsIngested, step.IngestSecondsElapsed, cfg.signal, res.SettleSeconds)
+
+ select {
+ case <-time.After(cfg.settleSeconds):
+ case <-ctx.Done():
+ }
+ if ctx.Err() != nil {
+ res.Steps = append(res.Steps, step)
+ break
+ }
+
+ latencyMs, readErr := probeRead(ctx, client, cfg)
+ step.ReadLatencyMs = latencyMs
+ switch {
+ case readErr != nil:
+ step.ReadOk = false
+ step.Passed = false
+ step.FailReason = fmt.Sprintf("read error: %v (latency %.0fms)", readErr, latencyMs)
+ case latencyMs > float64(cfg.readThresholdMs):
+ step.ReadOk = true
+ step.Passed = false
+ step.FailReason = fmt.Sprintf("read latency %.0fms > %dms threshold", latencyMs, cfg.readThresholdMs)
+ default:
+ step.ReadOk = true
+ step.Passed = true
+ res.MaxFillLevelPassed = target
+ }
+
+ fmt.Fprintf(stderrPrefix(), "read-probe target=%d read=%.0fms ok=%t passed=%t %s\n",
+ target, latencyMs, step.ReadOk, step.Passed, step.FailReason)
+ res.Steps = append(res.Steps, step)
+ if !step.Passed {
+ break
+ }
+ }
+
+ return res
+}
+
+// pollFillProgress drains attempted-item counters from the ingester until the
+// target is reached or the context cancels. Sub-second polling keeps overshoot
+// small (at fill-batch=8192 × 100 req/s the loadgen sends ~800k items/sec, so
+// 200ms granularity overshoots by ≤160k items — negligible at 100M fill).
+func pollFillProgress(ctx context.Context, ing *ingester, totalIngested *int64, target int64) {
+ tick := time.NewTicker(200 * time.Millisecond)
+ defer tick.Stop()
+ for *totalIngested < target {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ attempted, _ := ing.SnapshotAndResetItems()
+ *totalIngested += attempted
+ }
+ }
+}
+
+func readPathForSignal(signal string) string {
+ switch signal {
+ case "spans":
+ return "/api/endpoints/grouped"
+ case "metrics":
+ return "/api/metrics/application"
+ case "logs":
+ return "/api/logs"
+ }
+ return ""
+}
+
+// probeRead issues one HTTP read against the signal-specific endpoint and
+// returns wall-clock latency in ms plus any error. The request is hard-capped
+// at threshold + 1s so a hanging SUT can't deadlock the loop.
+func probeRead(ctx context.Context, client *http.Client, cfg config) (float64, error) {
+ now := time.Now().UTC()
+ fromDate := now.Add(-24 * time.Hour).Format(time.RFC3339)
+ toDate := now.Format(time.RFC3339)
+
+ probeCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.readThresholdMs+1000)*time.Millisecond)
+ defer cancel()
+
+ var req *http.Request
+ var err error
+ switch cfg.signal {
+ case "spans":
+ body, _ := json.Marshal(map[string]any{
+ "fromDate": fromDate,
+ "toDate": toDate,
+ "orderBy": "count",
+ "sortDirection": "desc",
+ "pagination": map[string]int{"page": 1, "pageSize": 50},
+ "search": "",
+ })
+ u, _ := url.Parse(cfg.target + "/api/endpoints/grouped")
+ q := u.Query()
+ q.Set("projectId", cfg.projectId)
+ u.RawQuery = q.Encode()
+ req, err = http.NewRequestWithContext(probeCtx, http.MethodPost, u.String(), bytes.NewReader(body))
+ if err != nil {
+ return 0, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ case "metrics":
+ u, _ := url.Parse(cfg.target + "/api/metrics/application")
+ q := u.Query()
+ q.Set("projectId", cfg.projectId)
+ q.Set("fromDate", fromDate)
+ q.Set("toDate", toDate)
+ u.RawQuery = q.Encode()
+ req, err = http.NewRequestWithContext(probeCtx, http.MethodGet, u.String(), nil)
+ if err != nil {
+ return 0, err
+ }
+ case "logs":
+ body, _ := json.Marshal(map[string]any{
+ "fromDate": fromDate,
+ "toDate": toDate,
+ "orderBy": "timestamp desc",
+ "pagination": map[string]int{"page": 1, "pageSize": 50},
+ })
+ u, _ := url.Parse(cfg.target + "/api/logs")
+ q := u.Query()
+ q.Set("projectId", cfg.projectId)
+ u.RawQuery = q.Encode()
+ req, err = http.NewRequestWithContext(probeCtx, http.MethodPost, u.String(), bytes.NewReader(body))
+ if err != nil {
+ return 0, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ default:
+ return 0, fmt.Errorf("no read endpoint configured for signal %q", cfg.signal)
+ }
+ req.Header.Set("Authorization", "Bearer "+cfg.jwt)
+
+ start := time.Now()
+ resp, err := client.Do(req)
+ elapsed := time.Since(start).Seconds() * 1000
+ if err != nil {
+ return elapsed, err
+ }
+ defer resp.Body.Close()
+ _, _ = io.Copy(io.Discard, resp.Body)
+ if resp.StatusCode >= 400 {
+ return elapsed, fmt.Errorf("status %d", resp.StatusCode)
+ }
+ return elapsed, nil
+}
diff --git a/benchmarks/loadgen/reads.go b/benchmarks/loadgen/reads.go
deleted file mode 100644
index d77cb6ec..00000000
--- a/benchmarks/loadgen/reads.go
+++ /dev/null
@@ -1,204 +0,0 @@
-package main
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "net/url"
- "sync"
- "time"
-)
-
-type reader struct {
- cfg config
- client *http.Client
- stats map[string]*latencyTracker
- ingester *ingester
-}
-
-func newReader(cfg config, client *http.Client, stats map[string]*latencyTracker) *reader {
- return &reader{cfg: cfg, client: client, stats: stats}
-}
-
-// attachIngester gives the reader access to a sample session id so it can hit
-// /api/sessions/:id/recording with an id that actually exists.
-func (r *reader) attachIngester(i *ingester) { r.ingester = i }
-
-type readSpec struct {
- name string
- method string
- path string
- body func() any
-}
-
-func (r *reader) specs() []readSpec {
- last24h := func() (string, string) {
- now := time.Now().UTC()
- return now.Add(-24 * time.Hour).Format(time.RFC3339), now.Format(time.RFC3339)
- }
- last1h := func() (string, string) {
- now := time.Now().UTC()
- return now.Add(-1 * time.Hour).Format(time.RFC3339), now.Format(time.RFC3339)
- }
- return []readSpec{
- {
- name: "endpoints_grouped", method: "POST", path: "/api/endpoints/grouped",
- body: func() any {
- f, t := last24h()
- return map[string]any{
- "fromDate": f,
- "toDate": t,
- "orderBy": "count",
- "sortDirection": "desc",
- "pagination": map[string]int{"page": 1, "pageSize": 50},
- "search": "",
- }
- },
- },
- {
- name: "exceptions_grouped", method: "POST", path: "/api/exception-stack-traces",
- body: func() any {
- f, t := last24h()
- return map[string]any{
- "fromDate": f,
- "toDate": t,
- "orderBy": "count desc",
- "pagination": map[string]int{"page": 1, "pageSize": 50},
- "search": "",
- "searchType": "all",
- "includeArchived": false,
- }
- },
- },
- {name: "dashboard_overview", method: "GET", path: "/api/dashboard/overview"},
- {name: "logs", method: "POST", path: "/api/logs", body: func() any {
- f, t := last1h()
- return map[string]any{
- "fromDate": f,
- "toDate": t,
- "orderBy": "timestamp desc",
- "pagination": map[string]int{"page": 1, "pageSize": 50},
- }
- }},
- // session_recording handled separately because the URL depends on a
- // live session id surfaced by the ingester.
- }
-}
-
-func (r *reader) run(ctx context.Context) {
- var wg sync.WaitGroup
- for _, spec := range r.specs() {
- spec := spec
- wg.Add(1)
- go func() {
- defer wg.Done()
- r.loopSpec(ctx, spec)
- }()
- }
- wg.Add(1)
- go func() {
- defer wg.Done()
- r.loopRecording(ctx)
- }()
- wg.Wait()
-}
-
-func (r *reader) loopSpec(ctx context.Context, spec readSpec) {
- interval := time.Duration(float64(time.Second) / r.cfg.readRPS)
- if interval < 10*time.Millisecond {
- interval = 10 * time.Millisecond
- }
- t := time.NewTicker(interval)
- defer t.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-t.C:
- r.doOne(ctx, spec)
- }
- }
-}
-
-func (r *reader) loopRecording(ctx context.Context) {
- interval := time.Duration(float64(time.Second) / r.cfg.readRPS)
- if interval < 10*time.Millisecond {
- interval = 10 * time.Millisecond
- }
- t := time.NewTicker(interval)
- defer t.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-t.C:
- sid := ""
- if r.ingester != nil {
- sid = r.ingester.SampleSessionId()
- }
- if sid == "" {
- // Nothing seeded yet — quietly skip; don't record as ok or err.
- continue
- }
- r.doOne(ctx, readSpec{
- name: "session_recording",
- method: "GET",
- path: "/api/sessions/" + sid + "/recording",
- })
- }
- }
-}
-
-func (r *reader) doOne(ctx context.Context, spec readSpec) {
- tracker, ok := r.stats[spec.name]
- if !ok {
- return
- }
-
- u, err := url.Parse(r.cfg.target + spec.path)
- if err != nil {
- tracker.Record(0, err)
- return
- }
- q := u.Query()
- q.Set("projectId", r.cfg.projectId)
- u.RawQuery = q.Encode()
-
- var body []byte
- if spec.body != nil {
- body, err = json.Marshal(spec.body())
- if err != nil {
- tracker.Record(0, err)
- return
- }
- }
-
- req, err := http.NewRequestWithContext(ctx, spec.method, u.String(), bytes.NewReader(body))
- if err != nil {
- tracker.Record(0, err)
- return
- }
- if body != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- if r.cfg.jwt != "" {
- req.Header.Set("Authorization", "Bearer "+r.cfg.jwt)
- }
-
- start := time.Now()
- resp, err := r.client.Do(req)
- elapsed := time.Since(start)
- if err != nil {
- tracker.Record(elapsed.Seconds()*1000, err)
- return
- }
- defer resp.Body.Close()
- _, _ = readAndDiscard(resp.Body)
- if resp.StatusCode >= 400 {
- tracker.Record(elapsed.Seconds()*1000, fmt.Errorf("status %d", resp.StatusCode))
- return
- }
- tracker.Record(elapsed.Seconds()*1000, nil)
-}
diff --git a/benchmarks/loadgen/report.go b/benchmarks/loadgen/report.go
deleted file mode 100644
index d56cd7f6..00000000
--- a/benchmarks/loadgen/report.go
+++ /dev/null
@@ -1,285 +0,0 @@
-package main
-
-import (
- "bytes"
- "compress/gzip"
- "context"
- "encoding/json"
- "fmt"
- "math/rand"
- "net/http"
- "time"
-
- "github.com/google/uuid"
-)
-
-type rTrace struct {
- Id string `json:"id"`
- Endpoint string `json:"endpoint"`
- Duration int64 `json:"duration"` // nanoseconds
- RecordedAt time.Time `json:"recordedAt"`
- StatusCode int `json:"statusCode"`
- BodySize int `json:"bodySize"`
- ClientIP string `json:"clientIP"`
- Attributes map[string]string `json:"attributes"`
- Spans []rSpan `json:"spans"`
- IsTask bool `json:"isTask"`
- DistributedTraceId string `json:"distributedTraceId"`
-}
-
-type rSpan struct {
- Id string `json:"id"`
- Name string `json:"name"`
- StartTime time.Time `json:"startTime"`
- Duration int64 `json:"duration"`
-}
-
-type rSession struct {
- Id string `json:"id"`
- StartedAt time.Time `json:"startedAt"`
- ClientIP string `json:"clientIP"`
- Attributes map[string]string `json:"attributes"`
- DistributedTraceId string `json:"distributedTraceId,omitempty"`
-}
-
-type rRecording struct {
- ExceptionId string `json:"exceptionId"`
- SessionId string `json:"sessionId,omitempty"`
- SegmentIndex int32 `json:"segmentIndex"`
- Events json.RawMessage `json:"events"`
- StartedAt *time.Time `json:"startedAt,omitempty"`
- EndedAt *time.Time `json:"endedAt,omitempty"`
-}
-
-type rException struct {
- IsTask bool `json:"isTask"`
- StackTrace string `json:"stackTrace"`
- RecordedAt time.Time `json:"recordedAt"`
- Attributes map[string]string `json:"attributes"`
- IsMessage bool `json:"isMessage"`
-}
-
-type rMetric struct {
- Name string `json:"name"`
- Value float64 `json:"value"`
- RecordedAt time.Time `json:"recordedAt"`
- Tags map[string]string `json:"tags,omitempty"`
-}
-
-type rFrame struct {
- StackTraces []rException `json:"stackTraces"`
- Metrics []rMetric `json:"metrics"`
- Traces []rTrace `json:"traces"`
- SessionRecordings []rRecording `json:"sessionRecordings"`
- Sessions []rSession `json:"sessions"`
-}
-
-type rReport struct {
- CollectionFrames []rFrame `json:"collectionFrames"`
- AppVersion string `json:"appVersion"`
- ServerName string `json:"serverName"`
-}
-
-var endpointPaths = []string{
- "GET /api/users", "POST /api/users", "GET /api/orders", "POST /api/orders",
- "GET /api/products/:id", "PUT /api/products/:id", "GET /api/search",
- "POST /api/checkout", "GET /api/cart", "DELETE /api/cart/:id",
- "GET /api/auth/me", "POST /api/auth/login", "GET /api/health",
-}
-
-// sendReportFrame builds one CollectionFrame, POSTs it gzipped to /api/report,
-// records latency on the ingest tracker, and returns a sample session id (when
-// one was included in the frame) so the reader can later query its recording.
-func sendReportFrame(ctx context.Context, client *http.Client, cfg config, rng *rand.Rand, stats *latencyTracker) string {
- frame := buildFrame(rng)
-
- body, err := encodeFrame(rReport{
- CollectionFrames: []rFrame{frame},
- AppVersion: "bench-1.0.0",
- ServerName: fmt.Sprintf("bench-%s-%s", cfg.tier, cfg.mode),
- })
- if err != nil {
- stats.Record(0, err)
- return ""
- }
-
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.target+"/api/report", bytes.NewReader(body))
- if err != nil {
- stats.Record(0, err)
- return ""
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Content-Encoding", "gzip")
- req.Header.Set("Authorization", "Bearer "+cfg.projectToken)
-
- start := time.Now()
- resp, err := client.Do(req)
- elapsed := time.Since(start)
- if err != nil {
- stats.Record(elapsed.Seconds()*1000, err)
- return ""
- }
- defer resp.Body.Close()
- // Drain so the connection can be reused — keep-alive is critical at high
- // frame rates; not draining leaves connections in CLOSE_WAIT.
- _, _ = readAndDiscard(resp.Body)
-
- if resp.StatusCode >= 400 {
- stats.Record(elapsed.Seconds()*1000, fmt.Errorf("status %d", resp.StatusCode))
- return ""
- }
- stats.Record(elapsed.Seconds()*1000, nil)
-
- if len(frame.Sessions) > 0 {
- return frame.Sessions[0].Id
- }
- return ""
-}
-
-func buildFrame(rng *rand.Rand) rFrame {
- now := time.Now().UTC()
- frame := rFrame{
- Traces: make([]rTrace, 0, tracesPerFrame),
- Metrics: make([]rMetric, 0, 5),
- Sessions: nil,
- StackTraces: nil,
- }
-
- for i := 0; i < tracesPerFrame; i++ {
- t := rTrace{
- Id: uuid.NewString(),
- Endpoint: endpointPaths[rng.Intn(len(endpointPaths))],
- Duration: int64(time.Duration(10+rng.Intn(990)) * time.Millisecond), // 10-1000ms
- RecordedAt: now.Add(-time.Duration(rng.Intn(5000)) * time.Millisecond),
- StatusCode: pickStatus(rng),
- BodySize: 200 + rng.Intn(8000),
- ClientIP: "192.0.2.1",
- Attributes: map[string]string{"region": "bench", "tier": "x"},
- Spans: buildSpans(rng, now),
- IsTask: rng.Float64() < 0.10,
- }
- frame.Traces = append(frame.Traces, t)
- }
-
- for i := 0; i < 5; i++ {
- frame.Metrics = append(frame.Metrics, rMetric{
- Name: "bench.metric." + []string{"cpu", "mem", "qps", "lat", "errs"}[i],
- Value: rng.Float64() * 100,
- RecordedAt: now,
- })
- }
-
- if rng.Float64() < recordingChance {
- sid := uuid.NewString()
- started := now.Add(-2 * time.Second)
- ended := now
- frame.Sessions = []rSession{{
- Id: sid,
- StartedAt: started,
- ClientIP: "192.0.2.1",
- Attributes: map[string]string{"browser": "bench"},
- }}
- frame.SessionRecordings = []rRecording{{
- ExceptionId: uuid.NewString(),
- SessionId: sid,
- SegmentIndex: 0,
- Events: fakeRRWeb(rng),
- StartedAt: &started,
- EndedAt: &ended,
- }}
- } else if rng.Float64() < 0.2 {
- // Even without a recording, ship occasional sessions so the read mix
- // always has at least one session id to query.
- sid := uuid.NewString()
- frame.Sessions = []rSession{{
- Id: sid,
- StartedAt: now,
- ClientIP: "192.0.2.1",
- Attributes: map[string]string{"browser": "bench"},
- }}
- }
-
- if rng.Float64() < exceptionChance {
- frame.StackTraces = []rException{{
- IsTask: false,
- StackTrace: "RuntimeError: bench-synthetic\n at bench:1\n at bench:2",
- RecordedAt: now,
- Attributes: map[string]string{"env": "bench"},
- }}
- }
-
- return frame
-}
-
-func buildSpans(rng *rand.Rand, now time.Time) []rSpan {
- n := 2 + rng.Intn(4) // 2-5 spans
- spans := make([]rSpan, n)
- for i := range spans {
- spans[i] = rSpan{
- Id: uuid.NewString(),
- Name: []string{"db.query", "http.call", "cache.get", "render", "json.encode"}[rng.Intn(5)],
- StartTime: now.Add(-time.Duration(rng.Intn(500)) * time.Millisecond),
- Duration: int64(time.Duration(1+rng.Intn(200)) * time.Millisecond),
- }
- }
- return spans
-}
-
-func pickStatus(rng *rand.Rand) int {
- r := rng.Float64()
- switch {
- case r < 0.92:
- return 200
- case r < 0.95:
- return 201
- case r < 0.98:
- return 404
- default:
- return 500
- }
-}
-
-// fakeRRWeb produces a ~100KB JSON array shaped like rrweb events. The backend
-// stores this opaquely in S3/disk without inspecting the structure, so a valid
-// JSON array of arbitrary size is sufficient to exercise the storage path.
-func fakeRRWeb(rng *rand.Rand) json.RawMessage {
- var buf bytes.Buffer
- buf.WriteString("[")
- const targetBytes = 100_000
- first := true
- for buf.Len() < targetBytes {
- if !first {
- buf.WriteString(",")
- }
- first = false
- fmt.Fprintf(&buf, `{"type":%d,"timestamp":%d,"data":{"href":"https://bench.local/page/%d","text":"%s"}}`,
- 2+rng.Intn(4), time.Now().UnixMilli(), rng.Intn(10000), randomString(rng, 64))
- }
- buf.WriteString("]")
- return buf.Bytes()
-}
-
-func randomString(rng *rand.Rand, n int) string {
- const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
- b := make([]byte, n)
- for i := range b {
- b[i] = charset[rng.Intn(len(charset))]
- }
- return string(b)
-}
-
-func encodeFrame(r rReport) ([]byte, error) {
- js, err := json.Marshal(r)
- if err != nil {
- return nil, err
- }
- var gz bytes.Buffer
- w := gzip.NewWriter(&gz)
- if _, err := w.Write(js); err != nil {
- return nil, err
- }
- if err := w.Close(); err != nil {
- return nil, err
- }
- return gz.Bytes(), nil
-}
diff --git a/benchmarks/loadgen/stats.go b/benchmarks/loadgen/stats.go
index 13825297..4d09615d 100644
--- a/benchmarks/loadgen/stats.go
+++ b/benchmarks/loadgen/stats.go
@@ -13,7 +13,10 @@ type latencyTracker struct {
}
func newLatencyTracker() *latencyTracker {
- return &latencyTracker{samples: make([]float64, 0, 8192)}
+ // 65536 covers 400 req/sec × 120s step without reallocation; the higher
+ // rate ramp steps are where percentile noise hurts most, so amortize the
+ // allocation up front rather than growing during the step.
+ return &latencyTracker{samples: make([]float64, 0, 65536)}
}
func (l *latencyTracker) Record(milliseconds float64, err error) {
diff --git a/benchmarks/scripts/chart.py b/benchmarks/scripts/chart.py
index cdb8f321..67e373ad 100755
--- a/benchmarks/scripts/chart.py
+++ b/benchmarks/scripts/chart.py
@@ -1,20 +1,22 @@
#!/usr/bin/env python3
-"""Render hardware-vs-breaking-point charts from a directory of loadgen JSONs.
+"""Render per-signal benchmark charts from a directory of loadgen JSONs.
Inputs: a directory containing N JSON files (one per matrix entry), each in
-the schema emitted by benchmarks/loadgen/. Order-independent.
-
-Outputs (written into the same directory):
- - chart.png Bar: max sustainable EPS per tier, two bars per tier
- (sqlite vs pgch). The headline.
- - chart-detail.png Lines: read P99 (ms) vs ingest EPS, one line per
- (tier, mode). Shows how reads degrade as ingest climbs.
- - summary.md Markdown table for human consumption / docs source.
+the schema emitted by benchmarks/loadgen/. Files without a "signal" field
+(old pre-OTLP-split format) are skipped with a log line.
+
+Outputs depend on which scenarios are present in the directory:
+ Throughput scenario:
+ - chart-spans.png / chart-metrics.png / chart-logs.png bar: max items/sec
+ - chart-detail-<sig>.png line: ingest p99 vs request rate
+ Read-probe scenario:
+ - chart-readprobe-<sig>.png line: read latency vs fill level
+ Always:
+ - summary.md tables per signal/scenario
"""
import json
import sys
-from collections import defaultdict
from pathlib import Path
import matplotlib
@@ -22,11 +24,20 @@ import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
-# Stable left-to-right ordering of tiers regardless of how the matrix runs.
TIER_ORDER = ["ccx13", "ccx23", "ccx33", "ccx43"]
MODE_ORDER = ["sqlite", "pgch"]
+SIGNALS = ["spans", "metrics", "logs"]
MODE_COLORS = {"sqlite": "#4f9fff", "pgch": "#ff9f4f"}
-READ_P99_BUDGET_MS = 3000
+ITEM_LABEL = {
+ "spans": "spans/sec",
+ "metrics": "data points/sec",
+ "logs": "log records/sec",
+}
+ROW_LABEL = {
+ "spans": "spans rows",
+ "metrics": "metric_points rows",
+ "logs": "log_records rows",
+}
def load_runs(results_dir: Path) -> list[dict]:
@@ -34,6 +45,16 @@ def load_runs(results_dir: Path) -> list[dict]:
for p in sorted(results_dir.glob("*.json")):
with p.open() as fh:
doc = json.load(fh)
+ if "signal" not in doc:
+ print(f"skipping {p.name}: missing 'signal' field (pre-OTLP-split format)", file=sys.stderr)
+ continue
+ if doc["signal"] not in SIGNALS:
+ print(f"skipping {p.name}: unknown signal {doc['signal']!r}", file=sys.stderr)
+ continue
+ doc.setdefault("scenario", "throughput")
+ if doc["scenario"] not in ("throughput", "read-probe"):
+ print(f"skipping {p.name}: unknown scenario {doc['scenario']!r}", file=sys.stderr)
+ continue
doc["_path"] = p
runs.append(doc)
return runs
@@ -47,7 +68,11 @@ def mode_rank(m: str) -> int:
return MODE_ORDER.index(m) if m in MODE_ORDER else len(MODE_ORDER)
-def render_bar(runs: list[dict], out: Path) -> None:
+def render_throughput_bar(runs: list[dict], signal: str, out: Path) -> None:
+ runs = [r for r in runs if r["signal"] == signal and r["scenario"] == "throughput"]
+ if not runs:
+ return
+
fig, ax = plt.subplots(figsize=(9, 5))
tiers_present = sorted({r["tier"] for r in runs}, key=tier_rank)
modes_present = sorted({r["mode"] for r in runs}, key=mode_rank)
@@ -59,7 +84,7 @@ def render_bar(runs: list[dict], out: Path) -> None:
ys = []
for tier in tiers_present:
match = [r for r in runs if r["tier"] == tier and r["mode"] == mode]
- ys.append(match[0]["maxSustainableEps"] if match else 0)
+ ys.append(match[0].get("maxSustainableItemsPerSec", 0) if match else 0)
offsets = [xi + (mi - (len(modes_present) - 1) / 2) * width for xi in x]
bars = ax.bar(offsets, ys, width=width, label=mode, color=MODE_COLORS.get(mode, "#777"))
for b, y in zip(bars, ys):
@@ -69,9 +94,9 @@ def render_bar(runs: list[dict], out: Path) -> None:
ax.set_xticks(x)
ax.set_xticklabels(tiers_present)
- ax.set_ylabel("Max sustainable traces/sec")
- ax.set_title("Traceway: max sustainable ingest by hardware tier\n"
- f"(failure = ingest err > 5% OR any read p99 > {READ_P99_BUDGET_MS}ms)")
+ ax.set_ylabel(f"Max sustainable {ITEM_LABEL[signal]}")
+ ax.set_title(f"Traceway: max sustainable {signal} ingest by hardware tier\n"
+ "(failure = combined HTTP error + OTLP rejected > 5%)")
ax.legend(title="DB mode")
ax.grid(axis="y", linestyle=":", alpha=0.4)
fig.tight_layout()
@@ -79,26 +104,30 @@ def render_bar(runs: list[dict], out: Path) -> None:
plt.close(fig)
-def render_detail(runs: list[dict], out: Path) -> None:
+def render_throughput_detail(runs: list[dict], signal: str, out: Path) -> None:
+ runs = [r for r in runs if r["signal"] == signal and r["scenario"] == "throughput"]
+ if not runs:
+ return
+
fig, ax = plt.subplots(figsize=(10, 6))
+ plotted = False
for run in sorted(runs, key=lambda r: (tier_rank(r["tier"]), mode_rank(r["mode"]))):
- xs, ys = [], []
- for s in run.get("steps", []):
- if not s.get("reads"):
- continue
- xs.append(s["actualEps"])
- # Worst read p99 across all read endpoints — that's what defines the cliff.
- ys.append(max((rd.get("p99", 0) for rd in s["reads"].values()), default=0))
- if xs:
- label = f"{run['tier']} / {run['mode']}"
- ax.plot(xs, ys, marker="o", label=label)
-
- ax.axhline(READ_P99_BUDGET_MS, linestyle="--", color="#cc3333", alpha=0.6,
- label=f"P99 budget ({READ_P99_BUDGET_MS}ms)")
- ax.set_xlabel("Actual ingest rate (traces/sec)")
- ax.set_ylabel("Worst read endpoint P99 (ms)")
- ax.set_title("Read latency degradation under increasing ingest load")
+ steps = (run.get("phase2") or {}).get("steps") or []
+ xs = [s["requestRate"] for s in steps if s.get("ingest")]
+ ys = [s["ingest"]["p99"] for s in steps if s.get("ingest")]
+ if not xs:
+ continue
+ ax.plot(xs, ys, marker="o", label=f"{run['tier']} / {run['mode']}")
+ plotted = True
+
+ if not plotted:
+ plt.close(fig)
+ return
+
+ ax.set_xlabel("Phase 2 request rate (req/sec)")
+ ax.set_ylabel("Ingest P99 latency (ms)")
+ ax.set_title(f"Ingest latency vs request rate — {signal}")
ax.set_xscale("log")
ax.set_yscale("log")
ax.grid(True, which="both", linestyle=":", alpha=0.4)
@@ -108,30 +137,116 @@ def render_detail(runs: list[dict], out: Path) -> None:
plt.close(fig)
+def render_readprobe(runs: list[dict], signal: str, out: Path) -> None:
+ runs = [r for r in runs if r["signal"] == signal and r["scenario"] == "read-probe"]
+ if not runs:
+ return
+
+ fig, ax = plt.subplots(figsize=(10, 6))
+ plotted = False
+ threshold_ms = 5000
+
+ for run in sorted(runs, key=lambda r: (tier_rank(r["tier"]), mode_rank(r["mode"]))):
+ rp = run.get("readProbe") or {}
+ threshold_ms = rp.get("readThresholdMs", threshold_ms)
+ steps = rp.get("steps") or []
+ xs = [s["rowsIngested"] for s in steps]
+ ys = [s["readLatencyMs"] for s in steps]
+ if not xs:
+ continue
+ ax.plot(xs, ys, marker="o", label=f"{run['tier']} / {run['mode']}")
+ plotted = True
+
+ if not plotted:
+ plt.close(fig)
+ return
+
+ ax.axhline(threshold_ms, linestyle="--", color="#cc3333", alpha=0.7,
+ label=f"threshold ({threshold_ms}ms)")
+ ax.set_xlabel(f"{ROW_LABEL[signal]} (ingested before probe)")
+ ax.set_ylabel(f"Read latency on {readPathForSignal(signal)} (ms)")
+ ax.set_title(f"Read latency vs ingested rows — {signal}")
+ ax.set_xscale("log")
+ ax.set_yscale("log")
+ ax.grid(True, which="both", linestyle=":", alpha=0.4)
+ ax.legend(loc="upper left", fontsize=9)
+ fig.tight_layout()
+ fig.savefig(out, dpi=130)
+ plt.close(fig)
+
+
+def readPathForSignal(signal: str) -> str:
+ return {
+ "spans": "/api/endpoints/grouped",
+ "metrics": "/api/metrics/application",
+ "logs": "/api/logs",
+ }.get(signal, "")
+
+
def render_summary(runs: list[dict], out: Path) -> None:
lines = ["# Traceway hardware benchmark — summary", ""]
lines.append(f"Runs analyzed: {len(runs)}")
lines.append("")
- lines.append("| Tier | Mode | Max EPS | Ingest p99 @max (ms) | Worst read p99 @max (ms) | Steps |")
- lines.append("|------|------|---------|----------------------|---------------------------|-------|")
- for run in sorted(runs, key=lambda r: (tier_rank(r["tier"]), mode_rank(r["mode"]))):
- max_eps = int(run.get("maxSustainableEps", 0))
- last_pass = None
- for s in reversed(run.get("steps", [])):
- if s.get("passed"):
- last_pass = s
- break
- ingest_p99 = int(last_pass["ingest"]["p99"]) if last_pass else 0
- worst_read = 0
- if last_pass and last_pass.get("reads"):
- worst_read = int(max(rd.get("p99", 0) for rd in last_pass["reads"].values()))
- lines.append(f"| {run['tier']} | {run['mode']} | {max_eps:,} | {ingest_p99} | {worst_read} | {len(run.get('steps', []))} |")
+ throughput_runs = [r for r in runs if r["scenario"] == "throughput"]
+ if throughput_runs:
+ lines.append("## Throughput scenario")
+ lines.append("")
+ lines.append("Failure threshold: combined HTTP error rate + OTLP rejected items > 5% of attempted.")
+ lines.append("")
+ for signal in SIGNALS:
+ sig_runs = [r for r in throughput_runs if r["signal"] == signal]
+ if not sig_runs:
+ continue
+ lines.append(f"### {signal.capitalize()}")
+ lines.append("")
+ lines.append(f"| Tier | Mode | Max {ITEM_LABEL[signal]} | Phase 1 max batch | Phase 2 max req/sec | Ingest P99 @ max (ms) |")
+ lines.append("|------|------|---------|-------------------|---------------------|------------------------|")
+ for run in sorted(sig_runs, key=lambda r: (tier_rank(r["tier"]), mode_rank(r["mode"]))):
+ max_items = int(run.get("maxSustainableItemsPerSec", 0))
+ max_batch = (run.get("phase1") or {}).get("maxBatchSize", 0)
+ max_rate = (run.get("phase2") or {}).get("maxRequestRate", 0)
+ last_pass = None
+ for s in reversed((run.get("phase2") or {}).get("steps") or []):
+ if s.get("passed"):
+ last_pass = s
+ break
+ ingest_p99 = int(last_pass["ingest"]["p99"]) if last_pass else 0
+ lines.append(f"| {run['tier']} | {run['mode']} | {max_items:,} | {max_batch:,} | {max_rate:g} | {ingest_p99} |")
+ lines.append("")
- lines.append("")
- lines.append("Generated by `benchmarks/scripts/chart.py`. "
- "Failure thresholds: ingest error rate > 5%, OR any read endpoint p99 > "
- f"{READ_P99_BUDGET_MS}ms.")
+ readprobe_runs = [r for r in runs if r["scenario"] == "read-probe"]
+ if readprobe_runs:
+ lines.append("## Read-probe scenario")
+ lines.append("")
+ lines.append("Failure: a read probe exceeded the configured threshold (default 5000ms) or returned an error. "
+ "Max fill level passed is the largest row count at which the read still came back in time.")
+ lines.append("")
+ for signal in SIGNALS:
+ sig_runs = [r for r in readprobe_runs if r["signal"] == signal]
+ if not sig_runs:
+ continue
+ lines.append(f"### {signal.capitalize()} — probing `{readPathForSignal(signal)}`")
+ lines.append("")
+ lines.append(f"| Tier | Mode | Max {ROW_LABEL[signal]} passed | Read latency @ max (ms) | First failing fill | Read latency @ failing (ms) |")
+ lines.append("|------|------|----------------|-------------------|--------------------|------------------------|")
+ for run in sorted(sig_runs, key=lambda r: (tier_rank(r["tier"]), mode_rank(r["mode"]))):
+ rp = run.get("readProbe") or {}
+ steps = rp.get("steps") or []
+ max_passed = run.get("maxFillLevelPassed", 0)
+ latency_at_max = 0
+ first_fail = ""
+ latency_at_fail = ""
+ for s in steps:
+ if s.get("passed"):
+ latency_at_max = int(s.get("readLatencyMs", 0))
+ elif not first_fail:
+ first_fail = f"{int(s.get('rowsIngested', 0)):,}"
+ latency_at_fail = f"{int(s.get('readLatencyMs', 0))}"
+ lines.append(f"| {run['tier']} | {run['mode']} | {int(max_passed):,} | {latency_at_max} | {first_fail or '—'} | {latency_at_fail or '—'} |")
+ lines.append("")
+
+ lines.append("Generated by `benchmarks/scripts/chart.py`.")
out.write_text("\n".join(lines) + "\n")
@@ -146,13 +261,15 @@ def main() -> int:
runs = load_runs(results_dir)
if not runs:
- print(f"no *.json files in {results_dir}", file=sys.stderr)
+ print(f"no usable *.json files in {results_dir}", file=sys.stderr)
return 1
- render_bar(runs, results_dir / "chart.png")
- render_detail(runs, results_dir / "chart-detail.png")
+ for signal in SIGNALS:
+ render_throughput_bar(runs, signal, results_dir / f"chart-{signal}.png")
+ render_throughput_detail(runs, signal, results_dir / f"chart-detail-{signal}.png")
+ render_readprobe(runs, signal, results_dir / f"chart-readprobe-{signal}.png")
render_summary(runs, results_dir / "summary.md")
- print(f"wrote {results_dir}/chart.png, chart-detail.png, summary.md")
+ print(f"wrote charts and summary.md into {results_dir}")
return 0
diff --git a/benchmarks/scripts/loadgen-bootstrap.sh b/benchmarks/scripts/loadgen-bootstrap.sh
index 15417984..67b68e8f 100755
--- a/benchmarks/scripts/loadgen-bootstrap.sh
+++ b/benchmarks/scripts/loadgen-bootstrap.sh
@@ -3,7 +3,7 @@
# project on the SUT, run the loadgen pointed at the SUT's private IP, and pull
# the result JSON back.
#
-# Usage: loadgen-bootstrap.sh <loadgen-public-ip> <sut-private-ip> <sut-public-ip> <duration> <tier> <mode> <out-path> [extra-loadgen-args...]
+# Usage: loadgen-bootstrap.sh <loadgen-public-ip> <sut-private-ip> <sut-public-ip> <duration> <tier> <mode> <signal> <out-path> [extra-loadgen-args...]
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
@@ -11,12 +11,12 @@ REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
# shellcheck source=_ssh.sh
source "${SCRIPT_DIR}/_ssh.sh"
-if [[ $# -lt 7 ]]; then
- echo "usage: $0 <loadgen-public-ip> <sut-private-ip> <sut-public-ip> <duration> <tier> <mode> <out-path> [extra-loadgen-args...]" >&2
+if [[ $# -lt 8 ]]; then
+ echo "usage: $0 <loadgen-public-ip> <sut-private-ip> <sut-public-ip> <duration> <tier> <mode> <signal> <out-path> [extra-loadgen-args...]" >&2
exit 2
fi
-LG_IP="$1"; SUT_PRIVATE_IP="$2"; SUT_PUBLIC_IP="$3"; DURATION="$4"; TIER="$5"; MODE="$6"; OUT_PATH="$7"
-shift 7
+LG_IP="$1"; SUT_PRIVATE_IP="$2"; SUT_PUBLIC_IP="$3"; DURATION="$4"; TIER="$5"; MODE="$6"; SIGNAL="$7"; OUT_PATH="$8"
+shift 8
# 1. Seed a project on the SUT (over its PUBLIC IP from the orchestrator). The
# project token + JWT + project id are then handed to the loadgen, which
@@ -52,13 +52,16 @@ bench_ssh "${LG_IP}" "chmod +x /root/loadgen/loadgen"
# 4. Run the benchmark, streaming stderr back so progress is visible. The
# loadgen writes JSON to /root/loadgen/result.json on the loadgen box;
-# we scp it home afterwards.
-echo "running loadgen on ${LG_IP} -> http://${SUT_PRIVATE_IP} (tier=${TIER} mode=${MODE} duration=${DURATION})" >&2
+# we scp it home afterwards. JWT and project ID are passed unconditionally
+# so the read-probe scenario can hit dashboard endpoints; the throughput
+# scenario ignores them.
+echo "running loadgen on ${LG_IP} -> http://${SUT_PRIVATE_IP} (tier=${TIER} mode=${MODE} signal=${SIGNAL} duration=${DURATION})" >&2
bench_ssh "${LG_IP}" /root/loadgen/loadgen \
--target "http://${SUT_PRIVATE_IP}" \
--token "${TOKEN}" \
--jwt "${JWT}" \
--project-id "${PROJECT_ID}" \
+ --signal "${SIGNAL}" \
--duration "${DURATION}" \
--tier "${TIER}" \
--mode "${MODE}" \
diff --git a/benchmarks/scripts/preflight.sh b/benchmarks/scripts/preflight.sh
index 49d0753d..60d9d357 100755
--- a/benchmarks/scripts/preflight.sh
+++ b/benchmarks/scripts/preflight.sh
@@ -57,6 +57,22 @@ if command -v hcloud >/dev/null 2>&1 && [[ -n "${HCLOUD_TOKEN:-}" ]]; then
fi
fi
+# --- Managed ClickHouse credentials (only if managed-ch is in the plan) -----
+#
+# run-local.sh sets BENCH_MODES_PLAN before invoking preflight so this check
+# fires only for runs that actually include managed-ch. CI's workflow can set
+# the same var; if neither sets it we fall back to checking BENCH_MODES from
+# the environment.
+
+modes_plan="${BENCH_MODES_PLAN:-${BENCH_MODES:-}}"
+if [[ ",${modes_plan}," == *",managed-ch,"* ]]; then
+ for v in CLICKHOUSE_SERVER CLICKHOUSE_USERNAME CLICKHOUSE_PASSWORD; do
+ if [[ -z "${!v:-}" ]]; then
+ err "${v} not set; required when modes includes 'managed-ch'. Add the BENCH_CH_* repository secret or export the var locally."
+ fi
+ done
+fi
+
if [[ "${fail}" -ne 0 ]]; then
echo >&2
echo "preflight failed. fix the issues above before running." >&2
diff --git a/benchmarks/scripts/reset-managed-ch.sh b/benchmarks/scripts/reset-managed-ch.sh
new file mode 100755
index 00000000..b279e859
--- /dev/null
+++ b/benchmarks/scripts/reset-managed-ch.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+# Reset the bench database on a managed ClickHouse to an empty state so each
+# matrix entry starts from a clean baseline. Reads from the environment:
+# CLICKHOUSE_SERVER host:nativePort (e.g. cluster.clickhouse.cloud:9440)
+# CLICKHOUSE_USERNAME
+# CLICKHOUSE_PASSWORD
+# CLICKHOUSE_DATABASE default: traceway
+# BENCH_CH_HTTPS_PORT default: 8443 (CH Cloud uses 8443; some hosts 8123)
+#
+# The HTTPS interface lives on the same hostname as the native port, just on a
+# different port. We strip the native port off CLICKHOUSE_SERVER to get the
+# host, then talk to it over HTTPS.
+set -euo pipefail
+
+: "${CLICKHOUSE_SERVER:?required for managed-ch mode}"
+: "${CLICKHOUSE_USERNAME:?required for managed-ch mode}"
+: "${CLICKHOUSE_PASSWORD:?required for managed-ch mode}"
+DB="${CLICKHOUSE_DATABASE:-traceway}"
+
+CH_HOST="${CLICKHOUSE_SERVER%:*}"
+CH_HTTPS_PORT="${BENCH_CH_HTTPS_PORT:-8443}"
+URL="https://${CH_HOST}:${CH_HTTPS_PORT}/"
+
+echo "resetting managed CH database '${DB}' on ${CH_HOST}:${CH_HTTPS_PORT}" >&2
+curl -fsSL --max-time 30 -u "${CLICKHOUSE_USERNAME}:${CLICKHOUSE_PASSWORD}" \
+ "${URL}" --data-binary "DROP DATABASE IF EXISTS \`${DB}\`"
+curl -fsSL --max-time 30 -u "${CLICKHOUSE_USERNAME}:${CLICKHOUSE_PASSWORD}" \
+ "${URL}" --data-binary "CREATE DATABASE \`${DB}\`"
+echo "managed CH '${DB}' is empty" >&2
diff --git a/benchmarks/scripts/run-local.sh b/benchmarks/scripts/run-local.sh
index 3123d277..7c161d06 100755
--- a/benchmarks/scripts/run-local.sh
+++ b/benchmarks/scripts/run-local.sh
@@ -9,9 +9,10 @@
# SSH key named 'benchmark-key'.
#
# Common usage:
-# run-local.sh # full matrix (4 tiers x 2 modes)
-# run-local.sh --smoke # 1 tier, 1 mode, short steps (~5 min)
-# run-local.sh --tier ccx13 --mode sqlite
+# run-local.sh # full matrix (4 tiers x 2 modes x 3 signals), throughput
+# run-local.sh --scenario read-probe # same matrix but ingest-and-probe-reads
+# run-local.sh --smoke # 1 tier, 1 mode, 1 signal, short steps (~5 min)
+# run-local.sh --tier ccx13 --mode sqlite --signal spans
# run-local.sh --dry-run # validate env + print plan, no provisioning
# run-local.sh --commit # drop the "-local" suffix on the output dir
set -euo pipefail
@@ -21,36 +22,49 @@ REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
TIERS="ccx13,ccx23,ccx33,ccx43"
MODES="sqlite,pgch"
+SIGNALS="spans,metrics,logs"
+SCENARIO="throughput"
DURATION="30m"
SMOKE=0
DRY_RUN=0
COMMIT=0
usage() {
- sed -n '1,16p' "$0"; exit 2
+ sed -n '1,17p' "$0"; exit 2
}
while [[ $# -gt 0 ]]; do
case "$1" in
- --tier) TIERS="$2"; shift 2 ;;
- --mode) MODES="$2"; shift 2 ;;
+ --tier) TIERS="$2"; shift 2 ;;
+ --mode) MODES="$2"; shift 2 ;;
+ --signal) SIGNALS="$2"; shift 2 ;;
+ --scenario) SCENARIO="$2"; shift 2 ;;
--duration) DURATION="$2"; shift 2 ;;
- --smoke) SMOKE=1; shift ;;
- --dry-run) DRY_RUN=1; shift ;;
- --commit) COMMIT=1; shift ;;
- -h|--help) usage ;;
+ --smoke) SMOKE=1; shift ;;
+ --dry-run) DRY_RUN=1; shift ;;
+ --commit) COMMIT=1; shift ;;
+ -h|--help) usage ;;
*) echo "unknown flag: $1" >&2; usage ;;
esac
done
+case "${SCENARIO}" in
+ throughput|read-probe) ;;
+ *) echo "invalid --scenario '${SCENARIO}' (expected throughput|read-probe)" >&2; exit 2 ;;
+esac
+export BENCH_SCENARIO="${SCENARIO}"
+
if [[ "${SMOKE}" -eq 1 ]]; then
TIERS="ccx13"
MODES="sqlite"
+ SIGNALS="spans"
DURATION="3m"
- echo "smoke mode: tier=ccx13 mode=sqlite duration=${DURATION} stepped 100->400 eps" >&2
+ echo "smoke mode: tier=ccx13 mode=sqlite signal=spans scenario=${SCENARIO} duration=${DURATION} (one short run)" >&2
fi
-# Preflight first — fail fast on missing tooling.
+# Preflight first — fail fast on missing tooling. Pass the chosen modes so
+# managed-ch can demand CH credentials before we burn a single euro.
+export BENCH_MODES_PLAN="${MODES}"
"${SCRIPT_DIR}/preflight.sh"
date_tag="$(date -u +%Y-%m-%d)"
@@ -62,17 +76,20 @@ fi
mkdir -p "${OUT_DIR}"
echo "results dir: ${OUT_DIR}" >&2
-# Plan: explode tiers x modes.
+# Plan: explode tiers x modes x signals.
plan=()
IFS=',' read -ra TIER_ARR <<<"${TIERS}"
IFS=',' read -ra MODE_ARR <<<"${MODES}"
+IFS=',' read -ra SIGNAL_ARR <<<"${SIGNALS}"
for t in "${TIER_ARR[@]}"; do
for m in "${MODE_ARR[@]}"; do
- plan+=("${t}|${m}")
+ for s in "${SIGNAL_ARR[@]}"; do
+ plan+=("${t}|${m}|${s}")
+ done
done
done
-echo "plan (${#plan[@]} entries):" >&2
+echo "plan (${#plan[@]} entries, scenario=${SCENARIO}):" >&2
for e in "${plan[@]}"; do
echo " - ${e//|/ x }" >&2
done
@@ -90,10 +107,10 @@ smoke_arg=""
failures=()
for e in "${plan[@]}"; do
- tier="${e%%|*}"; mode="${e##*|}"
- if ! "${SCRIPT_DIR}/run-matrix-entry.sh" "${tier}" "${mode}" "${DURATION}" "${OUT_DIR}" "${smoke_arg}"; then
- echo "FAIL: ${tier}/${mode}" >&2
- failures+=("${tier}/${mode}")
+ IFS='|' read -r tier mode signal <<<"${e}"
+ if ! "${SCRIPT_DIR}/run-matrix-entry.sh" "${tier}" "${mode}" "${signal}" "${DURATION}" "${OUT_DIR}" "${smoke_arg}"; then
+ echo "FAIL: ${tier}/${mode}/${signal}" >&2
+ failures+=("${tier}/${mode}/${signal}")
fi
done
diff --git a/benchmarks/scripts/run-matrix-entry.sh b/benchmarks/scripts/run-matrix-entry.sh
index 35e31323..6ef081de 100755
--- a/benchmarks/scripts/run-matrix-entry.sh
+++ b/benchmarks/scripts/run-matrix-entry.sh
@@ -4,26 +4,39 @@
# GitHub workflow; treat this as the single source of truth for matrix-entry
# orchestration.
#
-# Usage: run-matrix-entry.sh <tier> <mode> <duration> <out-dir> [smoke]
+# Usage: run-matrix-entry.sh <tier> <mode> <signal> <duration> <out-dir> [smoke]
# <tier> ccx13 | ccx23 | ccx33 | ccx43
# <mode> sqlite | pgch
+# <signal> spans | metrics | logs
# <duration> Loadgen total runtime, e.g. 30m, 3m
-# <out-dir> Directory to write <tier>-<mode>.json into
-# [smoke] "smoke" to enable short-step overrides (--initial-eps 100
-# --max-eps 400 --step-duration 1m). Optional.
+# <out-dir> Directory to write <tier>-<mode>-<signal>.json into
+# [smoke] "smoke" to enable short-step overrides (--phase1-batch-sizes
+# 256,1024 --phase2-request-rates 1,5 --step-duration 15s).
+# Optional.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-if [[ $# -lt 4 ]]; then
- echo "usage: $0 <tier> <mode> <duration> <out-dir> [smoke]" >&2
+if [[ $# -lt 5 ]]; then
+ echo "usage: $0 <tier> <mode> <signal> <duration> <out-dir> [smoke]" >&2
exit 2
fi
-TIER="$1"; MODE="$2"; DURATION="$3"; OUT_DIR="$4"; SMOKE="${5:-}"
+TIER="$1"; MODE="$2"; SIGNAL="$3"; DURATION="$4"; OUT_DIR="$5"; SMOKE="${6:-}"
LOCATION="${BENCH_LOCATION:-nbg1}"
+SCENARIO="${BENCH_SCENARIO:-throughput}"
-RUN_ID="$(date -u +%Y%m%d-%H%M%S)-${TIER}-${MODE}-$RANDOM"
-echo "=== run-matrix-entry tier=${TIER} mode=${MODE} duration=${DURATION} run_id=${RUN_ID} ===" >&2
+case "${SIGNAL}" in
+ spans|metrics|logs) ;;
+ *) echo "invalid signal '${SIGNAL}' (expected spans|metrics|logs)" >&2; exit 2 ;;
+esac
+
+case "${SCENARIO}" in
+ throughput|read-probe) ;;
+ *) echo "invalid BENCH_SCENARIO '${SCENARIO}' (expected throughput|read-probe)" >&2; exit 2 ;;
+esac
+
+RUN_ID="$(date -u +%Y%m%d-%H%M%S)-${TIER}-${MODE}-${SIGNAL}-${SCENARIO}-$RANDOM"
+echo "=== run-matrix-entry tier=${TIER} mode=${MODE} signal=${SIGNAL} scenario=${SCENARIO} duration=${DURATION} run_id=${RUN_ID} ===" >&2
mkdir -p "${OUT_DIR}"
@@ -48,12 +61,16 @@ LOADGEN_PUBLIC_IP=$(printf '%s' "${INFRA_JSON}" | jq -r '.loadgenPublicIp')
"${SCRIPT_DIR}/sut-bootstrap.sh" "${SUT_PUBLIC_IP}" "${MODE}"
# 3. Run the loadgen, pulling JSON back into OUT_DIR.
-extra_args=()
+extra_args=( --scenario "${SCENARIO}" )
if [[ "${SMOKE}" == "smoke" ]]; then
- extra_args+=( --initial-eps 100 --max-eps 400 --step-duration 1m )
+ if [[ "${SCENARIO}" == "read-probe" ]]; then
+ extra_args+=( --fill-levels 100000,1000000 --settle-seconds 5s )
+ else
+ extra_args+=( --phase1-batch-sizes 256,1024 --phase2-request-rates 1,5 --step-duration 15s )
+ fi
fi
-OUT_PATH="${OUT_DIR}/${TIER}-${MODE}.json"
+OUT_PATH="${OUT_DIR}/${TIER}-${MODE}-${SIGNAL}-${SCENARIO}.json"
"${SCRIPT_DIR}/loadgen-bootstrap.sh" \
"${LOADGEN_PUBLIC_IP}" \
"${SUT_PRIVATE_IP}" \
@@ -61,8 +78,9 @@ OUT_PATH="${OUT_DIR}/${TIER}-${MODE}.json"
"${DURATION}" \
"${TIER}" \
"${MODE}" \
+ "${SIGNAL}" \
"${OUT_PATH}" \
"${extra_args[@]}"
# Trap handles teardown — no explicit call needed.
-echo "matrix entry ${TIER}-${MODE} complete -> ${OUT_PATH}" >&2
+echo "matrix entry ${TIER}-${MODE}-${SIGNAL}-${SCENARIO} complete -> ${OUT_PATH}" >&2
diff --git a/benchmarks/scripts/sut-bootstrap.sh b/benchmarks/scripts/sut-bootstrap.sh
index 1f488938..a4118dbd 100755
--- a/benchmarks/scripts/sut-bootstrap.sh
+++ b/benchmarks/scripts/sut-bootstrap.sh
@@ -24,10 +24,16 @@ SUT_IP="$1"
MODE="$2"
case "${MODE}" in
- sqlite|pgch) ;;
- *) echo "mode must be sqlite or pgch, got: ${MODE}" >&2; exit 2 ;;
+ sqlite|pgch|managed-ch) ;;
+ *) echo "mode must be sqlite, pgch, or managed-ch, got: ${MODE}" >&2; exit 2 ;;
esac
+if [[ "${MODE}" == "managed-ch" ]]; then
+ : "${CLICKHOUSE_SERVER:?CLICKHOUSE_SERVER required for managed-ch mode}"
+ : "${CLICKHOUSE_USERNAME:?CLICKHOUSE_USERNAME required for managed-ch mode}"
+ : "${CLICKHOUSE_PASSWORD:?CLICKHOUSE_PASSWORD required for managed-ch mode}"
+fi
+
echo "waiting for ssh on ${SUT_IP}" >&2
wait_for_ssh "${SUT_IP}"
@@ -55,8 +61,32 @@ bench_rsync \
--exclude 'backend/storage' \
"${REPO_ROOT}/" "root@${SUT_IP}:/opt/traceway/"
+compose_args=( -f "benchmarks/compose/docker-compose.${MODE}.yml" )
+
+if [[ "${MODE}" == "managed-ch" ]]; then
+ # Wipe the managed CH database so this entry starts on an empty cluster.
+ # The script runs locally (orchestrator-side); the SUT itself never needs
+ # the curl + CH credentials.
+ "${SCRIPT_DIR}/reset-managed-ch.sh"
+
+ # Ship CH credentials to the SUT via a tempfile + --env-file. Inline env
+ # via ssh would have to survive two layers of shell quoting; the file is
+ # simpler and safe for arbitrary password characters.
+ env_tmp="$(mktemp)"
+ trap 'rm -f "${env_tmp}"' EXIT
+ cat > "${env_tmp}" <<EOF
+CLICKHOUSE_SERVER=${CLICKHOUSE_SERVER}
+CLICKHOUSE_USERNAME=${CLICKHOUSE_USERNAME}
+CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD}
+CLICKHOUSE_DATABASE=${CLICKHOUSE_DATABASE:-traceway}
+CLICKHOUSE_TLS=${CLICKHOUSE_TLS:-true}
+EOF
+ bench_scp "${env_tmp}" "root@${SUT_IP}:/opt/traceway/benchmarks/compose/managed-ch.env"
+ compose_args=( --env-file benchmarks/compose/managed-ch.env "${compose_args[@]}" )
+fi
+
echo "bringing up compose stack (mode=${MODE}) on ${SUT_IP}" >&2
-bench_ssh "${SUT_IP}" "cd /opt/traceway && BENCH_PORT=80 docker compose -f benchmarks/compose/docker-compose.${MODE}.yml up -d --build"
+bench_ssh "${SUT_IP}" "cd /opt/traceway && BENCH_PORT=80 docker compose ${compose_args[*]} up -d --build"
echo "polling /health on ${SUT_IP}" >&2
deadline=$(( $(date +%s) + 600 )) # cold compose build can hit 10 min on small tiers