Skip to content

feat(cpu): track memtier per-thread + whole-process CPU, warn when saturated (supersedes #346) - #471

Merged
fcostaoliveira merged 5 commits into
masterfrom
feat/cpu-utilization-tracking
Jun 16, 2026
Merged

fcostaoliveira merged 5 commits into
masterfrom
feat/cpu-utilization-tracking

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds per-thread and whole-process CPU utilization tracking for memtier_benchmark itself, so users can tell when the load generator (not the server under test) is the bottleneck and results are skewed. Supersedes #346 with a more accurate, aggregate-aware, configurable design (reusing #346's live-sampler helper and Python tests).

Almost no other load generator (wrk, wrk2, redis-benchmark, k6, fortio, vegeta, bombardier, ab, JMeter, Gatling) surfaces client-side CPU; the strongest precedent is Locust ("CPU usage above 90%! This may constrain your throughput..."). A CPU-saturated client silently under-drives its intended rate (coordinated omission), corrupting latency/throughput numbers.

Design

Two cooperating subsystems:

  • Authoritative totals — getrusage(RUSAGE_THREAD) captured inside each worker at run start/end, accumulated across restarts. A wall bracket is captured at the exact same points, so cores_used = cpu / wall covers one identical interval (no setup-vs-serving or across-restart skew). Linux-only; guarded by #if defined(RUSAGE_THREAD).
  • Live advisory sampler — per-second pthread_getcpuclockid + clock_gettime read from the main thread (no worker perturbation; macOS uses Mach thread_info). Drives the de-duped live warning and per-second JSON detail.

What users see

  • Console "CPU Utilization Summary" (total/user/sys, wall, cores used, avg % across worker threads, peak %) on stderr so piped table output is not corrupted.
  • JSON: a "CPU" aggregate block (sibling of Runtime) with a per-thread breakdown, plus a per-second "CPU Stats" block. Additive — no existing keys reordered/renamed.
  • --cpu-warn-threshold=PCT (default 95, mirrors --miss-rate-threshold). De-duped: one live warning per thread on first crossing + one end-of-run summary line per offending thread. No per-second spam.

avg_cpu_utilization_pct is worker-CPU-only, so it cannot exceed 100% from main-thread overhead. All divisions are guarded; JSON_handler::write_obj now emits null for any non-finite double.

Platform

Verified on glibc and musl/Alpine (Docker build). Linux-only RUSAGE_THREAD is guarded; _GNU_SOURCE added for glibc. macOS keeps the live sampler (Mach); the authoritative aggregate degrades gracefully.

Test plan

tests/test_cpu_stats.py (ported from #346 + extended), all passing locally via RLTest: schema, high-load de-duped warning, --cpu-warn-threshold behavior, aggregate/per-thread consistency, --run-count>1, and a psutil external cross-validation (matched within ~0.02s locally).

Developed and hardened through a multi-agent adversarial review modeled on the maintainers' real review standards.

🤖 Generated with Claude Code


Note

Medium Risk
Large instrumentation in the benchmark monitor loop and platform-specific CPU APIs could skew timing or behave differently on non-Linux, though guards and post-join reads limit worker impact.

Overview
Adds client-side CPU observability so users can see when memtier (not Redis) is limiting throughput. Workers record authoritative totals via getrusage(RUSAGE_THREAD) with matched wall brackets (accumulated across thread restarts); the main thread runs a per-second live sampler (Linux pthread_getcpuclockid, macOS Mach) for JSON time series, peak utilization, and de-duped stderr warnings.

New --cpu-warn-threshold (default 95%, same parsing style as --miss-rate-threshold) gates live and end-of-run bottleneck warnings. Results land in stderr CPU Utilization Summary, additive JSON CPU / CPU Stats sections, and multi-run aggregation in aggregate_average. JSON_handler now writes null for non-finite doubles so CPU metrics cannot break JSON.

Also adds tests/test_cpu_stats.py (schema, thresholds, multi-run, optional psutil cross-check), bash completion, and an adversarial-review Claude skill doc—not runtime behavior.

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

fcostaoliveira and others added 4 commits June 16, 2026 13:01
…turated

Supersedes #346 with an accurate, aggregate-aware, configurable design.

memtier now measures its OWN CPU so users can tell when the load generator
(not the server under test) is the bottleneck and results are skewed.

Two cooperating subsystems:
- Authoritative totals: getrusage(RUSAGE_THREAD) captured inside each worker
  at run start/end, accumulated across restarts. Exact user/sys CPU-seconds.
- Live advisory sampler: per-second pthread_getcpuclockid+clock_gettime from
  the monitor thread (non-intrusive; macOS uses Mach thread_info).

Surfaces:
- Console "CPU Utilization Summary" (total/user/sys, wall, cores used, avg %,
  peak %) on stderr so piped table output is not corrupted.
- JSON: aggregate "CPU" block (sibling of Runtime) + per-thread breakdown,
  plus per-second "CPU Stats" detail.
- --cpu-warn-threshold=PCT (default 95, mirrors --miss-rate-threshold). Live
  warning fires once per thread on first crossing; one end-of-run summary line
  per offending thread. No per-second spam.

Linux-only RUSAGE_THREAD guarded with #if defined; _GNU_SOURCE added for glibc.
Verified on glibc and musl/Alpine.

Tests: tests/test_cpu_stats.py (schema, high-load warning, threshold flag,
aggregate cores, psutil external cross-validation); psutil added to
test_requirements.txt.

Also adds .claude/skills/adversarial-review for maintainer-style review.

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

Round-1 adversarial review (15 agents) consensus fixes:

- Timing-window skew (central correctness fix): per-thread cores_used now
  divides CPU by a WALL bracket captured at the exact same points as the
  getrusage snapshots (thread entry/exit), accumulated across restarts via
  m_wall_usec_acc. The whole-process aggregate divides total CPU by the longest
  worker lifetime, so per-thread and aggregate figures are consistent and the
  denominator covers only the active window (not idle teardown). Removes the
  prior get_duration_usec() mismatch that inflated cores_used and could fire
  spurious warnings on short/TLS-heavy runs.
- avg_cpu_utilization_pct is now worker-CPU-only, so it cannot exceed 100% from
  main-thread overhead.
- Live sampler extracted into a cpu_live_sampler helper (SoC); skips finished/
  restarting workers so a joined/mid-restart pthread_t is never read.
- DRY: reuse ts_diff() for timeval deltas instead of a new tv_to_usec helper.
- JSON_handler::write_obj emits null for any non-finite double (NaN and +/-Inf),
  not just NaN.
- Tests: align high_load warn threshold with the load assertion; gate the
  end-of-run warning check on the authoritative JSON cores_used (not the
  per-second peak); make the threshold=100 case assert on the end-of-run line
  only; add test_cpu_multi_run for --run-count>1 aggregate CPU.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Round-2 adversarial verification fixes:

- HIGH: aggregate_average (multi-run AVERAGE report) computed
  avg_utilization_pct from total CPU (which includes the main thread),
  re-introducing the >100% inconsistency fixed for single runs. Carry a
  worker-only CPU total through cpu_summary.worker_total_seconds and base
  avg_utilization_pct on it in both the single-run and multi-run paths.
- Capture getrusage before gettimeofday at the end bracket too, so the wall
  window encloses the CPU window symmetrically (removes sub-us bias).
- Make the threshold=100 test assert warning-count consistency against the
  authoritative JSON (one 'of a core' line per thread with cores_used>1.0)
  instead of blanket silence, eliminating residual jitter flakiness.
- Comment accuracy: "summed active-serving wall" wording; JSON_handler include
  comment now references std::isfinite.

Co-Authored-By: Claude Opus 4.8 <[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

@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 2 potential issues.

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 4d5c2ab. Configure here.

Comment thread memtier_benchmark.cpp
thread->m_cpu_user_usec_acc += (unsigned long long) ts_diff(thread->m_cpu_start_ru.ru_utime, end_ru.ru_utime);
thread->m_cpu_sys_usec_acc += (unsigned long long) ts_diff(thread->m_cpu_start_ru.ru_stime, end_ru.ru_stime);
}
thread->m_wall_usec_acc += (unsigned long long) ts_diff(thread->m_wall_start_tv, end_tv);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wall time without CPU delta

Medium Severity

In cg_thread_capture_cpu_end, when the closing getrusage(RUSAGE_THREAD, …) call fails, the segment’s wall microseconds are still added to m_wall_usec_acc, but user/system CPU for that segment is not. Per-thread and aggregate cores_used, avg_cpu_utilization_pct, and end-of-run CPU warnings then divide incomplete CPU by a full wall bracket, understating utilization and possibly suppressing threshold warnings.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4d5c2ab. Configure here.

Comment thread tests/test_cpu_stats.py Resolved
The avg_cpu_utilization_pct consistency check still assumed the pre-consensus
relationship avg == 100*cpu_cores_used/threads. After avg was redefined to be
worker-CPU-only (main excluded) while cpu_cores_used stays whole-process, that
identity no longer holds: it is off by the main-thread share. Normally tiny, but
under TSAN the instrumented main thread's CPU is amplified, so the stale 0.5
tolerance failed (test_cpu_stats.py:240).

Reconstruct the exact invariants from the JSON instead, independent of run
timing: cpu_cores_used == total/wall, and avg == 100*(sum worker total/wall)/threads.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@fcostaoliveira
fcostaoliveira merged commit 4ebfa71 into master Jun 16, 2026
132 of 133 checks passed
@fcostaoliveira
fcostaoliveira deleted the feat/cpu-utilization-tracking branch June 16, 2026 19:21
fcostaoliveira added a commit that referenced this pull request Jun 16, 2026
…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]>
slice4e added a commit to slice4e/memtier_benchmark that referenced this pull request Aug 21, 2026
…ld_flag

test_cpu_warn_threshold_flag counted the substring "of a core" and compared
the result against the number of threads whose authoritative run-average
cores_used exceeds 1.0. But two different warnings contain that substring:

  memtier_benchmark.cpp:3059  "high CPU on thread %u: %.1f%% of a core ..."
  run_stats.cpp:2435          "thread %u averaged %.1f%% of a core over the
                               run ..."

Only the second is the end-of-run warning the assertion is about. With
--cpu-warn-threshold=100 the live per-second warning is also armed at 100%
of a core, and a 1s sample can legitimately exceed that because the wall
window and the CPU-clock sampling do not line up (the same file already
allows up to PER_THREAD_PCT_CEILING = 110%). When that happens the live
warning fires, end_warnings becomes 1 while over_one_core is 0, and the
test fails - intermittently, depending on runner load.

Match "of a core over the run", which is unique to the end-of-run message.
Verified against a live run: a single invocation emits both warnings, so
count("of a core") == 2 while count("of a core over the run") == 1.

Pre-existing since redis#471; unrelated to the JSON percentile-key change on
this branch.
fcostaoliveira added a commit that referenced this pull request Aug 26, 2026
…put (#517)

* fix(json): stop truncating/colliding deep-percentile keys in JSON output

result_print_to_json() built the "Percentile Latencies" key with
snprintf(buf, sizeof(buf) - 1, "p%.3f", quantile) into an 8-byte buffer.
The size-1 arg wasted a byte, and %.3f both rounds sub-100 quantiles up
to "100" and doesn't fit 3+ digit integer parts + 3 decimals + NUL.

For --print-percentiles requests with more than 2 decimal places (e.g.
99.999, 99.9999) this silently duplicated JSON keys (99.999 emitted
under "p99.99", already used by 99.99) and mislabeled 99.9999 as
"p100.0", colliding with an explicit p100 request. The plain-text
table was unaffected; only the JSON was wrong.

Fix: widen the buffer and use "%.10g", matching the format already
used for the equivalent text-table column header in run_stats::print()
(which fixed the same class of bug for the CLI table). This keeps every
requested quantile distinct and correctly labeled (e.g. "p50", "p99",
"p99.9", "p99.999", "p99.9999") without rounding tail values up to
"p100".

* fix tests to use the new format of json output

* fix(json): apply the same non-truncating percentile keys to Time-Serie

The per-second "Time-Serie" block had the same defect as "Percentile
Latencies": `snprintf(buf8, sizeof(buf)-1, "p%.2f", quantile)` rounds and
then truncates, so `--print-percentiles=99.99999,99.999999` emitted the
key "p100.0" twice and one value was silently overwritten in the JSON
object. Switch it to `p%.10g` into a 32-byte buffer so both JSON blocks
now agree with each other and with the stdout table headers.

BREAKING CHANGE: this deliberately drops the backwards-compat "pNN.NN"
key shape that the removed comment in result_print_to_json() promised
("legacy consumers and tests expect this exact format"). Time-Serie
percentile keys change p50.00 -> p50, p99.00 -> p99, p99.90 -> p99.9,
matching the "Percentile Latencies" change in the previous commit.
Consumers that hard-code these key names need updating; consumers that
iterate the dict are unaffected. Keeping the old shape is not possible
while also being collision-free, since no fixed-decimal format can
distinguish 99.99999 from 99.999999.

Tests updated: tests_oss_simple_flow.py (4 sites) and
test_monitor_input.py (2 sites).

* test(cpu): count only the end-of-run warning in test_cpu_warn_threshold_flag

test_cpu_warn_threshold_flag counted the substring "of a core" and compared
the result against the number of threads whose authoritative run-average
cores_used exceeds 1.0. But two different warnings contain that substring:

  memtier_benchmark.cpp:3059  "high CPU on thread %u: %.1f%% of a core ..."
  run_stats.cpp:2435          "thread %u averaged %.1f%% of a core over the
                               run ..."

Only the second is the end-of-run warning the assertion is about. With
--cpu-warn-threshold=100 the live per-second warning is also armed at 100%
of a core, and a 1s sample can legitimately exceed that because the wall
window and the CPU-clock sampling do not line up (the same file already
allows up to PER_THREAD_PCT_CEILING = 110%). When that happens the live
warning fires, end_warnings becomes 1 while over_one_core is 0, and the
test fails - intermittently, depending on runner load.

Match "of a core over the run", which is unique to the end-of-run message.
Verified against a live run: a single invocation emits both warnings, so
count("of a core") == 2 while count("of a core over the run") == 1.

Pre-existing since #471; unrelated to the JSON percentile-key change on
this branch.

* fix(json): narrow the percentile-key fix to only the colliding entries

Pushed by a maintainer (fcostaoliveira) in response to the review posted
on this PR, implementing the two asks from that comment:

1. Keep the legacy "p%.2f"/"p%.3f" key shape (byte-for-byte, including
   its original undersized-buffer truncation) for any quantile that
   doesn't collide with another requested quantile -- only the specific
   colliding entries fall back to full precision. The default config
   (50,99,99.9) is now byte-for-byte identical to pristine master; the
   64d863e/fbb94d9 commits on this branch renamed every key
   unconditionally, which is what the review pushed back on.

2. Added tests/test_json_percentile_key_collision.py: a regression test
   that reproduces the exact collision from this PR's own bug report
   (--print-percentiles=50,99,99.9,99.99,99.99999,99.999999) and asserts
   it fails on unpatched master (verified: master produces 5 keys for 6
   requested quantiles) and passes here. Also covers the default-config
   back-compat invariant, and a harder case where two quantiles are close
   enough that even "%.10g" can't tell them apart -- which needed a third
   escalation tier, "%.17g" (a double's round-trip-exact precision), to
   stay genuinely collision-free.

Consequently reverted the 4 test files this branch had updated to the
new key names (differential_redis_benchmark.py,
test_monitor_cluster_backpressure.py, test_monitor_input.py,
tests_oss_simple_flow.py) back to their original expectations, since the
default config they exercise no longer changes key shape.
tests/test_cpu_stats.py (the unrelated flaky-test fix) is untouched.

Does NOT resolve: the review's question about why this reverses the
back-compat precedent set in #379 for a similar bug in a different output
channel -- that's a judgment call for the PR author/maintainers, not
something this patch can answer on its own. Also left
run_stats.cpp:1931's pre-existing `sizeof(buf) - 1` idiom alone (out of
scope, noted only as a nitpick in the review).

This is a suggested patch, not a final answer -- happy to have any part
of it reverted, amended, or replaced if a different direction is
preferred.

* fix(json): key percentiles by whether the key names its quantile

c346638 escalates a percentile key when it collides with another
requested quantile. Collision is used there as a proxy for "this key is
wrong", but the implication only runs one way: a colliding key is wrong,
while a wrong key need not collide.

  --print-percentiles=99.9999
    legacy "p%.2f"  -> "p100.00" -> chopped to 6 chars -> "p100.0"
    legacy_keys_collide()? only one quantile requested -> false
    -> key stays "p100.0"

Nothing is missing and no key is duplicated; the JSON simply labels a
deep percentile as the maximum. The rule also misfires the other way:
when two keys collide both escalate, so a key that was already correct
moves because of its neighbour -- 99.9 is "p99.90" alone but becomes
"p99.900000000000006" when 99.900000001 is requested alongside it.

Ask the question about the key rather than about the set: use the
shortest format in the existing legacy -> %.10g -> %.17g ladder whose
output parses back to the quantile exactly. Collisions then become
impossible rather than detected -- an accepted key parses back to its own
quantile, so two distinct quantiles cannot produce the same one.

The result is that a key changes if and only if it was wrong. Full JSON
key-path diffs against pristine master are identical for the default
config, for an explicit 50,99,99.9, and for 50,99,100 (204/204 paths,
"p100.0" included).

c346638's four tests pass unchanged. Adds the lone-deep-percentile case,
which fails on master and on c346638, and pins that 99.9 keeps "p99.90"
when requested next to 99.900000001.

---------

Co-authored-by: fcostaoliveira <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant