Skip to content

Avoid histogram copies and batch latency percentile queries - #564

Merged
fcostaoliveira merged 4 commits into
masterfrom
optimize/hdr-percentile-queries
Oct 13, 2026
Merged

fcostaoliveira merged 4 commits into
masterfrom
optimize/hdr-percentile-queries

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Per-second latency summaries currently deep-copy a dense histogram and copy the percentile list for every client/command, then allocate temporary query results. Live display, StatsD, JSON, and the final table also repeat scalar percentile scans; the table rebuilds its totals histogram for every percentile column.

Pass summary inputs by const pointer/reference and reuse one scratch vector per client. Batch live and final queries in configured order, share instantaneous results between realtime display and StatsD, and merge the final table's total histogram once. JSON output also borrows its input vectors instead of copying them. The scalar-query adapter preserves p0, empty histograms, duplicate percentiles, and unsorted input; existing per-second history retains its previous batch-query semantics.

This is stage 2 of the HDR rolling-window plan, following merged #563. It adds no rolling window or sample-recording work.

Validation:

  • All four make check programs and make format-check pass on Linux ARM64 GCC 13.
  • HDR compatibility/query/summary tests pass ASan+UBSan, including scratch reuse, p0/p100, empty, sparse, broad, duplicate and unsorted percentile lists.
  • Targeted HDR export, JSON percentile-key, realtime, StatsD and arbitrary-command suites pass over plaintext and TLS. External Graphite and two RESP3-only cases skip in this local environment; mock UDP StatsD tests run. Both command-grouped and per-line final tables pass TLS tests.
  • New integration coverage independently decodes V2 histogram counts and checks exact JSON/table percentile values and requested column order, including empty command rows.

Component measurements (shared Linux ARM64 Colima VM on Apple M6, -O3, five samples per case; 10 or 1,000 populated bins): summaries fall from 3.4–5.1 µs to 0.19–0.23 µs. Three/nine-percentile queries are 2.4–6.7× faster; a single-percentile query adds roughly 6–7 ns. These are component timings, not application throughput results or x86 AVX2 measurements.

The summary path removes four temporary allocations per invocation after output-vector warmup, retaining 24 + 8*Q bytes per client for scratch on this 64-bit platform (48 bytes at the default three percentiles, excluding allocator overhead). Live queries retain approximately 32*Q bytes per enabled query plus vector metadata; the final table temporarily caches 8*rows*Q bytes of values. No histogram ring is allocated.

Five paired, alternating-order TLS sanity runs per case (pipeline 16, 3 threads × 10 clients, 10 seconds each, fixed Redis per comparison, separate CPU affinity):

Output Stage 1 median ops/sec Stage 2 median ops/sec Throughput change CPU/op change
Default, three percentiles 2,757,357 2,757,725 +0.013% −0.734%
Realtime, six unsorted percentiles 2,819,690 2,822,539 +0.101% +0.256%

Throughput differences are within observed variation. These short shared-VM runs can be server-limited; they do not establish portable gains or statistical equivalence. Full measurements, ranges, memory costs and limitations · Raw samples, summaries and provenance.

Measured commit 6faecef and initial rebased head feb0448 have identical source trees. Follow-up cbf1211 fixes macOS unit-test OpenSSL include paths and small final-table/test-review nits; local checks and TLS HDR/table tests re-pass. Full cross-platform CI is running on the draft.


Note

Medium Risk
Touches latency reporting across live UI, StatsD, JSON, and final tables; behavior is intentionally preserved but regressions would affect published percentile metrics.

Overview
Introduces latency_percentiles to query many configured percentiles in one HDR batch while keeping the old scalar behavior for p0, empty histograms, duplicate/unsorted lists, and non-finite inputs.

Live path: realtime latency display and StatsD now compute instantaneous percentiles once per tick (shared scratch across ticks) and pass precomputed values into statsd_publish_tick instead of re-scanning the aggregated histogram.

Reporting path: per-second summarize_quantiles takes histograms by pointer and reuses one m_quantile_values scratch per client; final table output merges the totals histogram once and batches lookups across all percentile columns and command rows; JSON percentile output uses the same helper. Several APIs stop copying large vectors (const references).

Build/test updates wire the new header into hdr_histogram_test (plus run_stats_types, OpenSSL/coverage flags) and add unit, integration, and StatsD coverage for batched vs scalar parity and table/JSON column order.

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

@github-actions

github-actions Bot commented Oct 12, 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 diff. Output stays the same: the table headers, column order, --- for empty rows and the JSON p%.3f keys are all unchanged. The new test covers this well. It decodes the V2 histogram on its own, checks Totals against the merged Sets+Gets, and uses an unsorted p0/p100/deep-tail list, so a doubled or missing totals merge would fail it. The empty-row condition in print_quantile_latency_columns (!arbitrary && row + 1 < size) matches the old has_set/get/wait_ops behavior, and arbitrary-command rows and Totals are still always computed. So I don't see a compat concern. A few small things:

  • In latency_percentiles::calculate() the return value of hdr_value_at_percentiles() is ignored. summarize_quantiles() checks the same call (if (result != 0) return;). I don't think it can fail with the inputs we pass today. But if it ever does, I guess we'd silently publish stale values from m_sorted_values left over from the previous tick, to StatsD and the realtime display. Would it be worth falling back to the scalar loop on a non-zero result, as you already do for the non-finite/empty case?
  • hdr_histogram_test now inherits all of memtier_benchmark_CPPFLAGS (and CODE_COVERAGE_LIBS) because it pulls in run_stats_types.cpp. That makes sense for the OpenSSL include paths. It does mean the unit test now depends on whatever ends up in the main binary's flags later, so maybe worth keeping in mind.
  • Nitpicking: in the realtime block, bool cur_samples = inst_samples; is just an alias now, so it could be dropped and inst_samples used directly.

