Skip to content

Use 64-bit counters for run statistics - #552

Merged
fcostaoliveira merged 2 commits into
redis:masterfrom
darth-modder:feat/64bit-stats-counters
Oct 12, 2026
Merged

fcostaoliveira merged 2 commits into
redis:masterfrom
darth-modder:feat/64bit-stats-counters

Conversation

@darth-modder

@darth-modder darth-modder commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Why

unsigned long is 32-bit on LLP64 (Windows) and ILP32 (i386/armhf Linux). The run-statistics accumulators use it, so on those platforms:

  • byte totals wrap at 4 GiB (a 1 KB-value run gets there in under a minute),
  • microsecond durations wrap after ~71 minutes,
  • tv_sec * 1000000 overflows where tv_sec is 32-bit.

I hit this while adding native Windows support (follow-up PR: #553, which depends on this one). It also affects 32-bit Linux builds today.

What

  • Byte/op/hit/miss/error/duration accumulators and their getters become unsigned long long / long long.
  • Microsecond arithmetic in ts_diff() / ts_diff_now() and the JSON start/finish times is done in long long.
  • Matching printf conversions: %lu → %llu, %ld → %lld. result_print_to_json() already printed its long parameters with %lld, which this fixes too.

On LP64 (64-bit Linux/macOS) the values and the text, CSV, JSON and StatsD output stay byte-identical. Only the types and their matching conversions change. No JSON keys or CSV columns change.

Testing

  • Linux/macOS/Alpine/Debian, TLS, cluster, StatsD and ASAN/TSAN/UBSan CI pass on my fork with no new compiler warnings. The differential suite (run-differential) and the CLI fuzzer also pass.
  • Opt-in suites (run-fuzz, run-soak): monitor-input fuzz passes. Soak passes every scenario except S4 test_connection_churn.py. S4 fails the same way on unmodified master (8 of 8 thread(s) ended before the requested test time was reached, test_connection_churn.py:115) and passes on 2.4, so it predates this PR. Reported separately as Soak S4 (test_connection_churn) fails on master: all threads stop ~120 s in despite --reconnect-on-error #554.
  • 32-bit Linux (i386 Debian bookworm, bits=32): a 30 s run of 256 KB SETs pushes about 41 GB through the counters.
    • On master, JSON Sets/Count came out as -622618800193123421, the byte sum was negative, and KB/sec read 25,645 instead of about 1,335,909.
    • The count bug is unsigned long passed to %lld. The bytes and KB/sec errors come from 32-bit wrapping.
    • With this change, Count matches the server-side SET calls exactly, and KB/sec matches Count×size/duration to within 0.02%.
  • 64-bit Linux, side by side (x86-64 Ubuntu 24.04): master and this branch ran the same fixed workloads against the same Redis, 3 times each.
    • Workloads: preload, pipelined mixed, RESP3, --command, --data-import, --run-count, timed.
    • Exit codes, server-side command counts, JSON Count and Bytes TX, JSON key paths and types, per-second CSV and HDR headers were identical.
    • stdout and stderr were identical with the numbers masked.
  • On a Windows build (from Build and run natively on Windows (MSYS2 / MinGW-w64) #553), the same 20 s, 8×50 64 KB SET run reported KB/sec TX = 62,442 before this change (the true byte total modulo 2^32) and 528,047 after. The second figure matches the sum of the per-second byte counts to within 0.003%. Before the change the JSON Start time also came out negative.

Note

Medium Risk
Broad type and format-string sweep across stats, reporting, and metrics paths; low logic change but any missed %lu/unsigned long pairing could cause wrong output or ABI mismatches on some platforms.

Overview
Widens run-statistics accumulators and their public getters from unsigned long / long to unsigned long long / long long so byte totals, op counts, hits/misses, errors, and microsecond durations do not wrap on 32-bit Linux, Windows LLP64, or similar platforms.

The change threads through aggregation (client_group, run_stats, run_stats_types), live progress and CSV/JSON output (memtier_benchmark, run_stats), and metrics export (metrics_snapshot, StatsD gauge(long long)), with matching printf/snprintf conversions (%lu→%llu, %ld→%lld). Duration math in ts_diff() / ts_diff_now() and JSON runtime timestamps now uses signed 64-bit arithmetic to avoid tv_sec * 1e6 overflow.

On 64-bit LP64 builds behavior and formatted output are intended to stay the same aside from the wider types; schema keys and CSV columns are unchanged.

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

Byte, op, hit/miss, error and duration accumulators were `unsigned long`,
which is 32-bit on LLP64 (Windows) and ILP32 (i386/armhf Linux): byte
totals wrap at 4 GiB, microsecond durations wrap after ~71 minutes, and
`tv_sec * 1000000` overflowed where `tv_sec` is 32-bit. Widen them to
`unsigned long long` / `long long` and do microsecond arithmetic in
`long long`. On LP64 the printed text, CSV, JSON and StatsD output is
unchanged; only the printf conversions (%lu -> %llu, %ld -> %lld) change
to match the types.
@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

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

Thanks for this, and for the very thorough write-up. I went through the whole diff. The i386 numbers (negative Count, KB/sec off by ~50x) and the 64-bit side-by-side make a convincing case. Since the LP64 text/CSV/JSON/StatsD output stays byte-identical and no keys or columns change, I don't see a compat concern here. A few comments:

  1. Regression protection. Right now nothing stops the next %lu/%u from slipping back in: CI has no 32-bit job, and benchmark_debug_log(), benchmark_error_log(), json_handler::write_obj() and the Prometheus append_fmt() have no printf format attribute, so -Wformat can't see their calls. You already applied the attribute temporarily for the audit. Did you consider just keeping it (__attribute__((format(printf, N, M))) on those declarations)? On LP64, -Wformat still flags %lu against unsigned long long because they're distinct types, so the existing CI would catch future mismatches with no new job. If that turns up too much noise elsewhere, an i386 container job running the existing tests would be the other option. Either way it would be better than relying on the manual run described in the PR. (PR#364 is an example of a fix in this repo that came with a test pinning the invariant.)

  2. Just checking about the lock-free counters on 32-bit. m_ops, m_bytes_*, m_hits etc. are bumped by workers and read from the main thread under the "benign race" comment. That was fine when they were word-sized, but on i386 a 64-bit load/store isn't atomic. A torn read could make total_ops - prev_ops (or cur_bytes) wrap to a huge value for one tick in the progress line, StatsD or Prometheus. I think that's a lot better than wrapping at 4 GiB every time, so it's probably acceptable, but it might be worth a line in the comment so nobody is surprised later. I may be wrong about how much this matters in practice. It's worth a second look from whoever owns the live-progress/metrics path.

  3. Nitpicking: the comment above statsd_publish_tick() (around memtier_benchmark.cpp:3317) still says the snapshot "carries cur/avg_ops_sec et al. as long". Only the second half of that sentence was updated.

The type changes themselves look solid and consistent to me. I'd mainly like to hear your thoughts on keeping the format attributes, since that would protect this fix from regressing.

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

run_stats::debug_dump() still printed the now 64-bit m_ops and byte counters
with %u; on 32-bit targets that consumes the wrong number of argument slots
and shifts every later argument. Print them with %llu, and print the
timeval fields (time_t/suseconds_t are not unsigned int) as long long.

benchmark_debug_log(), benchmark_error_log(), json_handler::write_obj() and
the Prometheus append_fmt() are variadic without a printf format attribute,
so -Wformat could not see these. Audited every call with the attribute
applied temporarily on x86-64 and i386; two more pre-existing 64-bit
mismatches turned up and are fixed here: the reqs_processed debug message
in shard_connection.cpp and the key_minimum/key_maximum JSON fields (both
unsigned long long printed with %u). Output is unchanged for values below
2^32.

print_json() declared start_time_ms/end_time_ms unsigned long long but
printed them with %lld; declare them long long to match the signed
arithmetic. The printed values are unchanged.
@darth-modder

darth-modder commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Fixed in bf87593:

  • debug_dump() now prints the widened counters with %llu. The start_time/end_time debug line also used %u for tv_sec/tv_usec, so it now casts to long long and uses %lld.
    • debug_dump() has no callers, so I checked it with a temporary call in an i386 build.
    • Before: m_ops_set/get/wait=6/0/54, m_bytes_set/get=0/0, m_get_hit/miss=0/471 (shifted).
    • After: 6/54/0, 471/2155, 0/54.
  • I audited the unchecked loggers by temporarily adding __attribute__((format(printf, …))) to benchmark_log_file_line, benchmark_log, json_handler::write_obj and append_fmt, then building with -Wformat.
    • master shows several existing mismatches.
    • This branch shows none, after also fixing the reconnecting, m_reqs_processed debug line and the key_minimum/key_maximum formats (%11u was being used for unsigned long long).
    • The attributes themselves aren't committed, because they surface unrelated warnings elsewhere. They could be a follow-up.
  • start_time_ms/end_time_ms are now long long, matching %lld and the signed ts_diff arithmetic.
  • I left an i386 CI job out of this PR. I can add a 32-bit build-and-smoke job as a follow-up.

The x86-64 warning set is identical to master's, and clang-format 18 is clean.

@darth-modder
darth-modder force-pushed the feat/64bit-stats-counters branch from c0b5ec2 to bf87593 Compare October 9, 2026 22:56

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks — fixes real wrap/UB on our i386/armhf packages too. CI green.

@fcostaoliveira
fcostaoliveira merged commit 2ed605f into redis:master Oct 12, 2026
119 checks passed
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