Skip to content

Replace invalid UTF-8 with U+FFFD in --json-out-file strings - #751

Merged
fcostaoliveira merged 1 commit into
masterfrom
fix/745-json-invalid-utf8
Oct 16, 2026
Merged

fcostaoliveira merged 1 commit into
masterfrom
fix/745-json-invalid-utf8

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

If a --command name or a configuration string (--key-prefix, --uri, --authenticate, --client-stats, --failed-keys-file, --prometheus-run-label, ...) contains bytes that are not valid UTF-8, those bytes are copied into --json-out-file as they are. JSON text must be UTF-8, so Python json.load fails with UnicodeDecodeError, while memtier exits 0. (jq is lenient and accepts the file, which hides the problem.)

Root cause

write_json_string_body() (JSON_handler.cpp) writes every user string into the file: object keys (write_json_key, since #741) and \"%s\" values. It escaped ", \ and bytes < 0x20, but copied every byte >= 0x80 without checking that it is part of a valid UTF-8 sequence.

Fix

  • utf8_sanitize() (new, JSON_handler.h/.cpp) returns a copy of a string with each invalid UTF-8 sequence replaced by U+FFFD, using the Unicode "maximal subpart" rule (the same as Python's errors="replace", WHATWG and ICU). Truncated sequences, lone continuation bytes, overlongs (C0 AF, E0 80 AF, F0 80 80 AF), surrogates (ED A0 80) and code points above U+10FFFF (F4 90 80 80, F5..FF) are invalid. Valid multi-byte UTF-8 is kept byte for byte, not \u-escaped.
  • write_json_string_body() runs every string through utf8_sanitize() before the existing escaping, so there is still one escaper. utf8_sanitize() is declared in JSON_handler.h because its job is keeping the JSON valid; run_stats.cpp calls it only to compute JSON keys before deduplication. If Prometheus /metrics emits invalid UTF-8 when a --prometheus-run-label value contains a non-UTF-8 byte (charset=utf-8 is advertised); the run exits 0 #753 wants it for Prometheus label values, it can move to a small shared header then. The replacement is written as UTF-8 (bytes EF BF BD) in both keys and values; the file contains no \ufffd escapes.
  • Why U+FFFD and not \u00XX: in JSON, \u00ff is the character U+00FF (ÿ), not the byte 0xFF. A parser would return a different, valid string that cannot be told apart from a real ÿ. U+FFFD is the standard marker for undecodable input.
  • Duplicate keys (review question): replacement can make two names equal: A\xff, A\xfe and a literal A + U+FFFD all become A + U+FFFD. JSON keys are deduplicated by make_unique_labels(), which used to run on the raw bytes, so the file got duplicate keys, json.load kept only one row, and the rows no longer added up to Totals. command_row_labels(), the JSON variant of unique_command_labels() and the aggregated type names now call utf8_sanitize() before deduplication, so the keys become A�s #1, A�s #2, ...
    • The text stats table shares these labels (command_row_labels()), so it shows the same A�s #1 / #2 row names as the JSON. This is on purpose: the shared function exists so the text table and the JSON name a row the same way, and the raw bytes were already unreadable in a terminal. Only the stats table changes. The text "Request Latency Distribution" section still prints the raw --command name, without #N, as on master.
    • HDR output file names are unchanged: raw bytes, deduplicated separately with _N by sanitize_file_name_component. The stderr "Writing ... command HDR latency histogram results" lines and the .hgrm header line use the JSON label, which is now sanitized and deduplicated after sanitizing. Because the two are numbered independently (already the case on master, see the comment in save_hdr_arbitrary_commands()), a file with an _2 suffix can hold the row named #4.
    • Prometheus /metrics and StatsD are not touched. Run-label values with invalid UTF-8 still reach /metrics; that is filed as Prometheus /metrics emits invalid UTF-8 when a --prometheus-run-label value contains a non-UTF-8 byte (charset=utf-8 is advertised); the run exits 0 #753.
  • command_row_name(), and the ::toupper / isspace calls on --command text in config_types.cpp and memtier_benchmark.cpp, now cast to unsigned char. Passing a negative char (a byte >= 0x80 where char is signed) is undefined behaviour; glibc happens to tolerate it.
  • tests/include.py: debugPrintMemtierOnError reads mb.stdout/mb.stderr with errors="replace", since they can echo the same bytes (it crashed with UnicodeDecodeError when the new test failed on master).

Tests

test_json_replaces_invalid_utf8 (--run-count=2):

  • --command names that each contain one kind of invalid sequence (invalid start byte, truncated 2- and 3-byte, lone continuation, overlong 2/3/4-byte, surrogate, above U+10FFFF, F5 lead);
  • valid UTF-8 names: Kключ, Lä😀, and the boundary code points U+07FF (DF BF), U+0800 (E0 A0 80), U+D7FF (ED 9F BF), U+FFFF (EF BF BF), U+10000 (F0 90 80 80) and U+10FFFF (F4 8F BF BF), so a decoder that rejects too much fails;
  • invalid bytes in --key-prefix (ending in a truncated sequence, so the NUL terminator ends it), the --uri user and password (--authenticate in cluster/unix-socket envs; an ACL user is created and deleted on each master inside the try/finally, and the test is skipped on Redis < 6.0), --client-stats, --failed-keys-file, and --prometheus-run-label when the build has the exporter (--prometheus-port=0).

It decodes mb.json as strict UTF-8, checks the stats row (Xs) and percentile array (X) keys in BEST/WORST/AGGREGATED and the configuration values against Python's decode("utf-8", "replace"), and checks that the valid names appear in the file as raw UTF-8. uri and authenticate are covered by the strict decode but their values are not compared, so the test does not conflict with redacting them (#731).

test_json_invalid_utf8_keys_stay_unique: A\xff, A\xfe and A + U+FFFD. Parses with an object_pairs_hook that fails on duplicate keys, and checks there are 3 command rows whose Count adds up to Totals. Both tests remove their temp dir when they pass.

binary env result
origin/master a7881e0 oss test_json_replaces_invalid_utf8 FAIL 5/5 (mb.json is not valid UTF-8: ... byte 0xff)
previous head ba24452 oss test_json_invalid_utf8_keys_stay_unique FAIL (keys A�s x3, 1 row instead of 3, Count 3 vs Totals 10)
this branch oss both tests PASS 10/10
this branch oss-cluster (3 shards) both PASS
this branch oss, whole test_json_output_integrity.py 20/20 pass

Mutation check: narrowing any of the boundary ranges (ED hi 0x9F to 0x9E, F4 hi 0x8F to 0x8E, 2-byte lead max 0xDF to 0xDE, E0 lo 0xA0 to 0xA1) makes test_json_replaces_invalid_utf8 fail.

Fixes #745

Affected versions

1.2.9 (key_prefix in the JSON configuration) / 1.2.16 (--command row names) through 2.5.2 and master.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Oct 16, 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 and the tests, and I only have a few comments.

The core fix looks right to me. utf8_sequence_length() stops at the NUL terminator because 0x00 is always below lo, so a truncated sequence at the end of the string can't read past it. The narrowed second-byte ranges (E0/ED/F0/F4) also give the same maximal-subpart result as Python's errors="replace". The regression test checks the bar #364 set: it decodes mb.json as strict UTF-8 and is shown failing on a7881e0. I'm also glad it checks that valid UTF-8 at the boundary code points comes through byte for byte, not just that bad input gets replaced.

  • The PR description seems to describe an earlier version of the change. It still says "this builds on the existing escaper; there is no second one" and only mentions the command_row_name() cast. The commit itself adds a public utf8_sanitize(), sanitizes before make_unique_labels(), adds the toupper/isspace casts in config_types.cpp/memtier_benchmark.cpp, and adds test_json_invalid_utf8_keys_stay_unique. Could you sync the description before merge, so whoever reads the squashed history sees the same story as the commit message?
  • Output-format question: since command_row_labels() is shared, the text stats table now shows A�s / A�s #1 where it used to print the raw bytes. I think that's fine, since those labels were already mangled in a terminal and the JSON was invalid anyway. Still, it changes the text output and not just the JSON. Did you consider keeping the raw name in the text table and only sanitizing on the JSON side, or is keeping the two in sync worth the change? (This is the support ASK in cluster mode #60 kind of question: what else moves besides the thing being fixed?)
  • I think this is out of scope, so just checking: the Prometheus text exposition format also expects UTF-8. Do --command names or --prometheus-run-label values with these bytes reach the exporter's label values unsanitized? If so, a follow-up issue might be worth opening rather than growing this PR.
  • Nitpicking: utf8_sanitize() now lives in JSON_handler.h but run_stats.cpp also calls it for text labels. That's fine at its current size, just mentioning it in case it ends up wanted elsewhere.

None of this blocks the fix itself. I'd mainly like the description updated and the text-table question answered before this merges.

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

write_json_string_body() escapes '"', '\' and control characters
(3d710d5, #741) but copied every byte >= 0x80 as it was. A --command name
or a configuration value such as --key-prefix, --uri, --client-stats or
--failed-keys-file that contains a non-UTF-8 byte therefore made the file
invalid JSON (JSON text must be UTF-8): Python json.load fails with
UnicodeDecodeError, while memtier exits 0.

New utf8_sanitize() (JSON_handler) replaces each invalid UTF-8 sequence
with U+FFFD, using the Unicode "maximal subpart" rule (the same as
Python's errors="replace"). Truncated sequences, overlongs, surrogates
(ED A0 80) and code points above U+10FFFF are invalid. Valid multi-byte
UTF-8 is kept byte for byte. write_json_string_body() runs every string
through it, so U+FFFD is written as UTF-8 (EF BF BD) in keys and values.

U+FFFD rather than \u00XX: in JSON, \u00ff is the character U+00FF,
not the byte 0xFF, so it would decode to a different, valid string that
cannot be told apart from a real U+00FF. U+FFFD is the standard marker
for undecodable input.

Replacement can make two names equal ("A\xff", "A\xfe" and a literal
"A<U+FFFD>" all become "A<U+FFFD>"). JSON object keys are deduplicated
by make_unique_labels(), so command_row_labels(), unique_command_labels()
(JSON variant) and the aggregated type names now sanitize before
deduplication; otherwise the file had duplicate keys and json.load kept
only one row. The text table shares these labels, so it shows the same
"A<U+FFFD>s #1" / "#2" names. HDR file names keep the raw bytes.

command_row_name(), and the ::toupper / isspace calls on --command text
in config_types.cpp and memtier_benchmark.cpp, now cast to unsigned char:
passing a negative char (a byte >= 0x80 where char is signed) is
undefined behaviour.

Tests:
- test_json_replaces_invalid_utf8: --command names with each kind of
  invalid sequence, valid UTF-8 names including the boundary code points
  U+07FF, U+0800, U+D7FF, U+FFFF, U+10000 and U+10FFFF, and invalid bytes
  in --key-prefix, --uri/--authenticate, --client-stats,
  --failed-keys-file and --prometheus-run-label. Decodes mb.json as
  strict UTF-8 and checks keys and values against Python's replacement.
- test_json_invalid_utf8_keys_stay_unique: three names that collide after
  replacement must give three distinct keys whose Count adds up to
  Totals.
debugPrintMemtierOnError reads output files with errors="replace", since
they can echo the same bytes.

Fixes #745

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira force-pushed the fix/745-json-invalid-utf8 branch from ba24452 to eeab19c Compare October 16, 2026 22:47
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks, good catch on the duplicate keys. It was a real bug: --command="A\xff x" --command="A\xfe x" gave three A�s keys (with a literal A� as well), json.load kept one row, and the rows summed to Count 3 against Totals 10.

Fixed in eeab19c. I took the approach you suggested:

  • New utf8_sanitize() in JSON_handler does the U+FFFD replacement, and write_json_string_body() uses it, so there is still one implementation.
  • command_row_labels(), the JSON variant of unique_command_labels() and the aggregated type names call it before make_unique_labels(), so colliding names become A�s #1, A�s #2, ...
  • The text table shares these labels and shows the same names. HDR file names keep the raw bytes.
  • New test test_json_invalid_utf8_keys_stay_unique parses with an object_pairs_hook that rejects duplicate keys and checks the per-command Count adds up to Totals. It fails on the previous head ba24452 and passes now.

On test_dir: the test removes it with shutil.rmtree when it passes (added in ba24452, kept in eeab19c). On failure it is kept for debugPrintMemtierOnError, like the other tests in this file. The new test does the same.

🤖 Generated with Claude Code

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the second pass. Point by point, for the edited review above:

(a) Description out of date. Synced with eeab19c. It now covers utf8_sanitize(), sanitizing before make_unique_labels(), the toupper/isspace casts in config_types.cpp and memtier_benchmark.cpp, and test_json_invalid_utf8_keys_stay_unique, so it tells the same story as the commit message.

(b) Text stats table now shows A�s / A�s #1. Yes, on purpose. command_row_labels() is shared because the text table and the JSON must name a row the same way; splitting it would bring back the mismatch it was added to prevent. The raw bytes were already unreadable in a terminal, and two names that collide after replacement would otherwise be two different-looking text rows that map to #1/#2 in the JSON. What else moves, so it's all written down (also in the PR description now):

  • Only the stats table changes. The "Request Latency Distribution" text section still prints the raw --command name, without #N, as on master.
  • HDR file names keep the raw bytes and their own _N numbering. The stderr "Writing ..." lines and the .hgrm header use the JSON label, now sanitized. The two were already numbered independently on master, so _2 can hold the row named #4.
  • Output for valid UTF-8 names is identical to master.

(c) Prometheus. Confirmed real and out of scope for this JSON fix: --prometheus-run-label="env=x\xffy" puts the raw 0xFF in 49 of 91 /metrics lines while advertising charset=utf-8, on master a7881e0, 2.5.2 and this PR's head. escape_label_value() only escapes \, " and newline. --command names don't reach /metrics, and StatsD already maps non-[A-Za-z0-9_.-] bytes to _. Filed as #753, with the affected versions (2.5.0+, since #468) and the isalnum signed-char UB in statsd.cpp.

(d) utf8_sanitize() in JSON_handler.h. Kept there: its purpose is keeping the JSON valid, and run_stats.cpp only calls it to compute JSON keys before deduplication. If #753 reuses it for Prometheus label values, that's the moment to move it to a small shared header, rather than adding a new file and Makefile.am entry for one caller now.

No code change in this round; the head is still eeab19c.

🤖 Generated with Claude Code

@fcostaoliveira
fcostaoliveira merged commit 38dfbaa into master Oct 16, 2026
129 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 17, 2026
/metrics advertises charset=utf-8 and the Prometheus text format
requires UTF-8, but escape_label_value() copied every byte other than
'\', '"' and newline as is. A --prometheus-run-label value with a
non-UTF-8 byte was therefore copied into every sample line, making the
whole scrape unparseable (promtool: "invalid label value"), while
memtier exited 0 without a warning.

Move utf8_sanitize() from JSON_handler into a small shared utf8.{h,cpp}
(unchanged; JSON_handler.h includes it, so JSON output is identical) and
run label values through it in escape_label_value(), so invalid
sequences become U+FFFD exactly as #751 does for --json-out-file. This
is preferred over rejecting the value at parse time, which would turn
command lines that run today into errors. Option parsing now prints a
warning when a value is not valid UTF-8. Valid UTF-8 values are emitted
byte-identical. The run labels are the only user strings that reach
/metrics; the build_info version and git_sha come from the build.

Also cast to unsigned char before isalnum() in the StatsD run-label and
prefix sanitizers: a byte >= 0x80 is negative as a plain char on x86,
and passing it to isalnum() is undefined behaviour.

Fixes #753

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.

--json-out-file is invalid UTF-8 (unparseable JSON) when a --command name or --key-prefix contains a non-UTF-8 byte; the run exits 0

1 participant