Skip to content

feat: built-in Prometheus /metrics exporter - #468

Merged
fcostaoliveira merged 30 commits into
masterfrom
feat/prometheus-exporter
Jun 17, 2026
Merged

fcostaoliveira merged 30 commits into
masterfrom
feat/prometheus-exporter

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

Built-in Prometheus /metrics exporter

Adds an optional, built-in Prometheus exporter so a running memtier_benchmark can be scraped live (Grafana, long soak/perf runs) without parsing stdout or the JSON output. Off by default; enabled with --prometheus-port.

What it does

  • --prometheus-port <p> (absent = disabled, 0 = ephemeral port announced on stdout), --prometheus-bind-addr (default 127.0.0.1; numeric IPv4/IPv6 only — hostnames/localhost rejected), --prometheus-run-label key=value (repeatable), --prometheus-latency-buckets.
  • A dedicated libevent evhttp listener thread serves GET /metrics in Prometheus text format (text/plain; version=0.0.4). Non-GET → 501, unknown path → 404, in-flight cap → 503.
  • Exposes process-lifetime counters (memtier_ops_total, memtier_{sent,received}_bytes_total, memtier_hits/misses/errors/connection_errors/retry*_total), a native latency histogram (memtier_latency_seconds), and gauges (memtier_build_info, memtier_connections, memtier_threads, memtier_run, …).

Design highlights

  • One producer, two transports. The existing 1 Hz StatsD snapshot block is refactored into a single metrics_snapshot producer consumed by both StatsD (byte-identical wire — pinned by an extended test_statsd.py) and the new exporter. No second stats pipeline.
  • Zero hot-path cost. Counters come from the existing benign-race getters; latency reuses the already-aggregated instantaneous HDR histogram. Render is on-scrape with a 1 s TTL.
  • Monotonic counters across --run-count runs and mid-run cg_thread::restart() resets via a process-lifetime accumulator.
  • Honest latency error model: a per-client total_count delta gate prevents a stalled/dropped client from re-adding its partial histogram on every tick; HELP text documents the phase-dependent sampling.
  • Safe teardown: a stop-event (event_active) protocol avoids a libevent lost-wakeup hang at shutdown; frees happen on the main thread post-join.
  • Security: loopback default, non-loopback bind prints a one-shot warning, and /metrics echoes no password / server address / TLS paths (redaction test included).

Build

Default-on; configure link-tests for evhttp ≥ 2.1.1 (in libevent, already required). ./configure --disable-prometheus compiles it out cleanly (exporter TU → zero symbols). No new dependencies.

Tests & docs (in this PR)

  • Unit harness tests/unit/prometheus_metrics_test.cpp (U1–U8) via make check.
  • tests/test_cli_validation_prometheus.py (V1–V19), tests/test_prometheus.py (F1–F20, live scrape/teardown/stall-dedup), tests/test_prometheus_redaction.py, CLI-fuzz corpus entries.
  • tests/run_local_gate.sh + make gate — one-command local gate (both build flavors, all suites, format/purity audits, sanitizer runs, promtool).
  • README, docs/REALTIME_METRICS.md, DEVELOPMENT.md, man page, bash-completion.

Locally: make gate green (incl. ASan/TSan exporter runs and docker-promtool); 21/21 functional, 19/19 CLI-validation, StatsD wire unchanged.

🤖 Generated with Claude Code


Note

Medium Risk
Introduces an unauthenticated HTTP listener and refactors the hot 1 Hz metrics path in run_benchmark, though runtime exposure is opt-in and loopback is the default bind.

Overview
Adds a built-in Prometheus pull exporter so a live run can be scraped at GET /metrics when --prometheus-port is set (0 picks an ephemeral port and prints the URL on stdout). New --prometheus-bind-addr, --prometheus-run-label, and --prometheus-latency-buckets flags sit alongside StatsD; --version reports prometheus=yes|no. ./configure enables evhttp by default (link-test for libevent ≥ 2.1.1) with --disable-prometheus to compile the feature out.

Implementation splits a config-free prometheus_metrics layer (snapshot POD, monotonic accumulator, text renderer) from prometheus_exporter (dedicated libevent evhttp thread, 1 s render cache, stop-event teardown). The benchmark loop builds one metrics_snapshot per tick for both StatsD (wire kept the same) and Prometheus (cumulative counters, gated HDR latency via copy_inst_histogram_if_changed / hdr_add_positive_delta). Rx/tx byte getters on client_group/run_stats feed sent/received counters without double-counting.

