Skip to content

fix(json): stop truncating/colliding deep-percentile keys in JSON output - #517

Merged
fcostaoliveira merged 6 commits into
redis:masterfrom
slice4e:fix/json-percentile-key-truncation
Aug 26, 2026
Merged

fcostaoliveira merged 6 commits into
redis:masterfrom
slice4e:fix/json-percentile-key-truncation

Conversation

@slice4e

@slice4e slice4e commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem

--json-out-file gives percentile keys that name the wrong number, and sometimes two
requested percentiles the same one. Both JSON blocks are affected, and both start
failing at the same unremarkable input — this is not a deep-tail-only bug.

Both sites build the key with a fixed-decimal format into an 8-byte buffer, but pass
sizeof(buf) - 1 as the size, so only 6 characters of key survive. The longest key that
fits is p99.99. That 6-char ceiling — not the format string — is what caps both blocks
at two effective decimal places.

Percentile Latencies (result_print_to_json() in run_stats.cpp):

char quantile_header[8];
snprintf(quantile_header, sizeof(quantile_header) - 1, "p%.3f", quantile);

Time-Serie (per-second stats, same function):

char quantile_header[8];
snprintf(quantile_header, sizeof(quantile_header) - 1, "p%.2f", quantile);

The %.3f looks like it carries an extra decimal, but p99.991 is 7 characters and
gets chopped back to p99.99, so in practice both blocks resolve to two decimals.

Where it starts

The format rounds, then the buffer truncates. Any quantile needing three or more
decimals comes out labelled as a different number:

--print-percentiles=99.9999
  "p%.2f" -> "p100.00" -> chopped to 6 chars -> "p100.0"

That value is the 99.9999th percentile, and the JSON calls it the maximum. Nothing is
missing and no key is duplicated, so nothing downstream can detect it.

When two requested quantiles are mangled onto the same string, the second write also
silently overwrites the first and one percentile disappears.
--print-percentiles=99.9,99.99,99.999,100 is enough to lose a value. The two blocks
differ only in how they are wrong, not in when: Time-Serie rounds 99.995 and up to
100.00 and truncates to p100.0; Percentile Latencies truncates the same values to
p99.99.

The plain-text table is unaffected; only the JSON is wrong.

Fix

A key is accepted only if reading it back gives exactly the quantile it labels:

strtod(key + 1, NULL) == quantile

Keys that pass are emitted unchanged, in their historical p%.2f/p%.3f shape —
including that shape's original truncation, since that truncated string is what
consumers read today. Keys that fail escalate to p%.10g, and then to p%.17g if
needed.

That single test also makes collisions impossible rather than detected. Reading
p99.99 back gives 99.99 and nothing else, so it cannot also be a faithful spelling of
99.991 — one of the two would have failed the test and escalated. Two different numbers
can't both pass with the same string. p%.17g reads back exactly for any double, so
some tier always passes.

Compatibility

A key changes if and only if it does not name the quantile it holds. Keys that are
correct today do not move — not just under the default config, but under any
configuration, regardless of what else is requested alongside them.

--print-percentiles before after
50,99,99.9 (default) p50.00,p99.00,p99.90 unchanged
50,99,100 p50.00,p99.00,p100.0 unchanged
50,99,99.9,99.999 …p99.99 (names 99.99) …p99.999
99.9999 p100.0 (names 100) p99.9999
99.99,99.991 p99.99 (one value lost) p99.99,p99.991

Consumers that look up p50.00, p99.00, p99.90 or p100.0 keep working. Consumers
reading a key that currently names the wrong quantile will see it renamed to the right
one — but that key was already returning a value that didn't match its label, so there
was nothing correct to depend on.

This does not reverse the back-compat decision in #379. That decision protected JSON
keys that were correct, and every one of them is still protected here.

Testing

make clean with no new warnings; make format-check reports nothing for
run_stats.cpp.

