Skip to content

Escape JSON object keys in --json-out-file - #741

Merged
fcostaoliveira merged 1 commit into
masterfrom
fix/738-json-key-escaping
Oct 16, 2026
Merged

fcostaoliveira merged 1 commit into
masterfrom
fix/738-json-key-escaping

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

--json-out-file produces invalid JSON when a --command name contains ", \ or a control character. memtier still exits 0.

memtier_benchmark ... --json-out-file j.json --command "'EC\"HO' x"
json.decoder.JSONDecodeError: Expecting ':' delimiter: line 110 column 9
memtier_benchmark ... --json-out-file j.json --command 'ECHO\ x'
json.decoder.JSONDecodeError: Invalid \escape: line 110 column 9
memtier_benchmark ... --json-out-file j.json --command "$(printf "'EC\001HO' x")"
json.decoder.JSONDecodeError: Invalid control character at: line 110 column 8

Root cause

json_handler::write_obj() and json_handler::open_nesting() write the object name with fprintf(.., "\"%s\":", objectname). 3d710d5 escaped string values only. Keys can come from user input: each --command name becomes a per-command key in ALL STATS (and in the other stats sections).

Fix

Add a small write_json_key() helper that writes the name through write_json_string_body() (the helper 3d710d5 added for values). Use it in write_obj() and open_nesting(), the only two places that write keys. This escapes ", \ and control characters (as \u00XX). Non-ASCII bytes pass through unchanged, the same as for values.

Ordinary keys are written byte for byte as before. On a default run and on a --command SET/GET --print-percentiles 50,99.9 run, the set of key tokens in the file is identical between master and this branch (140 and 142 distinct keys).

Tests

New test test_json_escapes_object_keys in tests/test_json_output_integrity.py. It runs three --commands whose names contain a quote, a backslash and \x01, checks that json.load succeeds, and checks that each per-command key round-trips.

  • master 0fc29f4: fails 5/5 (JSONDecodeError: Expecting ':' delimiter)
  • this branch: passes 10/10
  • whole test_json_output_integrity.py on this branch: 18/18 pass

Overlap

#729 also changes JSON_handler.cpp, but only the destructor and the new close(). The hunks do not overlap with this change. #735 (config print) does not touch the JSON handler.

Fixes #738

Affected versions

1.2.16 through 2.5.2 (latest) and master. Per-command keys have come from user input since 7cdbaff "add support for multiple arbitrary commands (#72)" (git tag --contains 7cdbaff: first tag 1.2.16). The unescaped "\"%s\":" key format is older than that. Confirmed by running master 0fc29f4. String values were fixed separately on master by 3d710d5, which is not released yet.

🤖 Generated with Claude Code


Note

Low Risk
Localized change to JSON serialization of keys only; behavior for normal keys is unchanged and coverage is added via integration test.

Overview
Fixes invalid --json-out-file output when object keys contain JSON-special characters. Per-command stats keys (derived from --command names) were written with unescaped fprintf("\"%s\":", …) while string values were already escaped; quotes, backslashes, or control bytes broke json.load().

Adds write_json_key() to route key names through the same write_json_string_body() escaping used for values, and switches write_obj() and open_nesting() to use it. Ordinary keys are unchanged byte-for-byte.

Adds regression test test_json_escapes_object_keys with command names containing ", \, and \x01, asserting the JSON parses and each per-command section key round-trips in ALL STATS.

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

json_handler::write_obj() and open_nesting() printed the object name with
"\"%s\":", so a key was written verbatim. Keys come from user input: a
--command name becomes a per-command key in "ALL STATS" (and the other
stats sections). A quote, a backslash or a control character in that name
made the file invalid JSON, while memtier still exited 0. 3d710d5 fixed
the same problem for string values only.

Write keys through write_json_string_body(), the helper 3d710d5 added for
values. Ordinary keys are written byte for byte as before.

Fixes #738

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira merged commit a25585e into master Oct 16, 2026
124 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
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]>
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 JSON when a --command name contains a quote or backslash (JSON object keys are not escaped)

1 participant