Skip to content

test: account for %lld truncation and %.3f rounding in JSON latency integrity checks - #636

Merged
fcostaoliveira merged 5 commits into
masterfrom
fix/json-integrity-latency-tolerance
Oct 16, 2026
Merged

fcostaoliveira merged 5 commits into
masterfrom
fix/json-integrity-latency-tolerance

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

test_json_output_integrity.py fails intermittently on low-count per-second buckets. Seen in TSAN "Single Endpoint TCP TLS (misc)" on PR #616:
Average Latency 7.0000 ms inconsistent with Accumulated/Count (41.0/6 = 6.8333 ms); tolerance 0.1667 ms

The section-level check (_assert_latency_consistent) is worse, because it has no 1/count term at all. A low-count Sets/Gets/Totals section fails on correct output. With -n 3 --ratio 1:1, all three sections fail. This was raised in the automated review and reported in #645.

Root cause

Test-only. All fields come from the same whole-microsecond sum, so memtier's output is consistent.

  • Accumulated Latency is printed with %lld, which truncates it by less than 1 ms. That makes Accumulated/Count low by at most 0.999/count ms.
  • The averages are printed with %.3f, which rounds by up to 0.0005 ms.
  • Time-Serie check: the tolerance covered only the truncation (1/count). In the CI case (6 ops, true sum just under 42 ms, acc 41, avg 7.000), 7.0 - 41/6 is 0.16666666666666696 in floating point, which is greater than 1/6 (0.16666666666666666).
  • Section check: the tolerance was only max(0.01 ms, 2%). With sub-ms latencies and a few ops, Accumulated Latency truncates to 0 and the check fails.

Fix

Both checks now share _latency_bounds(derived, count), which is one-sided:

  • Above Accumulated/Count: up to max(0.01, 2%, 1/count + 0.0005). The worst correct case is 0.999/count + 0.0005, so there are at least 0.001/count ms of headroom. No float epsilon is needed.
  • Below Accumulated/Count: only the static max(0.01, 2%). Here a correct average can only be off by print error: up to 0.0005 ms for the Time-Serie and Totals averages (double division), and less than 0.001 ms for Sets/Gets and arbitrary-command sections. Those use integer-µs division in totals_cmd::summarize, which is exact in %.3f.