Added tests/test_json_percentile_key_collision.py (5 tests, all passing):

  • deep tail 50,99,99.9,99.99,99.99999,99.999999 yields six distinct keys, each parsing
    back to its requested quantile — master emits five for six requests
  • the same for every populated Time-Serie bucket
  • 99.9999 requested alone is keyed p99.9999, not p100.0 — the mislabel case, which
    collides with nothing
  • 99.9,99.900000001,99.99999991,99.99999992: four distinct keys, and 99.9 keeps
    p99.90 even though its neighbour needs %.17g
  • default config emits exactly p50.00, p99.00, p99.90 in both blocks

Verified beyond the suite:

  • full JSON key-path diff against pristine master is identical — 204/204 paths — for no
    flag, for an explicit 50,99,99.9, and for 50,99,100
  • 4012 quantiles pushed through both formats produce zero collisions, with no collision
    check in the code
  • no in-tree consumer needed updating; every test file this branch touched earlier has
    been reverted, so the net diff is run_stats.cpp plus the new test

Drive-by: unrelated flaky test fix

test_cpu_stats.py::test_cpu_warn_threshold_flag was failing CI on this branch. It is
not related to this change — it has been flaky since #471.

The test counted the substring 'of a core' in stderr and compared it against the
number of threads whose run-average cores_used exceeds 1.0. Two different warnings
contain that substring:

memtier_benchmark.cpp:3059   warning: high CPU on thread %u: %.1f%% of a core (threshold %.1f%%) ...
run_stats.cpp:2435           warning: thread %u averaged %.1f%% of a core over the run (threshold %.1f%%) ...

Only the second is the end-of-run warning the assertion is about. With
--cpu-warn-threshold=100 the live per-second warning is armed at 100% of a core too,
and a 1-second sample can legitimately exceed that because the wall window and the
CPU-clock sampling do not line up — the same file already tolerates this via
PER_THREAD_PCT_CEILING = 110.0. When the live warning fires, end_warnings becomes 1
while over_one_core is 0 and the test fails, depending on runner load.

Fixed by matching 'of a core over the run', which is unique to the end-of-run message.

Happy to split this into its own PR if you'd prefer to keep this one single-purpose.

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".
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).
…ld_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 redis#471; unrelated to the JSON percentile-key change on
this branch.
@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Thanks for this — went through it, the root-cause diagnosis (the -1 on sizeof() plus a fixed-decimal format that rounds before it truncates) is precise and the writeup is genuinely one of the clearer bug reports I've seen come through here. A few things I'd want settled before this merges.

