Skip to content

JSON: preserve UTF-8 bytes through Parse (fixes toolview ¶ mojibake at the root) - #161

Merged
FMXExpress merged 2 commits into
mainfrom
claude/json-utf8-roundtrip
Jun 6, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/json-utf8-roundtrip

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

PasClaw.JSON.Parse was silently corrupting every non-ASCII byte that flowed through it. The mojibake we kept patching at downstream symptom sites — toolview's test, the markdown-render glyphs, the Anthropic stream-body trip — was the same root cause: fpjson's default GetJSON path round-trips parsed string tokens through DefaultSystemCodePage, and on a container locale with DefaultSystemCodePage=0 that round-trip clips every UTF-8 lead byte.

This PR fixes the parser; the downstream patches (TagUTF8 at HTTP boundary, hex-byte glyph constants in markdown-render, byte-aware hashline payload check) stay valid but no longer have to compensate for byte loss upstream.

Root cause

fpjson's jsonreader.pp line 241-242:

tkString : if (joUTF8 in Options) and (DefaultSystemCodePage<>CP_UTF8) then
             StringValue(TJSONStringType(UTF8Decode(CurrentTokenString)))

With joUTF8 set (the default) and DefaultSystemCodePage <> CP_UTF8 (any non-UTF-8 locale, including 0 / CP_ACP), the UTF8Decode → TJSONStringType cast silently re-encodes the parsed token through the system codepage. The resulting AnsiString carries CP_ACP and every codepoint the system CP can't represent gets clipped to a single trailing byte (or replaced with ? on a strict-ASCII fallback).

Codepoint UTF-8 wire stored after lossy path GetStr returns
U+00B6 C2 B6 bare B6 1 byte
é U+00E9 C3 A9 bare A9 1 byte
中 U+4E2D E4 B8 AD bare AD 1 byte
• U+2022 E2 80 A2 bare A2 1 byte

Fix

Bypass GetJSON entirely. Construct a TStringStream over the input bytes and drive TJSONParser directly with empty options — no joUTF8. The scanner's string-token path is then a plain Move of the raw bytes into the token AnsiString (jsonscanner.pp:405); no UTF-8 round-trip happens; the bytes we passed in are the bytes fpjson stores and AsString returns.

Applied to both TJsonObject.Parse and TJsonArray.Parse.