CI and local workflow: ASAN/TSAN matrices include Prometheus suites; ci.yml adds dual-flavor build-notls, a promtool lint job, and longer test timeouts; make check runs prometheus_metrics_test; make gate runs tests/run_local_gate.sh (both flavors, RLTest, HTTP smoke, optional sanitizers, purity greps). README, REALTIME_METRICS.md, man page, and bash-completion document the feature.

Reviewed by Cursor Bugbot for commit 8ba2ad3. Bugbot is set up for automated code reviews on this repo. Configure here.

fcostaoliveira and others added 17 commits June 15, 2026 23:47
…t parser) + unit harness

Add the pure, config-free, libevent-free metrics layer of the Prometheus
exporter (PLAN.md v5 sections 3.1/3.3/3.5/3.7/4/5):

- prometheus_metrics.{h,cpp}: mt_counter enum, counter_set, metrics_snapshot
  POD, monotonic_accumulator (base + per-thread last-seen fold, fold_final,
  fill), prom::text_renderer (exposition, escaping, slot-edge-quantized HDR
  bucket walk, %.12g le format with the division-form losslessness invariant),
  parse_latency_buckets (1-64 tokens, hard cap 86400 s, slot-collision reject,
  W2/W2b warn zones), validate_prom_label_name. The metric inventory lives in a
  single kMetricDefs[] table. Honors the Decisions #52 purity contract (no
  config.h/version.h/libevent; build_info via ctor string args) and mirrors the
  run_stats SEC HDR triplet via PROM_HDR_* (Decisions #22).
- tests/unit/prometheus_metrics_test.cpp: unit tests U1-U8 (assert-style main,
  no gtest), incl. the U2 clamp replica pinned to run_stats.cpp:46-47.
- Makefile.am: add the sources row (unconditional, not under HAVE_EVHTTP) and a
  check_PROGRAMS/TESTS harness wired into make check.

Dead code; zero behavior change.

Co-Authored-By: Claude Fable 5 <[email protected]>
…skips

Extend tests/test_statsd.py per PLAN §10 "StatsD wire pins" / Decisions #46
so a StatsD wire regression is RED instead of silently green:

- Add module-level per-metric value-format regexes (VALUE_FORMAT_RES):
  INT_G ("%ld"|g), F6_G ("%.6f"|g), F3_MS ("%.3f"|ms), plus the
  latency_p* class. progress_pct is pinned F6_G_OR_ZERO because the run-end
  zeroing block emits it via gauge((long) 0) -> ":0|g". An unknown metric
  name now FAILS (a renamed/new metric must update the pins).
- Convert the two post-run _skip() sites in test_statsd_metrics_emitted and
  test_statsd_prefix_and_label (memtier exited non-zero / no datagrams) into
  hard assertTrue(False) failures: these tests pass --statsd-host over
  loopback with --test-time=3 (>=2 ticks), so silence IS the regression.
  Soft skips kept where statsd was not requested (pre-bind, 8125-busy,
  env-gated graphite).

Green against the unmodified master binary (4/4 PASS): the pins describe
today's wire before the A1.2b refactor.

Co-Authored-By: Claude Fable 5 <[email protected]>
Extract the 1 Hz StatsD emit block out of run_benchmark()'s progress loop
into a file-static statsd_publish_tick() that consumes a metrics_snapshot
(the one-producer POD from prometheus_metrics.h), per PLAN section 3.6c /
Decisions #37. This is the single producer the Prometheus transport will
later share; this commit is statsd-ONLY (no cfg->prometheus references, no
Prometheus wiring, no behavior change) and lives OUTSIDE any HAVE_EVHTTP
guard.

Byte-identical UDP wire is preserved: the gauge(double):92 vs gauge(long):97
overload selection is unchanged because the snapshot carries cur/avg ops/bytes
as long (cast at the fill site) -> gauge(long) "%ld"|g, progress_pct as
double -> gauge(double) "%.6f"|g, latencies via timing(double) "%.3f"|ms,
and the connection_errors >0 send condition is kept. The run-end zeroing
block, the run-start/end events, and the inst_hist_agg/realtime aggregation
(:3052-3066) are untouched. Snapshot read sites and benign-race discipline
match the inline block.

Verified: A1.2a's value-format-sensitive gate 4/4 PASS pre and post; wire
capture shows the identical metric set and printf shapes; make check +
make format-check green; test_realtime_latencies.py 3/3 PASS (shared inst
histogram path unchanged); grep-audit: gauge/timing only in
statsd_publish_tick + run-end zeroing, event exactly two sites, zero
prometheus references.

Co-Authored-By: Claude Fable 5 <[email protected]>
…suppressions, harness override

Co-Authored-By: Claude Fable 5 <[email protected]>
…er TTL, stop-event teardown)

