Skip to content

Add --latency-window sliding-window tail latency and flag unresolved percentiles - #386

Merged
fcostaoliveira merged 7 commits into
masterfrom
feat/latency-sliding-window
Oct 24, 2026
Merged

fcostaoliveira merged 7 commits into
masterfrom
feat/latency-sliding-window

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Under --realtime-latencies there is no way to see the tail latency of a recent interval. You get the last second (inst) or the whole run (overall), but not, say, the last 60 seconds' p99.9999. Nothing flags tail percentiles that don't have enough samples to mean anything either. p99.9999 needs 1,000,000 samples, so with fewer it is just the maximum, and a rate-limited run can make that permanent without anyone noticing.

The existing overall row also loses samples (bug, since 2.4.0).

Root cause (overall row)

The main loop builds overall by adding up snapshots of each client's live, partial second (copy_inst_histogram). Each client resets that histogram on its own second boundary. Any samples recorded between the main loop's last snapshot and the client's reset are never counted. Two examples on master:

  • A short --requests run finishes before any snapshot: overall shows nothing, although the JSON reports 1000 samples.
  • The test_progress_interval peer test counted 9 of 12 samples. The test comment already noted that a sample "can legitimately disappear".

The first version of this PR filled its window ring from the same snapshots, so it had the same loss.

Fix

  • --latency-window=SECS (default 60, 0 disables, max 3600) adds a win<N>s row: the percentiles of every sample completed in the last N ticks.
  • Data source: master already folds each client's completed second into a pending histogram for Prometheus. That fold is now also enabled for --realtime-latencies. The main loop drains it once per tick, and the one drain feeds Prometheus, the window ring and the overall row. Every sample is counted exactly once, and no per-client memory is added. The win and overall rows lag inst by up to one second. inst and StatsD are unchanged.
  • Window: one dense histogram per window second (about 21 KB each, so 1.3 MB for 60 s), allocated on first use and stamped with its tick time. Each rendered frame merges only the slots from the last N seconds of wall-clock time with hdr_add and runs one batch percentile query, so win60s stays accurate if the progress loop drifts (e.g. under sanitizers). Empty ticks still take a slot. The window is on by default (60 s) under --realtime-latencies; --latency-window=0 disables it.
  • Sample sufficiency:
    • Every row shows its sample count n= (987, 12.3K, 1.23M; truncated, never rounded up).
    • A percentile p computed from fewer than ceil(1/(1-p)) samples is marked * (100 for p99, 1M for p99.9999).
    • Before the run, memtier warns when --requests or --rate-limiting mean the run, or the window, can never reach that count. For example, --rate-limiting=100 × 160 connections gives at most 960,000 samples per 60 s window, which is not enough for p99.9999. The run-level warning also covers the final results table, so it is printed with or without --realtime-latencies (e.g. -n 10 -c 1 -t 1 warns for the default p99/p99.9). In cluster mode the rate limit applies per endpoint connection, so the check runs once, after topology discovery, using the same connection count as the Rate limit: … aggregate target line.
    • --latency-window without --realtime-latencies gets a warning.
  • The row layout keeps a fixed line count per tick, so the TTY in-place redraw stays stable.