Making the bound one-sided keeps the integer-truncation regression detectable at low counts. The previous symmetric 1/count slack accepted it for count <= 3 (#645).

Deterministic tests:

Test evidence

  • Time-Serie test: fails with master's tolerance, reproducing the exact CI message, and passes with the fix.
  • Section check, real -n 3 --ratio 1:1 output (Sets 2 / 0.478 / 0, Gets 1 / 0.169 / 0, Totals 3 / 0.375 / 1): master's check fails all 3 sections, and the new check passes them.
  • Truncated-average test: both checks reject the case. The previous symmetric bound accepted it.
  • Integer-floor mutant: I took real runs with Latency around 1.32 and 2.45 ms and floored Latency/Average Latency to an integer. The new checks flag every section and bucket (6/6 per run).
  • No false positives on real output: I ran the new checks over 13 real JSON files from a local redis, 57 sections in total. These were -n 1..4 with skewed --ratio, plus --pipeline 8/40/48 runs with --run-count 2, which include the BEST/WORST/AGGREGATED sections. There were 0 failures.
  • Full file: rebased on master 66b58e7 and ran RLTest --env oss -t test_json_output_integrity.py twice. Run 2 passed 15/15. Run 1 passed 14/15: test_worker_finalization_failure_skips_process_cleanup failed once. That test does not run the latency checks, and it then passed 12/12 times when run alone.

Scope relative to #645

Fixes #635
Refs #645

Affected versions

Test-only; binaries unaffected. Both checks came from 7344622 (#364), and the Time-Serie 1/count term was added in 324553f. Both commits are first in 2.4.0, so 2.4.0 through 2.5.2 and master are affected.

🤖 Generated with Claude Code


Note

Low Risk
Test-only changes to assertion tolerances and new regression tests; memtier binaries and runtime behavior are unchanged.

Overview
Fixes flaky false failures in JSON latency integrity tests by modeling how memtier prints numbers: Accumulated Latency truncates to whole ms (%lld) and averages round to three decimals (%.3f).

Section and Time-Serie checks now share _latency_bounds(), which allows a wider slack above Accumulated/Count (1/count + 0.0005 on top of the existing 0.01 ms / 2% floor) but keeps the below side tight so regressions like averages truncated to integers (#645) still fail.

Adds a 3-request integration test plus synthetic cases (including a _FailureCounter harness) that lock in the CI TSAN bucket, low-count Sets sections, valid truncation/rounding, and rejection of bogus integer averages.

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

@fcostaoliveira
fcostaoliveira force-pushed the fix/json-integrity-latency-tolerance branch from f8b59be to 45172b9 Compare October 14, 2026 12:13
@github-actions

github-actions Bot commented Oct 14, 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 bound in _latency_bounds() and I think it holds. Above Accumulated/Count, the gap is at most 0.999/count from the %lld truncation plus 0.0005 from the %.3f rounding, so 1/count + 0.0005 covers it with some headroom. Below it, the only error is printing (under 0.001 ms for the integer-us sections, 0.0005 for the double ones), and the 0.01 ms floor covers that. Your -n 3 real run (Totals 3 / 0.375 / 1) also suggests Totals' Accumulated comes from the raw sum, not from adding up the truncated per-command values. If it were the sum, Totals could be off by up to 2/count. It may be worth a short note in the docstring that the bound assumes this. The count <= 0 guards already in both callers keep 1.0 / count safe. All three new tests check the exact boundary cases (fail on the old formula, pass on the new one), which is the bar PR#364 set for this file.

One question: the third commit makes the bound one-sided and adds test_tolerance_rejects_truncated_average for the #645 example. But the PR title still says this is only the Time-Serie check, and the body's "Scope relative to #645" section still says the false-pass half "is left for it". Doesn't this PR now cover all of #645? If so, I'd update the title and body, and maybe change "Refs #645" to "Fixes #645", so whoever triages #645 doesn't leave it open by mistake.

Nitpicking: _FailureCounter only stubs the three assert methods the helpers call today. That's fine, but if a helper later calls another env method, the test fails with an AttributeError, which hides the real cause.

Test-only change and the math checks out, so I'd mainly want the description to match what the PR now does before merge.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Point by point:

  1. Bound for the Time-Serie check. No change. avg - acc/count is at most 0.999/count + 0.0005, and the check allows 1/count + 0.0005 + 1e-9.

  2. _assert_latency_consistent has no 1/count term. You're right, and it does happen in practice. Real output from memtier_benchmark -t 1 -c 1 -n 3 --ratio 1:1 against a local redis:

    section Count Latency Accumulated old tolerance old result
    Sets 2 0.478 0 0.01 FAIL
    Gets 1 0.169 0 0.01 FAIL
    Totals 3 0.375 1 0.01 FAIL

    Fixed in 6a1c613. The bound now lives in _latency_tolerance(derived, count), and both checks use it. On the same output, all three sections now pass. Section Latency is computed with integer-us division (run_stats_types.cpp:260), so it can be up to 0.0015 ms below Accumulated/Count. That is the opposite direction from the %lld truncation, and the 0.01 ms floor already covers it, as the docstring notes. test_section_tolerance_covers_truncation adds your example (3 ops, 999 us, Accumulated 0, Latency 0.333). It fails with the old formula and passes with the new one.

    I also checked that the shared tolerance still catches the regression this file exists for. I took real runs with Latency around 1.32 ms and 2.45 ms and floored Latency/Average Latency to an integer. Every section and bucket is flagged (tolerances 0.027 and 0.049 ms).

    This is the false-failure half of test_json_output_integrity: latency tolerance lets a truncated average pass on low-count buckets and wrongly fails low-count sections #645. The other half of test_json_output_integrity: latency tolerance lets a truncated average pass on low-count buckets and wrongly fails low-count sections #645 is not changed here: the symmetric 1/count slack still accepts an integer-truncated average when count <= 3. Fixing that needs a one-sided interval check, so it stays in test_json_output_integrity: latency tolerance lets a truncated average pass on low-count buckets and wrongly fails low-count sections #645.

  3. Stale comment above ABS_TOLERANCE_MS. Updated. It now says the largest of the 0.01 ms floor, the 2% gap and the quantization bound from _latency_tolerance() is used.

The branch is rebased on master 0298524. test_json_output_integrity.py passes 14/14 locally, in 3 runs out of 3.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Update for the current head, dfc7f41, rebased on master 91eec24. This replaces my earlier reply, which described the previous revision.

  • The check is now one-sided. _latency_bounds allows max(0.01 ms, 2%) below Accumulated/Count. Above it, the limit is the larger of that same floor and 1/count + 0.0005 ms, so truncating Accumulated to %lld ms can only push the derived value down. There is no epsilon any more.
  • The docstring explains where each field comes from. Totals and Time-Serie use double division with %.3f rounding. Sets/Gets use integer-µs division in totals_cmd::summarize. The last commit adds a caveat for AGGREGATED AVERAGE RESULTS: those averages are unweighted means of the per-run averages (--run-count: AGGREGATED AVERAGE JSON "Latency"/"Average Latency" is an unweighted mean of per-run averages and disagrees with the text Avg. Latency #671), so the invariant only holds when every run has the same count, as with --requests.
  • _FailureCounter stubs only the three env methods the checks call. If a helper starts calling another one, the test fails with an AttributeError naming that method, which shows where the stub needs extending. It stays minimal for now.
  • Evidence from review:
    • An exhaustive sweep of counts 1-199 against true sums of 0-2999 µs gave no false failures.
    • Over 16 real JSON files (run-count 2/3, rate-limited, pipeline, large values), the new check passed all 570 assertions. The old check had 44 false failures on the same files.
    • Writers mutated to floor or truncate an average are still caught, between 13 and 18 failures per mutant.
    • The three new deterministic tests fail with the old helpers and pass with the new ones. The whole file passes 15/15.
  • The earlier macOS socket_options_test segfault was socket_options_test segfaults in build-macos (3): Homebrew libevent now links OpenSSL 4, memtier links openssl@3 #674, fixed on master by ci: link macOS libevent and memtier against the same OpenSSL #675, so this rebase picks up the fix.

@fcostaoliveira
fcostaoliveira force-pushed the fix/json-integrity-latency-tolerance branch from dfc7f41 to bca47c4 Compare October 16, 2026 07:25
fcostaoliveira and others added 5 commits October 16, 2026 08:42
The per-second consistency check allowed 1/count ms of slack for the
%lld truncation of "Accumulated Latency", but "Average Latency" is
also rounded by %.3f (up to 0.0005 ms). Both fields come from the same
whole-microsecond sum, so the gap is at most 0.999/count + 0.0005.
When the true sum is just under an integer ms and the avg rounds up
(6 ops, 41.999 ms -> avg 7.000, acc 41), the gap equals 1/count and
float error made the check fail (seen in TSAN CI on PR #616).

Allow 1/count + 0.0005 plus a tiny epsilon, and add a deterministic
regression case with two buckets: the CI values (exactly on 1/count,
needs the epsilon) and 7 ops / 7.999 ms -> avg 1.143, acc 7 (gap 0.143
> 1/7, needs the rounding term).

Fixes #635

Co-Authored-By: Claude Opus 5.5 <[email protected]>
_assert_latency_consistent() compared Latency with Accumulated/Count
using only max(0.01 ms, 2%). "Accumulated Latency" is printed with %lld
and is truncated by up to 0.999 ms, the same as in the Time-Serie
buckets, so a low-count section fails on correct output. For example,
-n 3 --ratio 1:1 gives Sets Count 2, Latency 0.478 and Accumulated
Latency 0.

Move the per-bucket bound (1/count + 0.0005 + epsilon) into
_latency_tolerance() and use it in both checks. Add a synthetic
section case (3 ops summing to 999 us) that fails with the old
formula and passes with the new one. Also update the comment above
ABS_TOLERANCE_MS, as suggested in the automated review.

This covers the false-failure half of #645. The false-pass half
(the symmetric 1/count slack accepts a truncated average for
count <= 3) is left for #645.

Refs #645

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A correct average can only be above Accumulated/Count by more than the
static floor. "Accumulated Latency" is truncated by %lld, so
Accumulated/Count is at most 0.999/count low, plus 0.0005 ms of %.3f
rounding on the average. Below Accumulated/Count, only print error is
possible. Time-Serie and Totals averages use double division and are
off by up to 0.0005 ms. Sets/Gets and arbitrary-command sections use
integer us division (totals_cmd::summarize), which is exact in %.3f and
less than 0.001 ms low. So the 1/count + 0.0005 term now applies only
above, and the 0.01 ms / 2% floor applies below. With that, an average
truncated to an integer is rejected even for low counts. A new test
covers the #645 example: 3 ops, Accumulated 4, average 1.000.

Drop FLOAT_EPSILON_MS. The bound leaves at least 0.001/count of headroom
over the worst case, so the epsilon never decided a result. Also fix the
docstring, which said the integer-division error came from the Totals
section and could reach 0.0015 ms.

Refs #645

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every real run in the file used >= 1000 requests, so a writer regression
that only shows at low counts (e.g. Accumulated rounded up instead of
truncated) passed the whole suite. Add a 3-request run that goes through
_validate_run_section, and a synthetic case on each side of the bound: a
correct integer-us average just below Accumulated/Count (rejects a zero
lower bound) and one just above 1/count + 0.0005 (rejects a looser upper
bound). The docstring now says the bounds do not apply to the default
per-type arbitrary-command sections, whose average is an HDR mean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira force-pushed the fix/json-integrity-latency-tolerance branch from bca47c4 to 71717c5 Compare October 16, 2026 07:42
@fcostaoliveira
fcostaoliveira merged commit 969c4de into master Oct 16, 2026
129 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 17, 2026
crash_handler() called localtime() and strftime() before it printed
anything. localtime() takes glibc's time zone lock, and the first call
in the process (always the one in the handler, since nothing else in
memtier calls it) runs tzset_internal(), which mallocs and opens
/etc/localtime. A crash that interrupts a thread holding the malloc or
time zone lock therefore deadlocked the handler before the
"BUG REPORT START" line, and its own alarm(5) watchdog then killed the
process with SIGALRM and no output. That is the flaky
test_crash_handler_worker_thread failure seen on PR #636.

The handler now:
- takes the local UTC offset once in prewarm_crash_handler() and formats
  the timestamp with integer arithmetic, in the same "%d %b %Y %H:%M:%S"
  format;
- writes the START header, the signal number and name, the signal code
  and the fault address with write(2) to stderr, before backtrace(),
  stdio or anything else that can lock;
- arms a SIGALRM handler that writes a "BUG REPORT INCOMPLETE" line
  before the watchdog ends the process, so a later hang is visible.

The rest of the report (backtrace, fprintf, client list) is unchanged
and stays after the essential lines; a comment lists which of those
calls are not async-signal-safe and why.

The new test_crash_handler_time_zone_lock_held preloads a shim whose
localtime/localtime_r/strftime/tzset block when called on a signal
stack, which reproduces the deadlock on every run: it fails on master
(exit -14, no report) and passes with this change.

Fixes #681

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 17, 2026
crash_handler() called localtime() and strftime() before it printed
anything. localtime() takes glibc's time zone lock, and the first call
in the process (always the one in the handler, since nothing else in
memtier calls it) runs tzset_internal(), which mallocs and opens
/etc/localtime. A crash that interrupts a thread holding the malloc or
time zone lock therefore deadlocked the handler before the
"BUG REPORT START" line, and its own alarm(5) watchdog then killed the
process with SIGALRM and no output. That is the flaky
test_crash_handler_worker_thread failure seen on PR #636.

The handler now:
- takes the local UTC offset once in prewarm_crash_handler() and formats
  the timestamp with integer arithmetic, in the same "%d %b %Y %H:%M:%S"
  format;
- writes the START header, the signal number and name, the signal code
  and the fault address with write(2) to stderr, before backtrace(),
  stdio or anything else that can lock;
- arms a SIGALRM handler that writes a "BUG REPORT INCOMPLETE" line
  before the watchdog ends the process, so a later hang is visible.

The rest of the report (backtrace, fprintf, client list) is unchanged
and stays after the essential lines; a comment lists which of those
calls are not async-signal-safe and why.

The new test_crash_handler_time_zone_lock_held preloads a shim whose
localtime/localtime_r/strftime/tzset block when called on a signal
stack, which reproduces the deadlock on every run: it fails on master
(exit -14, no report) and passes with this change.

Fixes #681

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.

test_json_output_integrity: per-second Average Latency tolerance misses %.3f rounding (flaky CI)

1 participant