← Back to Pull requests

MDEV-41153 json_escape() omits the second \u in surrogate pairs for n… #5759

Open
gengtianuiowa opened this pull request with 152 lines diff across 4 files
View on GitHub
gengtianuiowa gengtianuiowa commented on Sep 24, 2026 21:33 UTC
Author

Problem

A character outside the Basic Multilingual Plane is encoded in UTF-16 as a
surrogate pair. JSON requires each half of that pair to carry its own \u
prefix, so U+1F600 must be written as \uD83D\uDE00. json_escape() emitted a
single \u followed by the hex digits of both halves — \uD83DDE00 — which is
not valid JSON.

Because the output cannot be parsed back, any function that re-reads it fails:

SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF09F9880);
NULL
Warning 4038  Syntax error in JSON text in argument 1 to function 'json_set' at position 12

The escaping path is taken whenever the target character set cannot represent
the character, so any non-BMP character reaching a non-Unicode charset is
affected.

Root cause

json_escape() in strings/json_lib.c writes the "\u" prefix once, before the
hex digits, and then appends 4 or 8 hex digits depending on u_len:

uchar code_str[8];
int u_len= my_uni_utf16(0, c_chr, utf16buf, utf16buf + 4);

code_str[0]= hexconv[utf16buf[0] >> 4];          /* high surrogate */
...
if (u_len > 2)
{
  code_str[4]= hexconv[utf16buf[2] >> 4];        /* low surrogate, no \u prefix */
  ...
}

json_append_ascii(json_cs, json, json_end, code_str, code_str + u_len*2);

my_uni_utf16() returns 2 bytes for a BMP character and 4 for a surrogate pair,
but the code only ever emits one \u.

Fix

Emit one complete \uXXXX escape per UTF-16 code unit: loop over the buffer in
2-byte steps and write the \u prefix again before the low surrogate. The
leading \u of the first escape is still written by the existing generic escape
code above the loop.

Also reject a negative my_uni_utf16() return instead of using it as a length.
my_uni_utf16() answers MY_CS_ILUNI if asked to encode a code point that is
itself a surrogate, and the old code_str + u_len2 would then point before
code_str. This is a latent pre-existing issue rather than part of the reported
bug; it is included because the new loop bound would otherwise silently emit a
bare \u.

BMP characters are unaffected — they take a single loop iteration and produce
byte-identical output to before.

 strings/json_lib.c               | 56 +++++++++++++++++++-----------
 mysql-test/main/func_json.test   | 28 ++++++++++++++
 mysql-test/main/func_json.result | 35 ++++++++++++++++++

Testing

Added to mysql-test/main/func_json.test. Verified failing before the change
(every non-BMP case returned NULL with
Syntax error in JSON text) and passing
after.

| Case | Before | After |
|---|---|---|
| U+1F600 | NULL + syntax error | {"x": "\uD83D\uDE00"} |
| JSON_VALID of the above | NULL | 1 |
| Byte-level round trip via JSON_EXTRACT | NULL | F09F9880 |
| U+10000 (first non-BMP) | NULL | {"x": "\uD800\uDC00"} |
| U+10FFFF (last non-BMP) | NULL | {"x": "\uDBFF\uDFFF"} |
| Two adjacent non-BMP characters | NULL | {"x": "\uD83D\uDE00\uD83D\uDE01"} |
| U+0100, U+FFFD (BMP controls) | one escape | unchanged: \u0100, \uFFFD |
| U+00F6 (representable in latin1) | not escaped | unchanged, JSON_VALID = 1 |

The two BMP cases are controls: they must produce exactly one escape both before
and after, which is what guards the loop change from over-escaping. U+0100 and
U+FFFD were chosen because latin1 cannot represent them, so they genuinely reach
the escaping path — unlike U+00F6, which latin1 encodes directly and therefore
never escapes at all.

Suites

Every caller of json_escape() was identified and the covering suite run:

