Skip to content

feat: --realtime-latencies live per-second percentile output - #379

Merged
fcostaoliveira merged 3 commits into
masterfrom
feat/realtime-latencies
May 14, 2026
Merged

fcostaoliveira merged 3 commits into
masterfrom
feat/realtime-latencies

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Replaces the periodic [RUN #N ...] ops/sec progress line — which only ever exposed averages — with an opt-in per-tick block that surfaces miss ratio and the percentiles configured by --print-percentiles (both immediate and overall). Default behavior (no flag) is byte-identical to before, so existing log scrapers keep working.

$ ./memtier_benchmark --realtime-latencies --hide-histogram \
      --print-percentiles=50,99,99.9,99.99,99.99999,99.999999
[RUN #1  33%   1s] throughput 153,287 (avg: 153,287) ops/sec   8.62MB/sec (avg: 8.62MB/sec)   miss 49.86% (avg: 49.86%)
[RUN #1  33%   1s] latency  p50  1.215 (avg:  1.215)  p99  2.415 (avg:  2.415)  p99.9  9.151 (avg:  9.151)
[RUN #1  33%   1s] latency  p99.99 16.895 (avg: 16.895)  p99.99999 18.559 (avg: 18.559)  p99.999999 18.559 (avg: 18.559) ms
  • Each metric carries an immediate value and an (avg: X) overall counterpart. Overall percentiles come from a run-lifetime histogram maintained by hdr_add'ing each tick's instantaneous aggregate into a persistent accumulator (allocated once, freed after the loop).
  • The latency line wraps at 3 percentiles per line — line count is deterministic from the configured list, so the in-place TTY redraw stays stable across ticks.
  • On a TTY: redraws in place via \033[NA + \033[K. On non-TTY (CI logs, redirected files): appends, producing a clean per-second time series. Every emitted line carries the [RUN ... Ts] tag, so each line is independently greppable.
  • Drops the absolute ops counter from the rtl path — it scrolls fast and adds nothing the user can act on.

Drive-by fixes pulled in along the way

  • Percentile-label rounding: the legacy p%.*f formatter (capped at 3 fractional digits) was printing both 99.99999 and 99.999999 as p100, producing duplicate columns in the final stats table. Replaced with p%.10g everywhere a label is rendered (table headers, rtl output, statsd metric names). JSON keys keep their p%.2f / p%.3f shape for back-compat with existing consumers and the test suite.
  • Quantile storage precision: config_quantiles::quantile_list promoted from vector<float> to vector<double> (parse via strtod). Avoids deep-tail precision loss at storage — float couldn't represent 99.999999 distinctly from 100.
  • Final-table column alignment: percentile latency columns auto-size to fit headers like p99.999999 Latency (18 chars) instead of overflowing into the next column. Standard p50 / p99 / p99.9 columns keep width 15.

run_stats / client_group

  • Exposes get_total_hits() / get_total_misses() so the periodic loop can read per-second and cumulative cache stats without a full merge.

Test plan

  • tests/test_realtime_latencies.py::test_realtime_latencies_emits_two_line_block
  • tests/test_realtime_latencies.py::test_realtime_latencies_wraps_and_handles_deep_tail
  • tests/test_realtime_latencies.py::test_default_progress_line_unchanged
  • make format-check clean
  • Manual smoke tests against local Redis (1, 3, 6 percentiles; TTY and piped-to-file)
  • CI: code-style.yml, asan.yml, ubsan.yml, tsan.yml, ci.yml green

🤖 Generated with Claude Code


Note

Medium Risk
Touches the main progress/metrics loop, latency histogram aggregation, and stats counters; while gated behind a new flag, mistakes could affect live reporting and StatsD percentile emission.

Overview
Adds opt-in --realtime-latencies to replace the single stderr progress line with a per-second block showing throughput, miss ratio, and the configured --print-percentiles as current vs overall percentiles (TTY redraw vs non-TTY append).

Promotes --print-percentiles storage/parsing from float to double and updates percentile labeling/formatting to avoid deep-tail rounding collisions, including auto-sizing percentile table columns and stabilizing StatsD percentile metric names.

Extends stats plumbing to expose cumulative GET hits/misses (run_stats, totals, client_group) for live display, updates bash completion and the man page for the new flag, and adds a new tests/test_realtime_latencies.py suite covering output shape, wrapping, deep-tail labels, and legacy-mode regression.

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

Replaces the periodic '[RUN #N ...] ops/sec' progress line — which only
exposed averages — with a per-tick block that surfaces miss ratio and the
percentiles configured by --print-percentiles. Default behavior (no flag)
is byte-identical to before, so existing log scrapers keep working.

Example (--print-percentiles=50,99,99.9,99.99,99.99999,99.999999):

    [RUN #1  33%   1s] throughput 153,287 (avg: 153,287) ops/sec   8.62MB/sec (avg: 8.62MB/sec)   miss 49.86% (avg: 49.86%)
    [RUN #1  33%   1s] latency  p50  1.215 (avg:  1.215)  p99  2.415 (avg:  2.415)  p99.9  9.151 (avg:  9.151)
    [RUN #1  33%   1s] latency  p99.99 16.895 (avg: 16.895)  p99.99999 18.559 (avg: 18.559)  p99.999999 18.559 (avg: 18.559) ms

* Each metric carries both an immediate value and an '(avg: X)' overall
  counterpart. Overall percentiles come from a run-lifetime histogram we
  hdr_add into across ticks (allocated once, freed after the loop).
* Throughput line: ops/sec (cur/avg), bytes/sec (cur/avg), miss ratio
  (per-second / cumulative). The legacy absolute ops counter is dropped
  under --realtime-latencies — it scrolled fast and meant little.
* Latency line wraps at 3 percentiles per line so a 6-percentile config
  doesn't blow out the terminal. Line count is deterministic given the
  configured list, so the in-place TTY redraw stays stable across ticks.
* On a TTY the block redraws in place via \033[NA + \033[K. On non-TTY
  (CI logs, redirected files) it just appends, producing a clean
  per-second time series each line of which can be parsed independently
  (every line carries the [RUN ... Ts] tag).

Supporting fixes pulled in along the way:

* Percentile labels: replace p%.*f / p%g with p%.10g everywhere a label
  is rendered (final stats table, --realtime-latencies output, statsd
  metric names). The previous formatter capped at 3 fractional digits
  and silently rounded 99.99999 and 99.999999 both to 'p100', colliding
  in the table output. JSON keys keep their p%.2f / p%.3f shape for
  back-compat with existing consumers and the test suite.
* Promote config_quantiles::quantile_list from vector<float> to
  vector<double> (parse via strtod). Avoids deep-tail precision loss at
  storage time — float couldn't represent 99.999999 distinctly from 100.
* Auto-size percentile latency columns in the final stats table so long
  headers like 'p99.999999 Latency' don't spill into the adjacent column
  and break the table separators. Standard p50/p99/p99.9 keep width 15.

run_stats / client_group:

* Expose get_total_hits() / get_total_misses() so the periodic loop can
  read per-second and cumulative cache stats without a full merge.

Tests:

* tests/test_realtime_latencies.py covers (1) the 2-line block shape with
  immediate + (avg: X) for ops/sec, bytes/sec, miss%, and each configured
  percentile, (2) the 6-percentile wrap path, (3) deep-tail p99.99999 /
  p99.999999 labels not rounding to 'p100' (both in the stderr stream and
  the final stats table header), and (4) a regression test that the
  default progress line (no flag) is byte-identical to before.

Man page and bash completion updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@jit-ci

jit-ci Bot commented May 14, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

Comment thread run_stats.cpp Resolved

@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.

There are 2 total unresolved issues (including 1 from previous review).

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 fabd1c0. Configure here.

Comment thread run_stats.cpp
const double quantile = quantile_list[i];
char quantile_header[8];
// Backwards-compat JSON key shape "pNN.NN" (legacy
// consumers and tests expect this exact format).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

JSON quantile keys collide for deep-tail percentiles

Medium Severity

The quantile_header[8] buffer used with snprintf(..., sizeof(quantile_header) - 1, "p%.2f", quantile) produces colliding JSON keys for deep-tail percentiles. The PR promotes storage to double specifically to support values like 99.99999 and 99.999999, but %.2f rounds both to "p100.00" (7 chars), which then gets truncated to "p100.0" by the size-7 limit. This produces duplicate JSON keys, breaking parsers that don't accept repeated keys.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit fabd1c0. Configure here.

paulorsousa
paulorsousa previously approved these changes May 14, 2026
Two CI regressions caught by the first --realtime-latencies push, both
flagged by Cursor Bugbot:

* TSAN/ASAN failure: get_total_hits()/get_total_misses() iterated
  m_stats (std::list<one_second_stats>) while worker threads concurrently
  appended via roll_cur_stats() -> m_stats.push_back(). Even though
  std::list::push_back doesn't invalidate iterators, the read-during-write
  is still a data race under TSAN and qualitatively unsafe.

  Fix: add m_hits/m_misses scalar counters to the totals struct (same
  pattern as the existing m_ops/m_bytes_rx/m_bytes_tx fields) and bump
  them from update_get_op() via a new totals::update_op overload. The
  getters now return m_totals.m_hits/m_misses — the same benign-race
  read pattern that get_total_ops() has used since forever.

* macOS-openssl-1-0-2 / macOS-openssl-1-1 build failure: Apple clang on
  those targets doesn't enable C++11 by default, so the inline
  `auto comma_fmt = [](...) { ... };` lambda fails to parse with
  "expected expression". Linux clang/gcc in the other CI jobs were fine
  because they default to a newer C++ standard.

  Fix: hoist the helper to a file-scope `static void format_with_commas(
  unsigned long, char*, size_t)` next to size_to_str() and call it from
  the rtl block. No lambdas anywhere in the rtl path now.

Local TSAN-clean: tests/test_realtime_latencies.py all 3 tests pass
under OSS standalone.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed both Cursor Bugbot findings in 7f7262f:

1. Unsafe list iteration in get_total_hits/misses (run_stats.cpp L404) — fixed properly. Replaced the m_stats iteration with scalar counters on the totals struct (new m_hits / m_misses fields + a totals::update_op overload). The getters now return m_totals.m_hits / m_totals.m_misses — same benign-race scalar-read pattern that get_total_ops() has used since forever, and what TSAN tolerates. Confirmed by the TSAN/ASAN job failures clearing locally.

2. JSON quantile keys collide for deep-tail percentiles (run_stats.cpp L995) — deliberately deferred for this PR. The existing keys (p50.00, p99.00, p99.90) are pinned by tests_oss_simple_flow.py and test_monitor_input.py and almost certainly by downstream JSON consumers; changing the format is a back-compat break that wants its own PR with a tests-and-consumers migration. The collision is only triggered when a user passes a percentile > 99.99 AND wants the JSON output to disambiguate it — relatively niche. The --realtime-latencies stderr output and the final stats table column headers already handle deep-tail labels correctly via %.10g. Filed for a follow-up.

The macOS-openssl-1-0-2 / 1-1 build failure (Apple clang without C++11-on-by-default rejecting an inline auto = []() {...} lambda) is also fixed in 7f7262f by hoisting the helper to a file-scope static format_with_commas() next to size_to_str().

@fcostaoliveira
fcostaoliveira merged commit fe53c28 into master May 14, 2026
70 checks passed
@fcostaoliveira
fcostaoliveira deleted the feat/realtime-latencies branch May 14, 2026 22:32
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
fcostaoliveira added a commit to slice4e/memtier_benchmark that referenced this pull request Aug 24, 2026
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 redis#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.
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]>
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
…percentiles (#386)

Add --latency-window=N (default 60, 0 disables, max 3600) to --realtime-latencies, which prints labelled inst, win<N>s and overall latency rows with each row's sample count. For example, --latency-window=60 --print-percentiles=99.9999 reports the last minute's p99.9999.

Build the window and overall rows from the per-second histograms each client has completed, drained once per tick and shared with the Prometheus exporter. The overall row previously summed live partial-second snapshots and lost samples, e.g. n=0 of 1000 and n=9 of 12; it now matches the JSON total count exactly.

A percentile p needs at least 100/(100-p) samples (1,000,000 for p99.9999). Rows mark an unresolved percentile with '*', and when --requests or --rate-limiting bound the samples, memtier warns before the run about percentiles the run or the window can never resolve. The bounds include the per-connection burst on connect and the extra completed second a window can span. In cluster mode the rate limit applies per endpoint connection, so the check runs once the first topology is known.

The --realtime-latencies line format changes; default progress output and the JSON, CSV and HDR outputs are unchanged.

The overall-row sample loss was introduced in fe53c28 (#379) and is present in 2.4.0 through 2.5.2.

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

2 participants