[RUN #1  25%   1s] latency [inst    ] n=992     p50  0.087   p99  0.615   p99.9  3.135*
[RUN #1  25%   1s] latency [inst    ]           p99.9999  3.231*
[RUN #1  25%   1s] latency [win60s  ] n=0       p50    -     p99    -     p99.9    -
...
[RUN #1 100%   4s] latency [overall ] n=228.3K  p50  0.143   p99  1.535  ms

Output change: the realtime latency lines move from cur (avg: avg) pairs to labeled rows with n=. --realtime-latencies is opt-in, and the default progress line is unchanged (test_default_progress_line_unchanged).

Tests

  • test_latency_window_counts_every_sample_and_marks_unresolved: in a 1000-request run, the last frame's win60s and overall rows show n == JSON Totals Count == 1000. p99.9 (needs 1000) is not marked, p99.99 is, and the up-front warning names p99.99 only. On every frame, each value's marker must match its row's n.
  • test_latency_window_warns_when_rate_limit_cannot_fill_it: the window warning fires exactly once with the per-endpoint bound (standalone and cluster), the run warning does not.
  • test_latency_window_expires_old_seconds: a 1 s window drops expired seconds.
  • test_progress_interval_keeps_latency_samples_from_hidden_ticks now asserts the exact n=12.
  • Mutant check: going back to the live-snapshot source fails both exactness tests (n=0 vs 1000, n=9 vs 12).
  • Locally: test_realtime_latencies.py 8/8 and test_progress_interval.py 6/6 pass (standalone, authenticated). make format-check is clean, and the build adds no new warnings.
  • --latency-window is added to cli_fuzz.py.

Not in this PR (follow-ups): window percentiles in JSON, StatsD and Prometheus, and a simultaneous 30 s + 60 s window.

Affected versions

The overall row sample loss was introduced in fe53c28 (#379, --realtime-latencies) and is present in every release since: 2.4.0 through 2.5.2. The window and the sufficiency markers are new.

🤖 Generated with Claude Code


Note

Medium Risk
Changes main-loop latency aggregation and realtime stderr format (opt-in), but corrects overall percentile data and adds bounded-run warnings; cluster percentile checks depend on late topology discovery.

Overview
--realtime-latencies now prints three labeled rows per tick—inst, win<N>s (new --latency-window, default 60s), and overall—each with n= sample counts instead of side-by-side cur (avg: avg) pairs. Percentiles with too few samples are marked *, and startup warnings flag unresolvable tails when --requests or --rate-limiting cap throughput (cluster uses topology-derived connection fan-out).

win and overall are built from drained completed client seconds (same pending path as Prometheus), fixing overall sample loss from live partial-second snapshots. A wall-clock histogram ring backs the sliding window; Prometheus and realtime share one drain per tick when both are active.

Docs, man page, bash completion, and tests cover the new flag, row format, warnings, and exact sample accounting.

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

…encies

Adds a load1/5/15-style sliding window to the live latency block. The per-tick
output now emits three labeled rows per configured percentile:
  inst    — last tick
  win<N>s — sliding window (default 60s, configurable, 0 disables)
  overall — full run

The window is implemented as a ring of cloned hdr_histograms (one per second);
each tick we materialize the windowed percentile by hdr_add-ing every live slot
into a reused scratch histogram. Empty ticks consume a slot so the window
measures wall-clock seconds rather than seconds-with-traffic. Long
--print-percentiles lists wrap to multiple lines per row with deterministic
line count, preserving the TTY cursor-up redraw.

Adds three RLTests: three-row layout assertion, --latency-window=0 suppression,
and ring-populated sanity. Existing --realtime-latencies tests updated for the
new label-row layout.

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

jit-ci Bot commented May 18, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

The macOS openssl-1.0.2 / 1.1 CI jobs don't pick up -std=c++11 and
parse 'vector<vector<string>>' as the >> shift operator, breaking
those builds. Use a typedef so the closing token sequence never appears.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@fcostaoliveira fcostaoliveira modified the milestone: 2.4 Jun 1, 2026
fcostaoliveira and others added 2 commits October 24, 2026 06:50
…20261024

# Conflicts:
#	bash-completion/memtier_benchmark
#	memtier_benchmark.cpp
…solved percentiles

The window ring was filled from the live per-client second the main loop
samples, which a client resets on its own boundary: samples between the last
snapshot and the reset were lost (a short --requests run showed n=0 of 1000),
and the 'overall' row had the same problem. Fold completed seconds for
--realtime-latencies as well as Prometheus, drain them once per tick and
share the drain between both, so the win and overall rows count every sample
exactly once.

Each row now shows its sample count n. A percentile p needs at least
ceil(1/(1-p)) samples (1M for p99.9999); with fewer it is just the maximum,
so it is marked '*'. When --requests or --rate-limiting bound the sample
count, warn before the run about percentiles the run or the window can never
resolve.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira fcostaoliveira changed the title feat: --latency-window sliding-window tail latency for --realtime-latencies Add --latency-window sliding-window tail latency and flag unresolved percentiles Oct 24, 2026
@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review. A human maintainer's review is still required before merge.

Thanks for this. I went through the whole thing, and I think moving the win/overall rows onto the completed-second drain is the right call. The n=12 assertion in test_progress_interval.py and the n == JSON Count == 1000 check are the kind of fails-on-master regression tests this needs. A few comments below.

  1. Splitting out the bugfix. The overall sample loss has been in every release since 2.4.0, so it's a natural candidate for a 2.5.x patch. Right now it's tied to a new flag and a reworked realtime layout, which would make a cherry-pick to the release branch awkward. Did you consider putting the drain change in its own PR, with the run_stats.cpp fold, the shared drain_completed_latency() and the test_progress_interval change? The window and * markers could then follow on top.

  2. Realtime output format. I know --realtime-latencies is opt-in and the default progress line is untouched. Still, anyone scraping the p99 X (avg: Y) lines breaks. With the window on by default, every existing user also gets three times as many latency lines per tick. Even --latency-window=0 doesn't bring back the old shape. Was a less disruptive option considered? For example, the window could be off unless --latency-window is given, or the old cur (avg: …) layout could be kept when the window is disabled. If the break stays, I think it needs a clear line in the release notes.

  3. New warnings in default mode. warn_unresolvable_percentiles() now runs without --realtime-latencies too. So any quick small -n run, like -n 100 -c 1 -t 1, now prints a p99.9 warning on stderr. The reasoning makes sense for the final table, but it's a change to default output that a lot of smoke scripts and CI jobs will hit. I wonder if it should be limited to --realtime-latencies, or to explicitly requested percentiles, at least to start with.

  4. Per-client cost. summarize_current_second() now does an hdr_add into the pending histogram every second for every client when realtime is on. Prometheus already pays this cost, so it's probably fine. Did you check it with a high -c/-t count, given it runs under m_inst_histogram_mutex?

  5. percentile_min_samples(). The snapping logic (400 * DBL_EPSILON, capped at 7 digits) is fairly subtle for what it does. I may be wrong, but deriving the digit count from the percentile string the user typed might be simpler and easier to reason about. Not blocking.

  6. Cluster fan-out. s_rate_limited_connections comes from the first topology only and never resets. That's consistent with checking once per process, but a later topology change means the bound can go stale. A short comment saying that's intentional would help. This may also be worth a second look from whoever owns cluster topology handling.

  7. Nitpicking: test_latency_window_ring_smooths_spikes only checks that the window p99 is positive at some point. It doesn't test smoothing, so maybe rename it to match what it asserts.

The core fix looks solid. I'd mainly like to hear your thoughts on splitting the backportable fix out, and on the output and warning compatibility, before this merges.

(I'd post this as a comment, not a formal block.)

…dow by time

In cluster mode --rate-limiting applies to each endpoint connection, so the
up-front bound used clients x threads and could warn falsely. Run the check
from the cluster topology summary, once, with the same request-generating
connection count as the aggregate rate line.

Stamp each window slot with its tick time and merge only the last N seconds,
so win<N>s stays a wall-clock window when the progress loop drifts. Move the
60 second default into config_init_defaults().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Pushed 2ace4c9, which also fixes a real bug: the new window-expiry test was red only in the OSS-cluster jobs.

  • Cluster-mode warning bound (bug, fixed). In cluster mode --rate-limiting applies to each endpoint connection, so the up-front bound of clients × threads undercounted by the number of primaries and could warn falsely. The check now runs once, from the cluster topology summary, with the same request-generating connection count as the Rate limit: … aggregate target line. test_latency_window_warns_when_rate_limit_cannot_fill_it asserts the exact per-endpoint bound in both standalone and cluster mode. The expiry test no longer hard-codes a standalone per-second rate.
  • Default-on window. This is deliberate. The window row is the feature; the requirement it comes from is "report the last 60 s p99.9999". --realtime-latencies is opt-in and young (2.4.0), and its layout already changes in this PR for everyone who uses it, because the inst/overall rows gain n= and labels. Making the window opt-in on top of that would keep the format change but hide the useful part. JSON/CSV/HDR output and the default single-line progress are unchanged (test_default_progress_line_unchanged). --latency-window=0 gives the inst/overall-only layout.
  • Warnings without --realtime-latencies. Also intended. The run-level warning is about the final results table, which has the same resolution problem: p99.9 of 10 samples is the max. It only fires when --requests or --rate-limiting make the sample bound smaller than the percentile needs, so default runs (10,000 requests × 50 clients × 4 threads) don't warn. The PR description now says so.
  • Seconds vs. ticks. Fixed rather than documented. Each slot is stamped with its tick time, and a frame merges only slots from the last N seconds of wall-clock time, so win60s stays a 60-second window if the loop drifts.
  • Default location. Moved into config_init_defaults() (if (!cfg->latency_window_set) cfg->latency_window_secs = 60;).

Local: test_realtime_latencies.py 8/8 and test_progress_interval.py 6/6 (standalone, authenticated); format-check clean. Hosted CI is running on the new head.

fcostaoliveira and others added 2 commits October 24, 2026 07:48
2ace4c9 called the check from cluster_client, which broke make check: the
unit programs link cluster_client.o without memtier_benchmark.o. Publish the
first topology's rate-limited connection count from cluster_client instead,
and let the main loop warn once it is known, restarting the realtime frame so
the TTY redraw does not overwrite the warning.

Document that the window/overall rows wait for each client to complete its
second, that the check uses the total sample count, and the percent form of
the sample bound. Drop a stale comment and a redundant initialization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A rate-limited connection is granted a burst of request_per_interval on
connect, and the window merges the last N ticks of completed client
seconds, which can span N + 1 seconds. Include both in the run and
window bounds, so a percentile the warning says the window cannot
resolve is always marked '*'.

Snap 100/(100-p) to the significant digits that survive the binary
rounding of p, so p99.999999 needs 1e8 samples rather than slightly
more. Say an under-sampled percentile is not resolved instead of
claiming it reports the maximum, which HDR rounding does not
guarantee. Describe the inst row as each client's current second, widen
the count column for 100M+ samples, start the cluster warning on a new
line after single-line progress, and skip the unused realtime drain
histogram when Prometheus provides one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the re-review. Answers for head 2d66490 (all seven independent review lenses have now looked at it; four approve it as-is, the remaining three are still running):

  1. Splitting out the bugfix. I'm keeping this as one PR on master: the new rows are the reason the drain exists, and its tests (n == JSON Count, overall n=12) exercise both. If maintainers want a 2.5.x patch, I'll open a separate minimal backport against the 2.5 branch with just the run_stats.cpp fold, the drain for the overall row and the test_progress_interval assertion, instead of cherry-picking this squash.

  2. Realtime output format. Intentional, and it will be called out in the release notes. --realtime-latencies is opt-in, and the old cur (avg: …) row was itself built from the lossy partial-second snapshot, so it can't be kept as is. Every row is now labelled with its sample count. --latency-window=0 gives two rows (inst, overall). The default progress line and every file output (JSON, CSV, HDR) are unchanged; an output-compatibility review checked each one against master.

  3. Warnings in default mode. This is deliberate. Default --test-time runs and ordinary -n runs stay quiet. The warning only appears when --requests or --rate-limiting make a percentile in the final table impossible to resolve, e.g. -n 100 -c 1 -t 1 cannot produce a meaningful p99.9. It goes to stderr and the exit code is unchanged, so scripts that parse stdout or JSON are unaffected.

  4. Per-client cost. It's one hdr_add per client per completed second, under the per-client mutex, which the worker holds for only that one fold and the main thread for only one drain per tick. I ran -t 8 -c 50 (400 clients) for 20 s, twice each with and without --realtime-latencies, against a local authenticated server:

    • off: 257K and 243K ops/s, 89.2 s and 87.9 s user+sys CPU
    • on: 235K and 261K ops/s, 86.8 s and 92.0 s user+sys CPU

    The difference is within run-to-run noise on this shared host. TSan and ASan runs with Prometheus plus realtime and up to 6 threads are clean.

  5. percentile_min_samples(). By the time this function runs, the percentile is a double in quantile_list; the original string isn't kept. The snapping is exact from p0 to p99.99999999. Two reviewers checked it on 20 and 26 percentiles, including p99.97 → 3334 and p99.999999 → 1e8.

  6. Cluster fan-out. Yes, the bound comes from the first committed topology and is checked once per process. It's documented as known once the first topology is committed. A partial first map that later heals can exceed it; one reviewer reproduced 9928 samples against a stated 9600. I'll file that as a follow-up issue rather than grow this PR.

  7. test_latency_window_ring_smooths_spikes. Fair point. It checks that the window row reports a value; spike-free smoothing isn't asserted. The window logic itself is covered by test_latency_window_counts_every_sample_and_marks_unresolved and test_latency_window_expires_old_seconds. I'll rename it if another push is needed.

@fcostaoliveira
fcostaoliveira merged commit 9bf3960 into master Oct 24, 2026
150 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
Follow-up to #386.

percentile_min_samples() snaps 100/(100-p) to the intended value only when it lies within the error from parsing p as a double (half an ulp of 100, doubled for margin, amplified by 100/(100-p)); otherwise it rounds up, using an exact integer power-of-ten unit. p99.99991 now needs 1111112 samples (was 1111111) and p99.9999999999 needs 1e12 (was 999999999999).

The realtime rows and the percentile warnings print p%.15g, so 12 nines no longer show as p100; the final table and JSON labels are unchanged. The --requests run warning drops "about", since that bound is exact. A comment notes that the cluster bound comes from the first topology (#825).

Add test_percentile_sample_thresholds, which pins the thresholds against exact ceil(100/(100-p)), and assert that a rate-limited window run prints exactly one percentile warning, which catches a cluster run that also applies the pre-run check without the endpoint fan-out. Rename the window-row test, make the Python threshold helper exact, and fix the README example spacing and a split help string.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 25, 2026
With --cluster-mode --rate-limiting, the up-front percentile warning
(#386) took its sample bound from the first committed topology only.
Since #799 a run can start on a partial slot map, and when the map heals
memtier opens more endpoint connections, each with its own rate limit.
On a 3-primary cluster with one primary's slots restored 1 s into a 6 s
run at 800 req/s, memtier warned that p99.99 "records at most about
9664" and "will not be resolved", then recorded 10187 samples and
resolved it.

The cluster client now publishes the largest rate-limited connection
fan-out committed so far, written once per topology commit under the
topology-summary mutex. The main thread's once-a-second check remembers
what it said about each percentile, for the run and the window, and when
the fan-out grows prints one header line and then either the warning
again with the raised bound or a "may now be resolved" note. A
--requests bound does not depend on connections and is not repeated. The
progress-line newline is printed only when there is a warning.

test_cluster_unowned_slots.py heals the fake cluster after memtier's
first warnings and checks the exact update lines, the window '*' marks,
and that a --requests warning is not repeated.

Fixes #825

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.

1 participant