| Caller | Suite | Result |
|---|---|---|
| sql/item_jsonfunc.cc, sql/opt_histogram_json.cc | main (full) | 1200/1200 pass |
| sql/mysqld.cc (json_escape_string plugin service) | json, plugins, funcs_1, sys_vars | 798/799 |
| sql/sql_acl.cc (mysql.global_priv is JSON) | roles | 92/94 |
| escaping + charset conversion | func_json, func_json_notembedded, gis-json, ctype_utf8mb4, ctype_utf16, ctype_ucs | all pass |

Three failures appeared and none are caused by this change:

  • roles.set_default_role_invalid_skip_name_resolve — pre-existing. Confirmed by

  • reverting only strings/json_lib.c to stock 11.4, rebuilding, and observing
    the identical failure.
  • roles.acl_load_mutex-5170, sys_vars.allow_suspicious_udfs — pass

  • standalone; parallel-execution flakes.

    ACL and system-variable values are ASCII, so json_escape() returns before
    reaching the modified loop and its output there is byte-identical.

    Build: clang, -DWITH_WSREP=OFF, PerfSchema/RocksDB/ColumnStore/Mroonga/Connect
    disabled. MTR run with --skip-rpl; running as root skipped some tests. The
    rpl, galera, innodb
    , encryption and mariabackup suites were not run —
    none of them call json_escape().

    Note on target branch

    The Jira lists fixVersions 10.11, 11.4, 11.8, 12.3, 13.0, 13.1, and the
    buggy block is byte-identical on every one of those branches plus main:

    | Branch | Version | Buggy block |
    |---|---|---|
    | 10.11 | 10.11.19 | present |
    | 11.4 | 11.4.13 | present |
    | 11.8 | 11.8.9 | present |
    | 12.3 | 12.3.3 | present |
    | main | 13.2.0 | present |

    Copyright

    All new code of the whole pull request, including one or several files
    that are either new files or modified ones, are contributed under the
    BSD-new license. I am contributing on behalf of my employer Amazon Web
    Services, Inc.

    Diff: 152 lines (+131 / -21) across 4 files Reviewer: gkodinov Review duration: 33576m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.37) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.37 · 152 lines diff across 4 files
    0.37
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    91%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.301
    Real PR Conversation Timeline
    10 items
    gkodinov gkodinov requested changes on Sep 25, 2026 08:17 UTC
    Changes Requested Reviewer

    Thank you for your contribution! This is a preliminary review.

    First of all: please rebase on 11.4: 10.11 is close to EOL and we try to be conservative what is fixed in it.

    Also, your test fails in buildbot as follows, please fix:

    main.func_json                           w24 [ fail ]
            Test ended at 2026-09-24 21:45:46
    CURRENT_TEST: main.func_json
    --- /home/buildbot/amd64-debian-12-debug-embedded/build/mysql-test/main/func_json.result	2026-09-24 21:38:25.000000000 +0000
    +++ /home/buildbot/amd64-debian-12-debug-embedded/build/mysql-test/main/func_json.reject	2026-09-24 21:45:46.404652264 +0000
    @@ -3097,7 +3097,7 @@
     # U+1F600 GRINNING FACE, escaped because latin1 cannot represent it
     SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF09F9880) AS non_bmp;
     non_bmp
    -{"x": "\uD83D\uDE00"}
    +{"x": "\uD83D\uDE
     # The escaped output must be valid JSON and survive a round trip
     SELECT JSON_VALID(JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF09F9880)) AS valid;
     valid
    @@ -3109,14 +3109,14 @@
     # Boundary cases: first and last non-BMP code points
     SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF0908080) AS u10000;
     u10000
    -{"x": "\uD800\uDC00"}
    +{"x": "\uD800\uDC
     SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF48FBFBF) AS u10ffff;
     u10ffff
    -{"x": "\uDBFF\uDFFF"}
    +{"x": "\uDBFF\uDF
     # Several non-BMP characters in one string
     SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF09F9880F09F9881) AS two_non_bmp;
     two_non_bmp
    -{"x": "\uD83D\uDE00\uD83D\uDE01"}
    +{"x": "\uD83D\uDE
     # A BMP character that latin1 cannot represent is still escaped with
     # exactly one \uXXXX (unchanged behaviour).  U+0100 and U+FFFD sit below
     # and just above the surrogate range respectively.
    

    CLAassistant CLAassistant commented on Sep 25, 2026 16:40 UTC
    Contributor
    gengtianuiowa gengtianuiowa commented on Sep 25, 2026 16:44 UTC
    Author

    Thank you for your contribution! This is a preliminary review.

    > First of all: please rebase on 11.4: 10.11 is close to EOL and we try to be conservative what is fixed in it.

    > Also, your test fails in buildbot as follows, please fix:

    >
    > main.func_json                           w24 [ fail ]
    >         Test ended at 2026-09-24 21:45:46
    > CURRENT_TEST: main.func_json
    > --- /home/buildbot/amd64-debian-12-debug-embedded/build/mysql-test/main/func_json.result	2026-09-24 21:38:25.000000000 +0000
    > +++ /home/buildbot/amd64-debian-12-debug-embedded/build/mysql-test/main/func_json.reject	2026-09-24 21:45:46.404652264 +0000
    > @@ -3097,7 +3097,7 @@
    >  # U+1F600 GRINNING FACE, escaped because latin1 cannot represent it
    >  SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF09F9880) AS non_bmp;
    >  non_bmp
    > -{"x": "\uD83D\uDE00"}
    > +{"x": "\uD83D\uDE
    >  # The escaped output must be valid JSON and survive a round trip
    >  SELECT JSON_VALID(JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF09F9880)) AS valid;
    >  valid
    > @@ -3109,14 +3109,14 @@
    >  # Boundary cases: first and last non-BMP code points
    >  SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF0908080) AS u10000;
    >  u10000
    > -{"x": "\uD800\uDC00"}
    > +{"x": "\uD800\uDC
    >  SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF48FBFBF) AS u10ffff;
    >  u10ffff
    > -{"x": "\uDBFF\uDFFF"}
    > +{"x": "\uDBFF\uDF
    >  # Several non-BMP characters in one string
    >  SELECT JSON_SET(_latin1'{}', '$.x', _utf8mb4 0xF09F9880F09F9881) AS two_non_bmp;
    >  two_non_bmp
    > -{"x": "\uD83D\uDE00\uD83D\uDE01"}
    > +{"x": "\uD83D\uDE
    >  # A BMP character that latin1 cannot represent is still escaped with
    >  # exactly one \uXXXX (unchanged behaviour).  U+0100 and U+FFFD sit below
    >  # and just above the surrogate range respectively.
    > 

    Taking a look.

    gengtianuiowa gengtianuiowa commented on Sep 25, 2026 21:21 UTC
    Author

    Targeted the PR to 11.4 and resolved the test failure.

    gkodinov gkodinov requested changes on Sep 28, 2026 11:35 UTC
    Changes Requested Reviewer

    Thank you! Can you please resolve the conflicts in func_json.test so that buildbot can test this?

    gengtianuiowa gengtianuiowa commented on Sep 28, 2026 16:36 UTC
    Author

    Fixed the conflict. Waiting for the build to pass

    gkodinov gkodinov approved these changes on Sep 29, 2026 10:39 UTC
    Approved Reviewer

    LGTM. Thanks! Please stand by for the final review.

    sanja-byelkin sanja-byelkin commented on Oct 01, 2026 07:03 UTC
    Contributor

    @gkodinov Above looks like a seriouse bug (wrong results) wich potentially touch a lot of users, are you sure it should live yet another 2 years in 10.11?

    raghunandanbhat raghunandanbhat requested changes on Oct 01, 2026 08:32 UTC
    Changes Requested Reviewer

    @gengtianuiowa, could you please rebase this back to 10.11, it has 2 more years for EOL. thanks for understanding.

    Reviewers
    Assignees
    gengtianuiowa gengtianuiowa
    Labels
    risk: low confidence: 91.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 37.5% (MEDIUM) · Higher = larger blast radius
    37.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 91.9% · Lower = rushed or shallow review
    91.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 3% · Safe to merge
    3%
    Repository