Co-Authored-By: Claude Fable 5 <[email protected]>
Add the four Prometheus exporter flags (PLAN.md v5 section 5), guarded by
HAVE_EVHTTP, parse-and-validate only (no exporter creation yet):

  --prometheus-port           absent = disabled; 0 = ephemeral; sentinel -1
  --prometheus-bind-addr      numeric IPv4/IPv6 only; localhost/hostnames
                              rejected; [::1] stripped in place
  --prometheus-run-label      repeatable KEY=VALUE; validated, dup/16-cap
  --prometheus-latency-buckets parsed via prom::parse_latency_buckets

Wires every CLI touch point: anonymous enum, long_options[], case handlers
(port via the statsd strtoul pattern with range check before narrowing,
bind-addr bracket-strip + inet_pton, run-label via validate_prom_label_name,
buckets via parse_latency_buckets), config_init_defaults (127.0.0.1),
usage(), config_print() (prints prometheus-port = -1 when disabled),
config_print_to_json() (run-labels JSON-escaped; no secrets), the four
benchmark_config members, the prometheus_port sentinel init in main(),
the post-parse dependency check (E12) + one-shot non-loopback warning (W1)
via addr_is_loopback(), and the --version prometheus=yes/no token.

Canonical error strings E1-E12 and warning W1 pinned verbatim. Adds
explicit <arpa/inet.h>/<netinet/in.h> includes (previously only transitive).

Both configure flavors build; make check + make format-check green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Make the Prometheus exporter reachable for the first time (PLAN.md v5
sections 3.2, 3.6 a/b/d/e, 3.7), guarded by HAVE_EVHTTP:

  - g_prom_exporter ownership handle next to g_threads; cfg.prometheus alias.
  - Creation in main() after the statsd init block, after
    evthread_use_pthreads() and config_init_defaults(): build options from
    cfg, new prometheus_exporter, start() or exit(1) (deliberate leak,
    LSan-reachable). Only when --prometheus-port was given.
  - Producer wiring via a file-static prom_* helper island above
    run_benchmark() (prom_observe_and_fill / prom_fold_thread /
    prom_publish_tick / prom_publish_run_start/_end) with empty #else stubs
    so the run loop stays ifdef-free. prom_publish_tick resets the scratch
    tick histogram, runs the gated aggregate_inst_histogram_if_changed walk
    over non-finished threads, fills the full snapshot (counters via the
    rx/tx + ops/hits/misses/errors getters through the monotonic
    accumulator), and publishes. Wired into the shared 1 Hz tick next to
    statsd_publish_tick, run-start after the statsd start event, restart
    fold between join() and restart(), and post-join reconcile + run-end
    publish before the client_group deletion loop.
  - Join point before the TLS cleanup: stop_and_join(); delete; NULL — the
    first runtime exercise of the stop-event teardown (verified no hang,
    clean rc 0, port released).
  - --version token: prometheus=yes (HAVE_EVHTTP) / prometheus=no.
  - --test-time threaded into memtier_config_test_time_seconds via a new
    snapshot.test_time field stamped once in publish() from options.test_time
    (single chokepoint; no fill-site or renderer-ctor churn).

Live smoke: /metrics serves 200 with Content-Type text/plain; version=0.0.4,
ops_total monotonic across scrapes, build_info / latency histogram / run
labels present, non-GET -> 501, /metrics/ -> 404, no secrets in the body,
clean process exit. StatsD test 4/4 PASS (no shared-producer regression).

Co-Authored-By: Claude Fable 5 <[email protected]>
Add tests/test_cli_validation_prometheus.py implementing V1-V19 from the
Prometheus-exporter plan (PLAN.md section 10): every --prometheus-* reject
case with its pinned exit code and canonical E1-E12 / W1 / W2 / W2b message,
every accept/warn-accept case, the bind-collision exit(1) path (no sanitizer
output), --show-config / mb.json config-dump pins, and the LSan
exit(1)-after-creation leak case. Mirrors test_cli_validation_read_preference
structure; drives MEMTIER_BINARY (prom flavor) and the optional
MEMTIER_NOPROM_BINARY for the compiled-out V16 case.

Co-Authored-By: Claude Fable 5 <[email protected]>
Seed the Hypothesis CLI fuzzer (tests/cli_fuzz.py) with the four
--prometheus-* flags after --graphite-port: --prometheus-port gets the
weird-int corpus, the other three get the free-form string corpus. Their
parsers (inet_pton bind-addr, KEY=VALUE run-label validation, latency-bucket
list parsing) must reject malformed input cleanly and never crash. Verified
green at MEMTIER_FUZZ_MAX_EXAMPLES=100.

