Repository navigation
Replace invalid UTF-8 with U+FFFD in --json-out-file strings - #751
Conversation
|
🤖 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.
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]>
ba24452 to
eeab19c
Compare
|
Thanks, good catch on the duplicate keys. It was a real bug: Fixed in eeab19c. I took the approach you suggested:
On 🤖 Generated with Claude Code |
|
Thanks for the second pass. Point by point, for the edited review above: (a) Description out of date. Synced with eeab19c. It now covers (b) Text stats table now shows
(c) Prometheus. Confirmed real and out of scope for this JSON fix: (d) No code change in this round; the head is still eeab19c. 🤖 Generated with Claude Code |
/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]>
Problem
If a
--commandname 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-fileas they are. JSON text must be UTF-8, so Pythonjson.loadfails withUnicodeDecodeError, while memtier exits 0. (jqis 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'serrors="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 throughutf8_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 (bytesEF BF BD) in both keys and values; the file contains no\ufffdescapes.\u00XX: in JSON,\u00ffis 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.A\xff,A\xfeand a literalA+ U+FFFD all becomeA+ U+FFFD. JSON keys are deduplicated bymake_unique_labels(), which used to run on the raw bytes, so the file got duplicate keys,json.loadkept only one row, and the rows no longer added up to Totals.command_row_labels(), the JSON variant ofunique_command_labels()and the aggregated type names now callutf8_sanitize()before deduplication, so the keys becomeA�s #1,A�s #2, ...command_row_labels()), so it shows the sameA�s #1/#2row 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--commandname, without#N, as on master._Nbysanitize_file_name_component. The stderr "Writing ... command HDR latency histogram results" lines and the.hgrmheader 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 insave_hdr_arbitrary_commands()), a file with an_2suffix can hold the row named#4./metricsand 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/isspacecalls on--commandtext in config_types.cpp and memtier_benchmark.cpp, now cast tounsigned char. Passing a negativechar(a byte >= 0x80 wherecharis signed) is undefined behaviour; glibc happens to tolerate it.tests/include.py:debugPrintMemtierOnErrorreads mb.stdout/mb.stderr witherrors="replace", since they can echo the same bytes (it crashed withUnicodeDecodeErrorwhen the new test failed on master).Tests
test_json_replaces_invalid_utf8(--run-count=2):--commandnames 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,F5lead);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;--key-prefix(ending in a truncated sequence, so the NUL terminator ends it), the--uriuser and password (--authenticatein 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-labelwhen 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'sdecode("utf-8", "replace"), and checks that the valid names appear in the file as raw UTF-8.uriandauthenticateare 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\xfeandA+ U+FFFD. Parses with anobject_pairs_hookthat fails on duplicate keys, and checks there are 3 command rows whoseCountadds up toTotals. Both tests remove their temp dir when they pass.test_json_replaces_invalid_utf8FAIL 5/5 (mb.json is not valid UTF-8: ... byte 0xff)test_json_invalid_utf8_keys_stay_uniqueFAIL (keysA�sx3, 1 row instead of 3, Count 3 vs Totals 10)Mutation check: narrowing any of the boundary ranges (
EDhi 0x9F to 0x9E,F4hi 0x8F to 0x8E, 2-byte lead max 0xDF to 0xDE,E0lo 0xA0 to 0xA1) makestest_json_replaces_invalid_utf8fail.Fixes #745
Affected versions
1.2.9 (
key_prefixin the JSON configuration) / 1.2.16 (--commandrow names) through 2.5.2 and master.key_prefixinto the JSON unescaped (git tag --contains-> 1.2.9).🤖 Generated with Claude Code