Review
Fix JSON_SERIALIZE() coercion placeholder type for jsonb input (v3)
- Proposal version
- 3
- Base commit
- 412848dac37f2e4455e1505f83f0af0f3d28a67d
JSON_SERIALIZE() on jsonb does not return JSON text. It feeds the jsonb datum to json_out(), so the result is a few bytes of the container header, sometimes not valid in the server encoding. v3 types the coercion placeholder from the argument, which is the value the executor actually passes through. That is the right fix, and it should be back-patched to 17.
makeJsonConstructorExpr() builds the RETURNING coercion around a CaseTestExpr. When there is no func expression, that placeholder is json or jsonb according to the RETURNING format. coerceJsonFuncExpr() turns a string or bytea target into a CoerceViaIO. ExecInitExprRec() chooses the output function with getTypeOutputInfo(exprType()) of that argument, so the planned type selects json_out() or jsonb_out(), not the runtime datum.
JSON_SERIALIZE() does not go through ExecEvalJsonConstructor(). For JSCTOR_JSON_SERIALIZE, ExecInitExprRec() evaluates the single argument straight into the result slot and then runs the coercion. transformJsonSerializeExpr() calls transformJsonValueExpr() with no target type. An input that is already json or jsonb is left as it is. The default RETURNING clause is text FORMAT JSON, and bytea is also FORMAT JSON, so the placeholder was always JSONOID. json_out() then ran on jsonb.
json_out() is text_to_cstring(). It copies the varlena by length and does not read past the datum. textin() accepts the cstring via strlen(), so it stops at the first NUL. A jsonb container header is a little-endian uint32 of flags and count, and that word usually contains a zero. On PostgreSQL 18.6 this query returns the one byte 0x03, with octet_length 1:
SELECT JSON_SERIALIZE('[1,2,4]'::jsonb);
'{"a": 1}'::jsonb yields 0x01. '[]'::jsonb and a 256-element array both yield empty text, because the first header byte is 0x00. A 128-element array yields 0x80. That SELECT returns a row. convert_to() of the result then fails with invalid byte sequence for encoding "UTF8": 0x80. textin() does not check encoding. RETURNING bytea uses the same text step and then convert_to(), so the unpatched result is \x01 rather than the JSON bytes. RETURNING varchar(2) accepts the one-byte header. json input is fine and returns {"a": 1}. This is a wrong cast and a wrong value, not a cosmetic result type and not an over-read.
The pass-through and the format-based placeholder are unchanged on REL_17_STABLE and REL_18_STABLE. JSON_SERIALIZE() arrived in 03734a7fed7, and the placeholder was tied to the RETURNING format in 86d33987e8b. Both commits are in 17.
v3 sets the placeholder type to exprType() of the single argument when the constructor is JSCTOR_JSON_SERIALIZE, and asserts that the argument list has length one. Other constructors still use the RETURNING format. That matches the fexpr arm, which already uses exprType() of the func, and JSON_TABLE, whose CaseTestExpr uses the document expression's type. A jsonb argument then takes the assignment cast to the string type: jsonb_out() and the target input function. RETURNING bytea still uses the FORMAT JSON path in coerceJsonFuncExpr(), which coerces to text and then calls convert_to(). String and unknown inputs are still coerced to json in transformJsonValueExpr() first, so those placeholders stay JSONOID.
The other SQL/JSON functions do not have this mismatch. JSON() coerces its argument to the returning json or jsonb type before the same pass-through. JSON_SCALAR(), JSON_OBJECT(), JSON_ARRAY(), JSON_OBJECTAGG(), and JSON_ARRAYAGG() produce a real json or jsonb value of the format the placeholder already names. JSON_VALUE() and JSON_QUERY() coerce inside JsonExpr, not this CaseTestExpr. On 18.6, JSON(), JSON_SCALAR(), JSON_OBJECT(), JSON_VALUE(), and JSON_QUERY() all return normal text for a jsonb input. A domain over jsonb never reaches the new code. transformJsonValueExpr() rejects it with "cannot use non-string types with implicit FORMAT JSON clause". That check compares the type to JSONBOID exactly and is unchanged.
Casting jsonb to json in transformJsonSerializeExpr(), or converting in the executor, would also avoid json_out() on jsonb. Both add a conversion, and an executor-only change would leave the wrong coercion in the tree. Typing the placeholder from the argument is the direct fix. Stored views and rules keep the old CoerceViaIO until they are recreated. That is normal for a parser fix.
The new sqljson tests are the ones that catch a regression. The default text case must return {"a": 1}. RETURNING bytea must return \x7b2261223a20317d, which is that text. RETURNING varchar(2) must fail with "value too long for type character varying(2)". Without the fix, on 18.6, that varchar(2) query succeeds and returns the one-byte header. NULL::jsonb already returns NULL and does not call the output function.
Zsolt Parragi tested an early version. Nikhil Sontakke asked to drop redundant cases, then asked for the length Assert, the Node * cast, and the typmod case. v3 does that, and Nikhil marked it Ready for Committer. No one objected. Shihao Zhong later posted the same placeholder change on the bugs thread, with Backpatch-through: 17, and noted that existing views stay wrong until recreated:
https://postgr.es/m/CAGRkXqQXwh_gJmQE3PZj0v13omMPgFGBbb8TJoBFH8ECsAFCUg@mail.gmail.com
v3's message does not say to back-patch. The code on 17 and 18 is the same bug, so the commit should. The original report is:
https://postgr.es/m/03583FE7-A5EE-407C-907D-67865F3F8BFC@gmail.com
Assessment is 88, down 2 from the 90 anchor. The failure is real, the patch matches the executor, and the tests lock the value rather than the plan shape. The two points are only for the missing back-patch note, not for a problem in the change. Consensus is 76, up 6 from 70. Two reviewers went through the patch, the author took every comment, and the later bugs-list patch is the same fix with no disagreement. That is enough for a change this size, short of a wide thread.