There's one existing inconsistency the PR doesn't change: per-second history still uses the batch semantics, where p0 gives the upper equivalent value. The new live/final paths use the scalar ones. You call this out in the header comment, so it's fine for this stage. It may be worth a follow-up so the per-second JSON and the final summary can't disagree on p0.

This looks solid to me. I'd only want the return-value question answered before it merges.

(would file this as a comment, not a formal block)

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed the review nits in cbf1211:

  • Final rendering uses values[row].empty() for dashes, so it follows the cached row decision.
  • snprintf receives the full buffer size.
  • The independent V2 rank decoder now reads significant figures and lowest discernible value from the header and uses struct.calcsize for header length.
  • Tracked the legacy per-second p0/empty-history inconsistency as an explicit follow-up decision in the stage 2/rolling-window plan. This optimization intentionally preserves both existing behaviors.

Paired TLS results and full raw evidence are now attached to the PR description: default throughput +0.013%, CPU/op −0.734%; realtime throughput +0.101%, CPU/op +0.256%. Throughput changes fall within the observed spread. These are local sanity measurements, not a portable performance claim.

The initial macOS failures exposed missing configured OpenSSL includes in the expanded HDR unit-test target; it now inherits application CPPFLAGS. Four local unit programs, formatting, and TLS V2/JSON/table tests re-pass. CI is rerunning on this head.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The follow-up plan now explicitly tracks p0/empty-history normalization before stages 3/4; the link and local TLS measurements are in the description and preceding reply.

I kept the scratch-reuse test with the HDR compatibility tests so it calls the production one_sec_cmd_stats implementation. A separate executable would still need the same config headers/include flags, while a duplicated summary implementation would weaken that check. The new CPPFLAGS dependency is intentional; the OpenSSL 3, 1.1 and 1.0.2 macOS jobs now pass on this head.

Agreed on final reporting: the table retains one copied result vector per row. The description explicitly budgets that 8*rows*Q temporary storage. The no-allocation guarantee is for repeated latency_percentiles::calculate() calls, not constructing the query or rendering the final table. The PR stays draft while the full cross-platform matrix runs.

@fcostaoliveira
fcostaoliveira marked this pull request as ready for review October 13, 2026 08:27
fcostaoliveira and others added 2 commits October 13, 2026 10:05
The scratch-reuse test compared a stored double against expected / 1000.0
exactly. x87 builds can keep the right-hand side at extended precision, so
the i386 Debian packages' make check failed. Compare rounded microseconds.

hdr_histogram_test now takes memtier_benchmark_CPPFLAGS, which include the
coverage compile flags, so link CODE_COVERAGE_LIBS as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The table test ran pipelined, so Sets, Gets and Totals shared one latency
distribution and a dropped or doubled totals merge went unnoticed. Run
unpipelined with large SETs and missing-key GETs, query a dense unsorted
percentile grid, check Totals against the merged decoded Sets and Gets
histograms, cover arbitrary commands, and assert the header labels.

Require the default latency_p* StatsD metrics, and cover non-finite
percentiles in the batched/scalar compatibility unit test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira merged commit 667f187 into master Oct 13, 2026
126 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 14, 2026
With --enable-code-coverage, make check failed to link socket_options_test,
hdr_histogram_test and cluster_transaction_test with undefined __gcov_init,
__gcov_merge_add and __gcov_exit. These tests compile with
memtier_benchmark_CPPFLAGS, which carries the coverage flags, and two of them
link the instrumented memtier_benchmark objects, but none links libgcov.

The vendored AX_CODE_COVERAGE (serial 15) puts -lgcov in
CODE_COVERAGE_LDFLAGS and never defines CODE_COVERAGE_LIBS. The
$(CODE_COVERAGE_LIBS) in memtier_benchmark_LDADD, and the one #564 added to
hdr_histogram_test_LDADD, therefore expand to nothing. Only the main binary
got the runtime, through memtier_benchmark_LDFLAGS. That put -lgcov before the
objects, so it also depended on libtool reordering the link line.

Use $(CODE_COVERAGE_LDFLAGS) in both LDADD lists in place of the undefined
variable. The tests that reuse memtier_benchmark_LDADD inherit it,
memtier_benchmark_LDFLAGS is no longer needed, and -lgcov now follows the
objects. Run make check in the coverage CI job so this can't regress.

Fixes #595

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 14, 2026
With --enable-code-coverage, make check failed to link socket_options_test,
hdr_histogram_test and cluster_transaction_test with undefined __gcov_init,
__gcov_merge_add and __gcov_exit. These tests compile with
memtier_benchmark_CPPFLAGS, which carries the coverage flags, and two of them
link the instrumented memtier_benchmark objects, but none links libgcov.

The vendored AX_CODE_COVERAGE (serial 15) puts -lgcov in
CODE_COVERAGE_LDFLAGS and never defines CODE_COVERAGE_LIBS. The
$(CODE_COVERAGE_LIBS) in memtier_benchmark_LDADD, and the one #564 added to
hdr_histogram_test_LDADD, therefore expand to nothing. Only the main binary
got the runtime, through memtier_benchmark_LDFLAGS. That put -lgcov before the
objects, so it also depended on libtool reordering the link line.

Use $(CODE_COVERAGE_LDFLAGS) in both LDADD lists in place of the undefined
variable. The tests that reuse memtier_benchmark_LDADD inherit it,
memtier_benchmark_LDFLAGS is no longer needed, and -lgcov now follows the
objects. Run make check in the coverage CI job so this can't regress.

Fixes #595

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