PasClaw treats every string at every boundary as UTF-8 already (Indy HTTP + TagUTF8 from PR #149, file IO via TEncoding.UTF8 + TagUTF8, stdout via PasClaw.CliUI.Write on a UTF-8 terminal). The fpjson UTF-8 "decode" pass was a redundant round-trip that only served to corrupt them.

Symmetric write behaviour (PutStr / AddStr) needs no change — the lossy branch only ran on tkString during parse.

Test plan

  • New src/tests/json_utf8_roundtrip_tests.pas (6 cases): / é / 中 / • round-trips through Object.GetStr, ASCII unchanged, JSON escapes still parsed, TJsonArray.Parse + ItemStr symmetric coverage. All pass.
  • Wired into make test as test-json-utf8-roundtrip.
  • toolview_tests.TestEditHashlineCall (the test that originally surfaced the bug) now passes.
  • Full make clean on Linux/FPC. Smoke + every other unit test green (test-hashline, test-anthropic-server-tools, test-openai-server-tools, test-println-helper, test-utf8-codepage-tag, test-gemini-schema-strip, test-markdown-render).
  • Delphi build — no behavioural change expected. The Delphi backend ({$ELSE} branch) uses System.JSON which doesn't have fpjson's lossy branch; string = UnicodeString there carries codepoints losslessly anyway.
  • Live Anthropic / OpenAI / Gemini turns with non-ASCII assistant content (smart quotes, em-dashes, accents, CJK) to confirm the wire round-trip is clean end-to-end.

Not addressed here (separate concern)

toolview_tests.TestArgTruncation is still red — that's a distinct mojibake about TV_CALL_GLYPH = '⏺' and the '…' literal in Ellipsize getting clipped to ? when concatenated across mismatched codepage tags. Same class of bug as PR #157 (markdown glyph constants), same fix shape (per-compiler hex byte constants). Worth a follow-up but out of scope for the JSON layer fix.


Generated by Claude Code

PasClaw.JSON.Parse routes through fpjson's GetJSON wrapper, which in
turn pipes the input into TJSONScanner with the `joUTF8` option set
(it's the default). Inside jsonreader.pp there is this branch:

  tkString : if (joUTF8 in Options) and (DefaultSystemCodePage<>CP_UTF8) then
               StringValue(TJSONStringType(UTF8Decode(CurrentTokenString)))

On a container locale with DefaultSystemCodePage=0 (any non-CP_UTF8
value triggers this), the round-trip UTF8Decode → TJSONStringType cast
silently re-encodes the parsed token through the system codepage. The
result is an AnsiString whose tag is CP_ACP rather than CP_UTF8, and
every codepoint the system CP can't represent gets clipped to a
single trailing byte (or replaced with '?' on a strict-ASCII
fallback). Wire-visible mojibake:

  ¶  UTF-8 C2 B6 → stored as bare B6 → GetStr returns 1 byte
  é  UTF-8 C3 A9 → stored as bare A9 → GetStr returns 1 byte
  中 UTF-8 E4 B8 AD → stored as bare AD → GetStr returns 1 byte
  •  UTF-8 E2 80 A2 → stored as bare A2 → GetStr returns 1 byte

This is the bug surfaced by toolview_tests.TestEditHashlineCall
(the hashline patch header `¶path` lost its lead byte in transit,
producing "fs_edit_hashline(<B6>src/foo.pas)" downstream) and lurks
across every PasClaw boundary that round-trips non-ASCII through
JSON: provider responses (assistant content with em-dashes, smart
quotes, accents), MCP tool I/O, session persistence, gateway
SSE deltas, channel inbound payloads.

Fix: bypass GetJSON entirely. Construct a TStringStream over the
input bytes and drive TJSONParser directly with EMPTY options —
specifically, NO joUTF8. The scanner's string-token path is then a
plain `Move` of the raw bytes into the token AnsiString
(jsonscanner.pp:405), no UTF-8 round-trip happens, and the bytes
PasClaw passed in are the bytes fpjson stores and AsString returns.
Applied to both TJsonObject.Parse and TJsonArray.Parse.

PasClaw treats every string at every boundary as UTF-8 already
(HTTP via Indy + TagUTF8 at PR #149, file IO via TEncoding.UTF8 +
TagUTF8 in ReadFileText, stdout via PasClaw.CliUI.Write on a
UTF-8 terminal). The fpjson "UseUTF8 decode" pass was a redundant
extra round-trip that only served to corrupt them.

Symmetric Add/PutStr behaviour is unchanged because the write side
never went through the lossy branch — fpjson's AnsiString Add just
stores the bytes passed in, and the tag survives the trip through
AsJSON.

Regression coverage in src/tests/json_utf8_roundtrip_tests.pas:
  - U+00B6 (¶, 2-byte UTF-8) round-trip through Object.GetStr
  - U+00E9 (é, 2-byte UTF-8) round-trip
  - U+4E2D + U+2022 (3-byte UTF-8 sequences) round-trip
  - Plain ASCII round-trip (regression guard)
  - JSON escapes (\\" \\\\ \\n) still parsed correctly
  - TJsonArray.Parse + ItemStr symmetric coverage
All 6 pass.

Wired into `make test` as `test-json-utf8-roundtrip`. The previously-
failing toolview TestEditHashlineCall now passes; the separate
TestArgTruncation failure is a distinct ToolView ellipsis/glyph
mojibake (mixed-codepage concat trap, same class as PR #157), not
addressed here.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2e13bdef9c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pkg/json/PasClaw.JSON.pas Outdated
except
on E: Exception do raise EPasClawJSON.CreateFmt('JSON parse: %s', [E.Message]);
try
Parser := TJSONParser.Create(Stream, []);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve UTF-8 for escaped member names

When a peer sends valid JSON that uses \u escapes for non-ASCII object keys, which is common for producers that default to ASCII-only JSON, clearing joUTF8 here makes FPC's scanner convert those escapes through the process code page instead of UTF-8. On the non-UTF-8/CP=0 locale this change is intended to fix, {"caf\u00e9":1} stores the key as caf E9 rather than UTF-8 caf C3 A9, so Has/Get* lookups using the normal UTF-8 key fail even though the raw UTF-8 spelling now works.

Useful? React with 👍 / 👎.

Codex correctly noted that disabling joUTF8 on the parser flips the
SECOND scanner branch into a lossy path:

  jsonscanner.pp:270 (and the surrogate-pair twin at :359)
    if (joUTF8 in Options) or (DefaultSystemCodePage=CP_UTF8) then
      U:=Utf8Encode(WideString(WideChar(u1)))
    else
      U:=String(WideChar(u1));

Without joUTF8 AND with DefaultSystemCodePage <> CP_UTF8, the
WideChar gets cast through the system codepage. On a CP=0 locale:

  é (é) → byte E9      (Latin-1 mapping, want UTF-8 C3 A9)
  中 (中) → ?             (unmappable → ASCII fallback)
  😀 (😀) → garbage  (surrogate pair, same cast)

Producers that emit ASCII-safe JSON spell every non-ASCII codepoint
as \uXXXX (a common defensive default — see RFC 7159 §7). With the
previous fix, such JSON would parse with corrupted strings AND keys.
Has() lookups against the UTF-8 spelling fail because the stored key
is the Latin-1 bytes instead — silently losing data.

Fix: restore joUTF8 in the parser options, and swap
DefaultSystemCodePage = CP_UTF8 across the parse call. That
satisfies both scanner branches:

  Raw bytes  (jsonreader.pp:241): the
    if (joUTF8 in Options) and (DefaultSystemCodePage<>CP_UTF8)
  guard fails on the CP side, so StringValue(CurrentTokenString)
  runs unchanged. Bytes preserved.

  \u escapes (jsonscanner.pp:270, :359): the
    if (joUTF8 in Options) or (DefaultSystemCodePage=CP_UTF8)
  guard succeeds, so Utf8Encode runs. Codepoints encoded to UTF-8
  losslessly.

DefaultSystemCodePage is saved on entry and restored on exit.
Concurrent Parse calls race only on the swap pair — they all set
the same CP_UTF8 value, so the race is benign; the window is the
parser pass itself, brief and CPU-bound. The skip-when-already-CP_UTF8
guard makes the swap a no-op when DefaultSystemCodePage is already
where we want it.

Applied symmetrically to TJsonObject.Parse and TJsonArray.Parse.
Added jsonscanner to the FPC uses-clause for the joUTF8 symbol.

Test plan — extends json_utf8_roundtrip_tests.pas with four new
cases targeting the escape paths:

  TestUnicodeEscapeBMP        — é → UTF-8 C3 A9 (é)
  TestUnicodeEscapeBMP3Byte   — 中 → UTF-8 E4 B8 AD (中)
  TestUnicodeEscapeInKey      — object key with \uXXXX must be
                                findable via its UTF-8 spelling
                                (Has + GetStr round-trip)
  TestSurrogatePairEscape     — 😀 → UTF-8 F0 9F 98 80 (😀)
                                (covers the second lossy branch at
                                jsonscanner.pp:359)

All 10 tests pass. The original toolview ¶ regression
(TestEditHashlineCall) still passes. Full pasclaw build clean;
smoke + every other unit test green.
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