Co-Authored-By: Claude Fable 5 <[email protected]>
Add the four --prometheus-* flags to bash-completion's options_no_comp list
(all take arguments) on the statsd/graphite continuation line, and regenerate
memtier_benchmark.1 via `make rebuild-man` (help2man harvests usage()). The
man-page regeneration also picks up other usage() flags whose stanzas had
drifted since the page was last generated, plus the prometheus=yes --version
token in the .TH header -- all faithful output of the repo's man mechanism.

Co-Authored-By: Claude Fable 5 <[email protected]>
Add the shared exporter scrape utilities the functional suite (F1-F20) and
redaction suite build on, per PLAN.md §8/§10:

* PROM_LISTEN_RE       -- captures the one-line stdout announce URL (IPv6 host
                          kept bracketed, RFC 3986).
* PROM_CONTENT_TYPE    -- the byte-exact text/plain;version=0.0.4 pin.
* wait_for_prometheus_url -- poll a Popen stdout file for the announce line.
* prom_scrape          -- HTTP GET (or arbitrary method) returning a PromScrape;
                          HTTP >=400 unwrapped to a real status, connection-level
                          failure reported as status=None (the F15 closed-outcome
                          "process beat the scrape to teardown" branch).
* prom_parse           -- parse exposition via prometheus_client's official
                          parser into {sample_name: [Sample, ...]}.
* prom_sample_value    -- first sample value by name + optional label subset.

Co-Authored-By: Claude Fable 5 <[email protected]>
…eardown)