The big one: --realtime-latencies (#379) hit this exact class of bug in a different output channel — table headers, the rtl stderr block, statsd names — and that PR's own commit message says explicitly: "JSON keys keep their p%.2f / p%.3f shape for back-compat with existing consumers and the test suite" while everything else got switched to %.10g. That was a deliberate, reasoned decision to leave JSON alone. This PR reverses it without engaging with why. I may be wrong, but given the precedent (this is the same tradeoff oranagra reasoned through in #212 — pick the less-breaking of two viable fixes), shouldn't the PR at least say what changed since #379 to make the JSON break acceptable now?

And separately — does the fix actually need to touch every key, or only the ones that collide? The default config is 50,99,99.9; under the old %.2f/%.3f code those three never round or truncate, so p50.00/p99.00/p99.90 are correct today for anyone running with defaults. This PR still rewrites them to p50/p99/p99.9. That's breaking every default-config consumer to fix a bug that only manifests once someone asks for 3+ decimal places. Did you consider keeping the fixed-decimal shape for quantiles that already round-trip cleanly and only falling back to %.10g for the ones that'd otherwise collide? Feels closer to the "minimize blast radius" call yossigo made on #60.

On testing: per #364's own bar, a JSON-format fix needs a regression test that fails on master and passes here — not just a manual --print-percentiles=... run pasted into the description. The test diffs in this PR only update existing assertions from p99.00 to p99 (2-decimal quantiles, which never collided in the first place); nothing here actually exercises 99.99 vs 99.991 or 99.99999 vs 99.999999 and asserts six distinct keys. Can you add one that pins that specific invariant?

Nitpicking: run_stats.cpp:1931 — the text-table header you're citing as the template still does sizeof(average_header) - 1. Not this PR's problem to fix, but it's the same "wastes a byte" pattern you removed at both JSON sites, one function up.

The flaky-test fix looks fine and orthogonal — you already offered to split it, that's enough for me, no need to actually do it unless someone else feels strongly.

Buffer widening and the switch to sizeof(buf) without the -1 at both JSON sites look correct on their own. The core mechanics of the fix look solid, I'd just want the #379-reversal question answered and a real collision-repro test before this merges.

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

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

Copy link
Copy Markdown
Collaborator

Pushed a follow-up commit (c346638) implementing the two asks above — didn't want to just leave the questions hanging, and figured a concrete patch would make the discussion easier to react to. To be clear: this is a suggested direction, not a decision — please revert, amend, or replace any part of it if you'd rather go a different way. It's your PR.

What it does:

  • Narrows the fix so only quantiles that actually collide change key shape. The default config (50,99,99.9) now produces byte-for-byte identical keys to master (p50.00, p99.00, p99.90) — verified by diffing full JSON output against pristine master, 233/233 and 226/226 key paths match. Reverted the 4 test files back to their original expectations accordingly (test_cpu_stats.py untouched).
  • Added tests/test_json_percentile_key_collision.py — reproduces your own bug report's exact repro (--print-percentiles=50,99,99.9,99.99,99.99999,99.999999), confirmed it actually fails on unpatched master (5 keys for 6 requested quantiles) and passes here, plus a back-compat test and a harder case where two quantiles are close enough that even %.10g collides (needed a third escalation tier, %.17g, to stay genuinely collision-free — verified against --print-percentiles=99.9,99.900000001,99.99999991,99.99999992).

What it doesn't answer: the #379 back-compat-precedent question is still open — that's a real judgment call, not something I could resolve unilaterally. Also left the run_stats.cpp:1931 nitpick alone (out of scope).

Happy to discuss/adjust — just didn't want the review to stall waiting on a from-scratch redesign when a starting point was quick to put together.

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

slice4e commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @fcostaoliveira . Taking c346638 as the baseline — thanks for pushing it. I've kept all of it and changed one
thing: when a key escalates.

The one change

c346638 escalates a key when it collides with another requested quantile. Collision
stands in for "this key is wrong", and that only holds one way — a colliding key is
wrong, but a wrong key doesn't have to 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, nothing is duplicated. The JSON just says the maximum and means the
99.9999th percentile, and no consumer can tell.

It misfires the other way too. Both sides of a collision escalate, so a correct key
moves because of its neighbour:

--print-percentiles=99.9                 -> p99.90                (correct)
--print-percentiles=99.9,99.900000001    -> p99.900000000000006   (same quantile!)

99.9 is a default percentile. So the back-compat guarantee holds for the default
config, but it isn't a general property — adding an unrelated percentile can still
move a key someone depends on.

The fix

Ask about the key, not the set: use the shortest format in your existing
legacy → %.10g → %.17g ladder whose output parses back to the quantile exactly.

strtod(key + 1, NULL) == quantile

99.9999 alone no longer round-trips through p100.0, so it escalates. 99.9 does
round-trip through p99.90, so it stays — its neighbour's problem stays its
neighbour's.

Why I deleted the collision scans

A key is only accepted if reading it back gives exactly the quantile it labels. That
one rule makes collisions impossible. Say 99.99 and 99.991 both ended up as p99.99 —
reading p99.99 back gives 99.99 and nothing else, so it can't also be a faithful
spelling of 99.991. The 99.991 key would have failed the test and escalated. Two
different numbers simply can't both pass with the same string.

The ladder can't run out of options either: %.17g always reads back exactly for a
double, so some tier always passes.

So collisions are now prevented instead of detected.

Verified

Three binaries, same Redis, Totals."Percentile Latencies":

--print-percentiles master c346638 this
50,99,99.9 (default) p50.00,p99.00,p99.90 same same
50,99,99.9,99.999 …p99.99 …p99.99 …p99.999
99.9999 p100.0 p100.0 p99.9999
100,99.9999 p100.0 p99.9999,p100 p99.9999,p100.0
99.9,99.900000001 p99.90 p99.900000000000006,… p99.90,…
99.99,99.991 p99.99 p99.99,p99.991 same

Your four tests pass unchanged. Added the 99.9999-alone case, which fails on master
and on c346638, plus an assertion that 99.9 keeps p99.90 when requested next to
99.900000001.

On the #379 question

With this change, it isn't a reversal of #379, and the PR no longer needs its "⚠️ Breaking change"
section. I'll rewrite the description accordingly.

Left alone: run_stats.cpp:1931, out of scope — agreed.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

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

Thanks for pushing this further — the shift from pairwise collision-escalation to a per-key round-trip test is a real improvement, not just a rename. Went through the logic by hand and then verified it against a build.

I built this commit (fa15654) and ran it against a live Redis for every row in your comparison table — default 50,99,99.9 unchanged, 50,99,99.9,99.999 → ...,p99.999, 99.9999 alone → p99.9999 (not p100.0), 99.9,99.900000001 → p99.90,p99.900000000999995, 99.99,99.991 → both distinct, 100,99.9999 → both distinct. All matched byte-for-byte. make is clean — the one -Wformat-truncation warning in run_stats.cpp that shows up in the build log is on key[%zu] Misses (line ~1995 on master, unrelated to this diff, confirmed pre-existing by building master separately), not anything touched here.

The structural argument for "collisions are impossible" is sound, and it's actually stronger than the PR describes: because format_percentile_key() only ever looks at its own quantile argument, a key's shape can't depend on what else was requested — that's not just empirically true, it's true by construction now, which is what actually fixes the "correct key moves because of its neighbor" bug in c346638. Buffer widening to 32 also checks out — DBL_MAX/-DBL_MAX through %.17g top out around 24-25 chars, smallest subnormal is fine too, so no overflow risk from the escalation.

One real gap in the round-trip proof, though I think it's out of scope rather than a blocker: "%.17g always reads back exactly for a double, so some tier always passes" isn't quite true for NaN — NaN == NaN is false under IEEE 754, so percentile_key_is_exact() can never actually return true for a NaN quantile. It still terminates safely (fixed 3-tier cascade, not a loop-until-pass, so no infinite loop), but it lands on %.17g's rendering of NaN because the ladder ran out, not because the check passed. Tested it directly: --print-percentiles=nan is accepted with no validation upstream (config_quantiles in config_types.cpp has never checked range/finiteness) and produces JSON key pnan, no crash. Two different NaN payloads (nan(1) vs nan(2), both valid via strtod) would collapse to the identical pnan key — an actual collision the "impossible" claim doesn't quite cover. That said, this already collided the same way on master before this PR (old %.3f of any NaN is also just "nan"), and percentiles are documented as 0-100 so nobody sane requests NaN — I'd lean toward not blocking on it, but is it worth a one-line caveat in the percentile_key_is_exact() comment rather than stating the guarantee unconditionally? I may be wrong that it's worth even that much.

On the #379 question: I think this resolves it, not just sidesteps it — the earlier concern was that the fix moved keys that didn't need to move; this version's per-key independence means a key only ever changes if it doesn't already name its quantile, which is the actual bar #379 set. Agreed the "Breaking change" section can go.

The test_cpu_stats.py fix is correct as a standalone thing — checked that "of a core over the run" only appears in the end-of-run warning (run_stats.cpp) and not the live per-second one (memtier_benchmark.cpp), so the tightened substring match does disambiguate them.

Nitpicking: legacy_percentile_key()'s inner snprintf(truncated, sizeof(truncated) - 1, ...) reproduces the original bug's exact off-by-one on purpose (to preserve the historical truncated shape) — the comment above it explains why, so this is fine, just flagging it so nobody "fixes" it later without reading the comment.

Nice work narrowing this down through three iterations — the final design is meaningfully simpler than where it started.

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

Approving based on the review above — the fix is now structurally sound (per-key round-trip check, verified byte-for-byte against a real build across the full comparison table), CI is fully green, and the one open item (NaN round-trip edge case) is explicitly non-blocking. Nice collaborative iteration getting here.

@fcostaoliveira
fcostaoliveira merged commit 95efe5e into redis:master Aug 26, 2026
117 checks passed
@slice4e

slice4e commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @fcostaoliveira for the collaborative effort.

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