F1-F20 + F15b against the RLTest harness via --prometheus-port=0 stdout
discovery: disabled-by-default, mid-run scrape shape, counter/histogram
monotonicity, run-fold accumulator, redaction, fixed-port announce,
run-label propagation, TTL clamp, hardening (501/404/oversize-header),
clean shutdown + port re-bind, teardown race window (F15/F15b stop-event
protocol), IPv6, connection-churn monotonicity, cluster smoke, stall
dedup (F19, Decisions #54), and the in-flight-cap 503 seam (F20).

F19 trailing-window freeze detection fixed: anchor to the most recent
sample >=1.8 s old (a trailing window) instead of the oldest qualifying
sample, which forever compared the live value against the pre-stall value
and never matched. The stall is a genuine DEBUG SLEEP on a dedicated
redis-py connection; the gate still proves _count stays flat while frozen.

Co-Authored-By: Claude Fable 5 <[email protected]>
Dedicated redaction suite (PLAN.md §6, the #440 precedent; modeled on
test_tls_logging.py::test_tls_paths_redacted_in_json).  R1 sets a
requirepass canary on the target, runs an authenticated benchmark, and
asserts the live /metrics body contains none of: the password canary, a
server/host/addr/target identity label, the target host/port in an
identity context, any '/'-rooted path-like label value, nor (under TLS
cells) the --cert/--key/--cacert absolute paths or their basenames.  R2
asserts the 404 body is the fixed string "not found\n" and never echoes
the requested URI.  Runs under both plaintext and TLS (after
./tests/gen-test-certs.sh); 2/2 green in each flavor.

Co-Authored-By: Claude Fable 5 <[email protected]>
PLAN.md §7.4:
- §7.4d: append test_prometheus.py to the standalone (misc) and cluster-TLS
  (misc) sanitizer cells in asan.yml/tsan.yml (so F15/F15b teardown runs
  under ASan/TSan -- the hang guard), test_prometheus_redaction.py to the
  standalone (misc) cells, and test_cli_validation_prometheus.py to the
  (cli) cells (runs V19 under detect_leaks=1).
- §7.4e: new self-contained promtool-lint job -- build default-on, scrape a
  live /metrics, install promtool from the sha256-pinned
  prometheus-2.53.2.linux-amd64.tar.gz, and fail on rc != 0 or ANY output;
  uploads the scraped exposition as an artifact.
- §7.4a: complete build-notls -- assert the prometheus=yes/=no --version
  token in each flavor and that --prometheus-port is rejected (rc 2 +
  "unrecognized option") in the --disable-prometheus build (deferred by A1.3).
- tests/test_requirements.txt: add prometheus_client>=0.20 (the exposition
  parser behind the functional + redaction suites).

CI-config-only: actionlint/pyyaml are unavailable locally, so the workflow
YAML is structurally hand-verified (indentation, no tabs) but not lint-run;
the test_requirements.txt change is locally exercised by the green suites.

Co-Authored-By: Claude Fable 5 <[email protected]>
- README.md: new "Prometheus /metrics exporter" subsection under Real-Time
  Metrics -- enablement via --prometheus-port, ephemeral-port announce, the
  four flags, exported families, and the no-identity-leak guarantee.
- docs/REALTIME_METRICS.md: full Prometheus section -- options, ephemeral-port
  contract (stdout announce, IPv6 bracketing, GET-only/501/404/Content-Type),
  metric mapping vs StatsD, the error model (phase-dependent ~50% capture,
  stall dedup + residuals, run-tail loss, <=1% HDR quantization; end-of-run
  output is authoritative), the threat model, and --cluster-mode /
  --verify-only / --unix-socket interaction statements.
- DEVELOPMENT.md: raise the libevent prerequisite to 2.1.1 (evhttp floor) with
  the --disable-prometheus escape, add the disable bullet, and a new
  "### Prometheus exporter build flavor" section (default-on configure, the
  evhttp >= 2.1.1 LINK test + loud failure, --version prometheus=yes/no token,
  unit harness under both flavors).

Co-Authored-By: Claude Fable 5 <[email protected]>
tests/run_local_gate.sh implements the consolidated local gate (PLAN.md §11),
S0-S10: prereqs + test venv, srcdir hygiene, sibling-VPATH both-flavor builds,
format-check, flavor asserts (prometheus=yes/no token, compiled-out flag
rejection), unit harness x2, the RLTest CLI/functional/redaction/statsd/
realtime/cluster suites (+ TLS redaction when certs present), the live HTTP
smoke (hardening, render-cache TTL, run-boundary monotonicity, verify-only
teardown loop), error paths + IPv6 + the in-flight-cap 503 seam, the ASan and
TSan cells, and the docs/completion/fuzz/purity grep audits.  Adds the `gate`
Makefile target and the `make gate` paragraph to the DEVELOPMENT.md exporter
section (S10 staleness greps require the token).

Deviations from the §11 listing, both justified: (1) the Content-Type check
reads headers via `curl -fsS -D -` (a GET) instead of `curl -fsSI` (a HEAD) --
the exporter is GET-only and answers HEAD with 501 (hardening, F11), so -fsSI
fails spuriously; (2) the gate reuses an existing venv (.venv or .venv-tests)
carrying RLTest + prometheus_client rather than creating a fresh one, because
this host's python cannot bootstrap pip (no ensurepip); pip install runs only
when pip is present.  The docker-promtool fallback degrades to warn+skip if the
pinned prom/prometheus image is unavailable offline.

Ran `make gate` end-to-end: GATE PASS (exit 0).  All suites green
(19/21/2/4/3/21/2 targeted + 304/304 full-suite fuzz), ASan + TSan clean
(zero sanitizer reports), docker-promtool lint clean on the captured scrape.

Co-Authored-By: Claude Fable 5 <[email protected]>
@jit-ci

jit-ci Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

fcostaoliveira and others added 5 commits June 16, 2026 03:48
The functional and redaction suites only ran green locally in plaintext
standalone. CI exercises TLS and OSS-cluster variants where:
- the live memtier run and F19's DEBUG SLEEP client must speak TLS when the
  env is TLS (server resets plaintext connections otherwise);
- requirepass must be set/cleared on every master node in a cluster, or
  memtier restart-loops against shards that still reject AUTH and never exits.

Also convert a proc.wait timeout into a clean assertion instead of an
unhandled exception. Validated locally: test_prometheus 21/21 and redaction
2/2 across TLS-standalone, plaintext-cluster, and TLS-cluster.

Co-Authored-By: Claude Fable 5 <[email protected]>
Under TSan/ASan builds (~5-10x slower) the 300k-key --verify-only run in
F15b does not finish within the 30s proc.wait deadline, so wait() raised an
unhandled TimeoutExpired. The zero-snapshot assertions (the test's purpose)
already passed by then. Use a generous 180s wait, tolerate a slow tail
(finally: _kill reaps the process), and raise the preload timeout to 300s.

Co-Authored-By: Claude Fable 5 <[email protected]>
F11/F15/F20 waited for a --test-time run to exit with timeouts (10-30s)
tuned for normal builds. Under sanitizer + OSS-cluster + TLS, startup
(cluster discovery, per-shard TLS handshakes) and teardown push total
runtime well past those, raising unhandled TimeoutExpired. Use 120s waits
that fail cleanly on a true hang. Validated under TLS-cluster locally.

Co-Authored-By: Claude Fable 5 <[email protected]>
The functional suite added ~2 min to the serial full-suite Test cells
(Single Endpoint / OSS), tipping them past the 15-min step budget even
though every test passed. Trim gratuitously long --test-time runs (F2/F3/
F9/F17/F18) and F19's stall window, and cut F15's teardown iterations
20->8. Per-test redis env spin-up dominates the rest, so also raise the
matrix and coverage 'Run tests' step timeout 15->25 min (the suite grew
with a real feature; per-test timeouts still bound genuine hangs).

Co-Authored-By: Claude Fable 5 <[email protected]>
memtier_connections/threads/run/configured_runs/config_test_time_seconds
are integer counts but were formatted with %.6g, which switches to
scientific notation past 6 significant digits (e.g. a large clients x
threads connection count would render as 1.23457e+06, losing fidelity).
Render them with integer formats. Prometheus parsed the floats fine, so
this is exposition-cleanliness, not a scrape correctness fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

V0 perturbation result — no slowdown from the exporter

Authoritative run on isolated c7i.4xlarge (client) against a fixed TLS Redis target, round-robin n=7, drift-cancelling, comparing three builds of this branch's tree:

  • master 62413fd (no exporter)
  • assembly e30c633 — exporter compiled in, not enabled at runtime (prometheus=yes)
  • noprom e30c633 --disable-prometheus (prometheus=no)
pipeline arm ops/sec (median, n=7) Δ vs master p99 ms Δ p99
1 master 167,219 — 0.575 —
1 assembly 167,781 +0.3% 0.575 ±0
1 noprom 168,267 +0.6% 0.567 −0.008
16 master 1,212,069 — 0.951 —
16 assembly 1,257,173 +3.7% 0.935 −0.016
16 noprom 1,245,849 +2.8% 0.943 −0.008

Verdict: PASS (regression-aware). Neither build regresses ops/sec or p99 vs master beyond the per-arm noise band (master CV 1.9–2.5%). The exporter, whether compiled-in-but-idle or compiled-out, does not slow memtier down.

The small p16 advantage for the PR builds is faster, not slower, and is consistent with a within-round arm-ordering effect (master is benchmarked first in each round); p99 is equal-or-better throughout, so there is no latency cost. A local pre-check (dev box, plaintext) reached the same conclusion within its wider noise.

Methodology + raw JSON: design/prometheus-exporter/v0-results/ in the workspace. Per the plan this clears the V0 merge gate.

@fcostaoliveira
fcostaoliveira marked this pull request as ready for review June 16, 2026 14:35
@fcostaoliveira fcostaoliveira added run-differential Triggers memtier-vs-reference differential suite on this PR run-soak Triggers soak/stress nightly suite on this PR run-fuzz Triggers monitor-input fuzz driver on this PR labels Jun 16, 2026
Comment thread prometheus_exporter.cpp Resolved
publish_run_end runs after the run's worker threads have joined, but set
memtier_threads to the configured --threads, so a scrape between runs
(--run-count > 1) showed every worker as active when none were. Report 0
active threads at run-end, consistent with the (already 0) connections
gauge. Addresses Cursor Bugbot review on PR #468.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread prometheus_exporter.cpp Resolved
…hread

Under TSan, the exporter's dedicated libevent event_base (epoll) thread races
with the main thread creating benchmark sockets (shard_connection::setup_socket
-> socket()) on a reused file-descriptor *number* — a known TSan fd-shadow
limitation, not a real race (independent kernel objects; epoll_ctl/socket are
kernel-thread-safe; the exporter never touches benchmark connection fds). This
surfaced as a ThreadSanitizer warning in memtier output that test_prometheus's
_no_sanitizer_output guard correctly flagged. Suppress via the exporter thread
frame, consistent with the existing libcrypto/stats-getter suppressions and the
design's proactive-suppression decision. TSAN_OPTIONS in tsan.yml passes this to
the memtier subprocess.

Co-Authored-By: Claude Fable 5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

monitor-fuzz failure is pre-existing, unrelated to this PR

The monitor-fuzz check is red, but it is not caused by this exporter PR — it reproduces identically on master (62413fd), which contains none of these changes.

Root cause (pre-existing): the monitor-input loader accepts an arbitrary command whose name is ≥100 characters; printing the stats table then aborts on a hard assertion:

run_stats.cpp: Assertion `column.column_size < 100 && "command name too long"' failed  → SIGABRT

Minimal repro (crashes master 62413fd, no exporter code involved):

printf '1.0 [0 127.0.0.1:0] "%s" "k"\n' "$(python3 -c 'print("A"*150)')" > /tmp/mi.txt
./memtier_benchmark --monitor-input=/tmp/mi.txt --command='__monitor_line@__' \
  --server=127.0.0.1 --port=6379 --test-time=2 --clients=1 --threads=1 --hide-histogram
# -> Aborted (SIGABRT), run_stats.cpp print_type_column assertion

A normal short command name exits cleanly. The fuzzer hits this because random mutations of the corpus seeds produce long command-name tokens.

This PR touches no monitor-input parsing or print_type_column code (git diff 62413fd..HEAD confirms). Every other check is green, including ASan/UBSan/TSan, the full soak suite, differential, and all prometheus/redaction/CLI suites. Filing the parser crash as a separate upstream issue; it should not block this exporter PR.

fcostaoliveira and others added 3 commits June 16, 2026 22:40
…prometheus-exporter

Resolves tests/test_requirements.txt by keeping both new deps (prometheus_client
for the exporter suites + psutil for master's CPU cross-validation). Source files
(run_stats, client, memtier_benchmark) auto-merged; verified: both build flavors
compile, make check + format-check green, statsd wire test 4/4 (one-producer
refactor intact), live /metrics scrape 200.

Co-Authored-By: Claude Fable 5 <[email protected]>
Move the 'Prometheus exporter listening on ...' stdout line from just-after-bind
to the end of start(), after HDR alloc + stop event + pthread_create all succeed.
Previously a failure in any later start() step exited 1 while stdout already
advertised a /metrics URL that was never brought up. Port is still resolved early;
only the announce is deferred. Addresses Cursor Bugbot review on PR #468.

Co-Authored-By: Claude Fable 5 <[email protected]>
…p, comment

From the adversarial review (1 major + 2 minors, 0 blockers):
- hits/misses HELP overpromised 'miss-tracked arbitrary commands'; the counters
  source m_totals.m_hits/_misses, incremented only on the GET path (arbitrary
  misses live in m_arbitrary_misses[], never folded into m_totals). Corrected
  HELP to state GET-only coverage; arbitrary-command hit/miss totals are a PR2
  item (live-summing m_arbitrary_misses would reintroduce the per-command race
  v1 deliberately avoids).
- memtier_exporter_snapshot_age_seconds: 'now' is sampled before the snapshot
  mutex, so a concurrent publish() could make published_at > now -> negative
  gauge. Clamp age to >= 0.
- Fix a stale comment claiming the start()-failure exporter is leaked; it is
  freed (delete + NULL) before exit(1).

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread prometheus_exporter.cpp Resolved
The constructor's initial zero snapshot set memtier_threads to --threads before
any worker existed, so a scrape during --verify-only or pre-run startup showed
live threads while memtier_run=0 and counters=0 — contradicting the idle-zero
snapshot and the run-end 0-threads behavior. Set active_threads=0 in the ctor
snapshot. Thread gauge is now consistent across all publish sites: ctor=0,
run_start=N, tick=live, run_end=0. Addresses Cursor Bugbot review on PR #468.

Co-Authored-By: Claude Fable 5 <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit e58a85a. Configure here.

Comment thread run_stats.cpp Resolved
fcostaoliveira and others added 2 commits June 17, 2026 00:15
copy_inst_histogram_if_changed() added the whole inst-totals histogram to
the lifetime histogram whenever total_count had changed since the last
gated copy. The inst histogram is reset only once per worker-second in
summarize_current_second(); when an exporter tick and that reset drift so
two 1 Hz ticks land within one worker-second, samples already folded on
the earlier tick were added again, inflating memtier_latency_seconds
buckets and _count (the metric is documented as a possible *under*count,
never an inflation).

Fix: keep a per-run_stats snapshot of the inst histogram as of the
previous gated copy (m_prom_last_inst, a deep-copyable safe_hdr_histogram
so run_stats stays value-copyable for post-join vector collection) and
add only the positive per-bucket delta versus that snapshot, so every
latency sample is folded at most once. A reset (cur total < last total)
re-adds the full current histogram. Frozen histograms (cur == last) are
still skipped, preserving the dead-client dedup (F19). In the rare window
where a reset is masked by net growth, some post-reset samples may be
dropped — an undercount consistent with the metric's non-authoritative
contract, never a double-count.

Verified: prometheus RLTest suite 20/21 pass locally (F19 fails only
because the local redis rejects DEBUG SLEEP, unrelated to this change);
redaction suite 2/2; clang-format clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…delta

Addresses the 7-agent adversarial review's one confirmed finding: no test
exercised the growing branch of copy_inst_histogram_if_changed that the
double-count fix (ec18e09) added. The only related test, F19, uses DEBUG
SLEEP to freeze the server, so it drives only the cur==last skip path —
byte-identical before and after the fix. Reverting the fix to "always
hdr_add the whole inst histogram" would still pass the entire suite.

- Extract the per-bucket positive-delta math into a pure free function
  prom::hdr_add_positive_delta(target, cur, prev) in the always-linked,
  libevent-free prometheus_metrics layer, so it is unit-testable in
  isolation. run_stats::copy_inst_histogram_if_changed now calls it.
- Add U9 to tests/unit/prometheus_metrics_test.cpp: (a) only positive
  per-bucket deltas are folded, shrinking buckets contribute 0; (b) a
  two-ticks-within-one-worker-second growth scenario asserting the lifetime
  histogram folds each sample exactly once (total 4, not the doubled 6 the
  pre-fix always-add produced). This is the regression guard for ec18e09.
- copy_inst_histogram_if_changed returns void now: the bool was advertised
  but the sole caller (aggregate_inst_histogram_if_changed) dropped it
  (flagged as a dead contract by two review lenses). Header comment updated.

Verified: prometheus_metrics layer always compiled (no HAVE_EVHTTP guard),
so --disable-prometheus still links (built both flavors). make check passes
U1-U9; prometheus RLTest 20/21 (F19 fails only on local redis rejecting
DEBUG SLEEP); clang-format clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@fcostaoliveira
fcostaoliveira merged commit 16df2db into master Jun 17, 2026
181 of 184 checks passed
fcostaoliveira added a commit that referenced this pull request Jun 17, 2026
#484)

* feat(prom): export arbitrary-command hits/misses as new counter series

Closes #483. The exporter (#468) reported memtier_hits_total / memtier_misses_total
from the GET path only; arbitrary-command (--command) hits/misses tracked in
run_stats m_arbitrary_misses[] were never surfaced, so a --command workload showed
0 in /metrics while console/JSON showed nonzero.

Add two new aggregate COUNTER series — memtier_arbitrary_hits_total and
memtier_arbitrary_misses_total (Option B: additive, GET series values unchanged,
no per-command label per the v1 cardinality rule). A combined total is one PromQL
sum(); folding into the existing series (Option A) was rejected because it would
silently redefine a shipped monotonic counter and destroy GET-vs-arbitrary
decomposability.

Race-free by construction: new client_group/run_stats accessors sum only the
per-command scalar totals in m_arbitrary_misses[] (never the per-key vectors the
worker grow-resizes), read at the single off-worker producer point
(prom_read_cg_counters) alongside the GET totals, so they inherit the monotonic
accumulator and the cross-run/restart fold with no new publish site and no new
hot-path work.

- prometheus_metrics.{h,cpp}: MT_ARBITRARY_HITS/MISSES enum slots before
  MT_NUM_COUNTERS; two kMetricDefs rows inserted in the contiguous counter block
  (after retried_ops_total, before connections) so the render loop's def-vs-enum
  lockstep holds; counter_metric_name cases; GET HELP reworded to forward-reference
  the new series (values unchanged); render comments made range-relative.
- run_stats / client_group: get_total_arbitrary_hits/misses (unsigned long long;
  the source fields are 64-bit).
- memtier_benchmark.cpp: fill the two slots in prom_read_cg_counters.

Tests:
- Unit U10: positional placement guard, full sentinel render proving every counter
  index renders its own value (GET series NOT folded; new series at their enum
  index), and HELP honesty.
- Integration F21 (surfaced + exact Option-B leak guard: GET series stay 0 under an
  arbitrary-only workload), F22 (arbitrary series present and 0 without --command),
  F23 (cluster aggregation), F24 (accumulation across run boundary via memtier_run).

Verified: make check (U1-U10), prometheus RLTest standalone 24/25 (F19 fails only on
local redis rejecting DEBUG SLEEP), --disable-prometheus builds and links,
clang-format clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(prom): suppress the benign arbitrary-misses getter race for TSan

The new race-free producer read of m_arbitrary_misses[] (#483) trips
ThreadSanitizer the same way every other live counter getter does: the main
thread sums total_hits/total_misses while workers bump them in
update_arbitrary_op_misses. Verified locally (TSan build, setarch -R) that
without these entries TSan reports the race at run_stats::get_total_arbitrary_hits
(run_stats.cpp:501), get_total_arbitrary_misses (:509) and the writer (:412-413),
and that adding them yields a clean run.

It is benign by the same reasoning as the existing getter suppressions: the read
touches only the monotonic scalar totals (never the grow-resized per_key_*
vectors; the outer m_arbitrary_misses vector is sized once in
setup_arbitrary_commands and not resized mid-run), live values are approximate,
and authoritative totals merge race-free post-join.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
This was referenced Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-differential Triggers memtier-vs-reference differential suite on this PR run-fuzz Triggers monitor-input fuzz driver on this PR run-soak Triggers soak/stress nightly suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant