BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

Started by PG Bug reporting form3 months ago14 messagesbugs
Jump to latest
#1PG Bug reporting form
noreply@postgresql.org

The following bug has been logged on the website:

Bug reference: 19621
Logged by: Suyang Zhong
Email address: syzhong16@gmail.com
PostgreSQL version: 19beta3
Operating system: Ubuntu 22.04
Description:

Consider the following test case:

```sql
CREATE TABLE t0(x text);
INSERT INTO t0 VALUES ('{}'), (NULL);
CREATE VIEW v0 AS
SELECT x, json_value(x, '$.a' RETURNING int DEFAULT 42 ON EMPTY) AS jv
FROM t0;

SELECT x IS NULL AS is_null, jv FROM v0;
-- f | 42
-- t | 42

SELECT jv FROM v0 WHERE x IS NULL;
-- NULL
```

The second query selects exactly the row the first query shows as `t | 42`,
yet returns NULL for its `jv`.

A further reduction shows that the result depends on the input row order.

```sql
SELECT json_value(x, '$.a' RETURNING int DEFAULT 42 ON EMPTY) FROM (VALUES
('{}'), (NULL)) v(x);
-- 42
-- 42
SELECT json_value(x, '$.a' RETURNING int DEFAULT 42 ON EMPTY) FROM (VALUES
(NULL), ('{}')) v(x);
-- NULL
-- 42
```

Reproduced on 20devel, and on 17.11, 18.1, 18.4, and 19beta3; on 17rc1 only
the `ON ERROR` variants misbehave.

#2Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: PG Bug reporting form (#1)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

вс, 16 авг. 2026 г. в 17:36, PG Bug reporting form <noreply@postgresql.org>:

Consider the following test case:

```sql
CREATE TABLE t0(x text);
INSERT INTO t0 VALUES ('{}'), (NULL);
CREATE VIEW v0 AS
SELECT x, json_value(x, '$.a' RETURNING int DEFAULT 42 ON EMPTY) AS jv
FROM t0;

SELECT x IS NULL AS is_null, jv FROM v0;
-- f | 42
-- t | 42

SELECT jv FROM v0 WHERE x IS NULL;
-- NULL
```

The second query selects exactly the row the first query shows as `t | 42`,
yet returns NULL for its `jv`.

A further reduction shows that the result depends on the input row order.

```sql
SELECT json_value(x, '$.a' RETURNING int DEFAULT 42 ON EMPTY) FROM (VALUES
('{}'), (NULL)) v(x);
-- 42
-- 42
SELECT json_value(x, '$.a' RETURNING int DEFAULT 42 ON EMPTY) FROM (VALUES
(NULL), ('{}')) v(x);
-- NULL
-- 42
```

Reproduced on 20devel, and on 17.11, 18.1, 18.4, and 19beta3; on 17rc1 only
the `ON ERROR` variants misbehave.

Hi, Suyang!

Thanks for the report!

On NULL input, jsonpath is deliberately not run: there is nothing to
search, so the result is NULL (a NOT NULL domain still checks the NULL).

The "found empty" / "had an error" flags were cleared only in the step
that runs jsonpath. NULL skips that step, so the previous row's flags
remain. The next check is "empty? then DEFAULT" — and it fires for the
wrong row.

This dates to SQL/JSON itself (6185c973, March 2024): NULL skips path
evaluation, the reset lived inside that evaluation. Later (dd8bea88abf)
the extra steps were omitted for the default "just return NULL", so the
bug stayed hidden. A non-NULL DEFAULT (42, TRUE ON ERROR) keeps those
steps — the bug shows. On 17rc1 the reporter mostly saw ON ERROR: ON
EMPTY DEFAULT did not always go through the same path yet.

Proposal fix
-----------
Clear "empty/error" at the start of each row, before deciding not to
run the path on NULL. NULL still does not run the path. The only change
is that another row's DEFAULT no longer sticks.

CC Amit Langote (JSON).

Attachments:

t253430_2
0001-Reset-JsonExpr-empty-error-flags-before-NULL-short-circuit.patchtext/x-patch; charset=US-ASCII; name=0001-Reset-JsonExpr-empty-error-flags-before-NULL-short-circuit.patchDownload+120-16
#3zengman
zengman@halodbtech.com
In reply to: Andrey Rachitskiy (#2)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

Hi everyone,

I have another question related to JSON functions. Although it is a different issue, I wonder whether it would make sense to handle both cases in the same patch.

I tested the current patch, but it does not seem to address the problem I reported here:

```
/messages/by-id/19625-683b498c92087bc8@postgresql.org
```

--
Regards,
Man Zeng

#4Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: zengman (#3)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

вт, 18 авг. 2026 г. в 07:06, zengman <zengman@halodbtech.com>:

I tested the current patch, but it does not seem to address the problem I
reported here:
```

/messages/by-id/19625-683b498c92087bc8@postgresql.org
```

Dear Zeng,

One is per-row executor state. The other is a wrong parse-time rewrite of a
boolean DEFAULT. They share only that both involve SQL/JSON DEFAULT.
Combining them would mix an executor opcode change with a parser coercion
change, and it would make review and back-patching harder.

--
Regards,
Rachitskiy Andrey

#5Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Andrey Rachitskiy (#4)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

вт, 18 авг. 2026 г. в 13:56, Andrey Rachitskiy <pl0h0yp1@gmail.com>:

вт, 18 авг. 2026 г. в 07:06, zengman <zengman@halodbtech.com>:

I tested the current patch, but it does not seem to address the problem I
reported here:
```

/messages/by-id/19625-683b498c92087bc8@postgresql.org
```

Dear Zeng,

One is per-row executor state. The other is a wrong parse-time rewrite of
a boolean DEFAULT. They share only that both involve SQL/JSON DEFAULT.
Combining them would mix an executor opcode change with a parser coercion
change, and it would make review and back-patching harder.

Dear Amit,

Attached is v2 of the patch.
v1 was a malformed unified diff: three context lines after the
ExecEvalJsonIsPredicate hunk were missing the leading space, so
git apply rejected the file as corrupt. There is no code change
versus v1.

I also re-checked the reporter's JSON_EXISTS / JSON_VALUE /
JSON_QUERY examples from the later duplicate report [0]/messages/by-id/19654-3acd06154d027634@postgresql.org; they pass
with this patch.

[0]: /messages/by-id/19654-3acd06154d027634@postgresql.org
/messages/by-id/19654-3acd06154d027634@postgresql.org

--
Regards,
Rachitskiy Andrey

Attachments:

t253430_5
v2-0001-Reset-JsonExpr-empty-error-flags-before-NULL-short-circuit.patchtext/x-patch; charset=US-ASCII; name=v2-0001-Reset-JsonExpr-empty-error-flags-before-NULL-short-circuit.patchDownload+124-16
#6Manu
manuelreyesbravo@gmail.com
In reply to: Andrey Rachitskiy (#5)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

Hi Andrey,

I tested v2 on master, REL_18_STABLE and REL_17_STABLE, together with
Srinath's fix for #19695 [1]/messages/by-id/CAFC+b6p8Oo3_pLXPa=DVXx1XDQJ09b2W3U3WKPtkQYyh0z0z-A@mail.gmail.com, which touches the same function. Both
apply cleanly on all three branches, build without warnings, and the
main regression suite passes. The reported cases now give the right
answer on the three branches:

- #19621: json_value(x, '$.a' RETURNING int DEFAULT 42 ON EMPTY) over
'{}' then NULL returns 42, NULL (it was 42, 42)
- #19654: json_exists(j, 'strict $.a' FALSE ON ERROR) over '{}' then
NULL returns false, NULL (it was false, false)

I could not exercise the llvmjit_expr.c part: this machine has no LLVM
build.

One thing for the back-patch. EEOP_JSONEXPR_RESET is inserted before
EEOP_JSONEXPR_PATH, so every opcode from there to EEOP_LAST changes its
value: 24 of them on REL_17_STABLE and 25 on REL_18_STABLE. On master
that is fine, but the back branches are under the buildfarm's ABI
compliance check (.abi-compliance-history), and anything built against
a minor release that uses those values would be off by one after the
update. Putting the new opcode just before EEOP_LAST in the
back-branch versions, with the dispatch table and llvmjit_expr.c
following the same order, would leave the existing values alone.

If you post back-branch versions, I will rerun the same checks on
them.

[1]: /messages/by-id/CAFC+b6p8Oo3_pLXPa=DVXx1XDQJ09b2W3U3WKPtkQYyh0z0z-A@mail.gmail.com
/messages/by-id/CAFC+b6p8Oo3_pLXPa=DVXx1XDQJ09b2W3U3WKPtkQYyh0z0z-A@mail.gmail.com

Regards,
Manu

#7Srinath Reddy Sadipiralla
srinath2133@gmail.com
In reply to: Manu (#6)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

Hi,

Patch LGTM , I have tested with LLVM build as well , it works as intended.

--
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/

#8Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Srinath Reddy Sadipiralla (#7)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

чт, 24 сент. 2026 г., 22:07 Srinath Reddy Sadipiralla <srinath2133@gmail.com

:

Hi,

Patch LGTM , I have tested with LLVM build as well , it works as intended.

--
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/

Hi, Srinath!
Thnx for the review!

Manu, thnx for the testing.

---
Regards,
Rachitskiy Andrey

Show quoted text
#9jian he
jian.universality@gmail.com
In reply to: Andrey Rachitskiy (#5)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

On Fri, Sep 4, 2026 at 6:38 PM Andrey Rachitskiy <pl0h0yp1@gmail.com> wrote:

Attached is v2 of the patch.

--
Regards,
Rachitskiy Andrey

+ EEO_CASE(EEOP_JSONEXPR_RESET)
+ {
+ ExecEvalJsonExprReset(state, op);
+
+ EEO_NEXT();
+ }
+
--- a/src/include/executor/execExpr.h
+++ b/src/include/executor/execExpr.h
@@ -265,6 +265,7 @@ typedef enum ExprEvalOp
  EEOP_XMLEXPR,
  EEOP_JSON_CONSTRUCTOR,
  EEOP_IS_JSON,
+ EEOP_JSONEXPR_RESET,
  EEOP_JSONEXPR_PATH,
  EEOP_JSONEXPR_COERCION,
  EEOP_JSONEXPR_COERCION_FINISH,

This seems unnecessary.
In EEOP_JSONEXPR_PATH, we can
if document or jsonpath is NULL, we can just go to jump_end (return
NULL) or jump_eval_coercion (NULL need coerce to constrainted domain),
no need to worry about ON ERROR, ON EMPTY.

What do you think of the attachment?

--
jian
https://www.enterprisedb.com/

Attachments:

t253430_9
v3-0001-Reset-JsonExpr-empty-error-flags-before-NULL-short-circuit.patchtext/x-patch; charset=US-ASCII; name=v3-0001-Reset-JsonExpr-empty-error-flags-before-NULL-short-circuit.patchDownload+116-22
#10Manu
manuelreyesbravo@gmail.com
In reply to: jian he (#9)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

Hi jian,

This seems unnecessary.
In EEOP_JSONEXPR_PATH, we can
if document or jsonpath is NULL, we can just go to jump_end (return
NULL) or jump_eval_coercion (NULL need coerce to constrainted domain),
no need to worry about ON ERROR, ON EMPTY.

That also takes care of the back-branch concern I raised on v2: with
no new opcode, v3 does not change any header, so the ExprEvalOp values
stay as they are.

v3 applies cleanly to master, REL_18_STABLE and REL_17_STABLE, builds
without warnings, and the main regression suite passes on all three.

Since the bug is state leaking from one row to the next, I also
checked it with a differential test (attached): every row of a
two-row query must give the same result as that row evaluated alone.
It covers json_value (RETURNING int, a NOT NULL domain and a CHECK
domain), json_query and json_exists, with every ON EMPTY / ON ERROR
combination, over every ordered pair of rows built from five
documents ('{}', '{"a":1}', '{"a":"x"}', '{"a":[1,2]}', NULL) and
three paths ('$.a', 'strict $.a', NULL). That is 9675 cases:

- unpatched master (09a579abaca): 567 mismatches (497 json_value,
56 json_query, 14 json_exists)
- v3 on master, REL_18_STABLE and REL_17_STABLE: 0

The single-row answers do not change: all 645 of them are the same
with and without v3, including NULL input into the NOT NULL domain.

With Srinath's fix for #19695 on top, its case is right too
(1, NULL, 2). As before, I could not exercise JIT here.

Regards,
Manu

Attachments:

rows_oracle.sql.txttext/plainDownload
#11Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: jian he (#9)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

сб, 26 сент. 2026 г. в 21:29, jian he <jian.universality@gmail.com>:

On Fri, Sep 4, 2026 at 6:38 PM Andrey Rachitskiy <pl0h0yp1@gmail.com>
wrote:

Attached is v2 of the patch.

--
Regards,
Rachitskiy Andrey

+ EEO_CASE(EEOP_JSONEXPR_RESET)
+ {
+ ExecEvalJsonExprReset(state, op);
+
+ EEO_NEXT();
+ }
+
--- a/src/include/executor/execExpr.h
+++ b/src/include/executor/execExpr.h
@@ -265,6 +265,7 @@ typedef enum ExprEvalOp
EEOP_XMLEXPR,
EEOP_JSON_CONSTRUCTOR,
EEOP_IS_JSON,
+ EEOP_JSONEXPR_RESET,
EEOP_JSONEXPR_PATH,
EEOP_JSONEXPR_COERCION,
EEOP_JSONEXPR_COERCION_FINISH,

This seems unnecessary.
In EEOP_JSONEXPR_PATH, we can
if document or jsonpath is NULL, we can just go to jump_end (return
NULL) or jump_eval_coercion (NULL need coerce to constrainted domain),
no need to worry about ON ERROR, ON EMPTY.

What do you think of the attachment?

--
jian
https://www.enterprisedb.com/

Hi, Jian!

Thanks for posting this alternative.

I considered the same shape earlier: keep the empty/error reset in
EEOP_JSONEXPR_PATH and stop skipping that step on SQL NULL. Your version is
simpler than adding EEOP_JSONEXPR_RESET. No new opcode, and no JIT or
back-branch ABI churn.

The commit message still described a RESET opcode that the diff does not
add. I adjusted the subject and body to match what the patch actually does
(retarget JUMP_IF_NULL at PATH, drop the CONST NULL pad, handle NULL inside
ExecEvalJsonExprPath).

Either approach fixes the reported cases. I am fine with whichever version
a committer prefers.

Attachments:

t253430_11
v3-0001-Handle-SQL-NULL-inside-EEOP-JSONEXPR-PATH.patchtext/x-patch; charset=US-ASCII; name=v3-0001-Handle-SQL-NULL-inside-EEOP-JSONEXPR-PATH.patchDownload+116-22
#12Amit Langote
amitlangote09@gmail.com
In reply to: Andrey Rachitskiy (#11)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

Hi,

On Mon, Sep 28, 2026 at 1:03 PM Andrey Rachitskiy <pl0h0yp1@gmail.com> wrote:

сб, 26 сент. 2026 г. в 21:29, jian he <jian.universality@gmail.com>:

On Fri, Sep 4, 2026 at 6:38 PM Andrey Rachitskiy <pl0h0yp1@gmail.com> wrote:

Attached is v2 of the patch.

--
Regards,
Rachitskiy Andrey

+ EEO_CASE(EEOP_JSONEXPR_RESET)
+ {
+ ExecEvalJsonExprReset(state, op);
+
+ EEO_NEXT();
+ }
+
--- a/src/include/executor/execExpr.h
+++ b/src/include/executor/execExpr.h
@@ -265,6 +265,7 @@ typedef enum ExprEvalOp
EEOP_XMLEXPR,
EEOP_JSON_CONSTRUCTOR,
EEOP_IS_JSON,
+ EEOP_JSONEXPR_RESET,
EEOP_JSONEXPR_PATH,
EEOP_JSONEXPR_COERCION,
EEOP_JSONEXPR_COERCION_FINISH,

This seems unnecessary.
In EEOP_JSONEXPR_PATH, we can
if document or jsonpath is NULL, we can just go to jump_end (return
NULL) or jump_eval_coercion (NULL need coerce to constrainted domain),
no need to worry about ON ERROR, ON EMPTY.

What do you think of the attachment?

--
jian
https://www.enterprisedb.com/

Hi, Jian!

Thanks for posting this alternative.

I considered the same shape earlier: keep the empty/error reset in EEOP_JSONEXPR_PATH and stop skipping that step on SQL NULL. Your version is simpler than adding EEOP_JSONEXPR_RESET. No new opcode, and no JIT or back-branch ABI churn.

The commit message still described a RESET opcode that the diff does not add. I adjusted the subject and body to match what the patch actually does (retarget JUMP_IF_NULL at PATH, drop the CONST NULL pad, handle NULL inside ExecEvalJsonExprPath).

Either approach fixes the reported cases. I am fine with whichever version a committer prefers.

Thanks, Jian and Andrey. I agree that v3’s approach of having
ExecEvalJsonExprPath() itself handle a NULL context item or path is
better than adding a new code to do that job, which as you have
pointed out is not painless to backpatch.

Here is v4 with some comment and commit message updates, plus one more
regression case for JSON_EXISTS’s default FALSE ON ERROR. I plan to
commit and back-patch it to 17 barring objections.

--
Thanks, Amit Langote

Attachments:

t253430_12
v4-0001-SQL-JSON-Fix-ON-EMPTY-ERROR-state-leakage-on-NULL.patchapplication/octet-stream; name=v4-0001-SQL-JSON-Fix-ON-EMPTY-ERROR-state-leakage-on-NULL.patchDownload+140-20
#13Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Amit Langote (#12)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

ср, 4 нояб. 2026 г., 15:06 Amit Langote <amitlangote09@gmail.com>:

Here is v4 with some comment and commit message updates, plus one more
regression case for JSON_EXISTS’s default FALSE ON ERROR. I plan to
commit and back-patch it to 17 barring objections.

Hi Amit,

LGTM

Thanks for the review

#14Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Andrey Rachitskiy (#13)
Re: BUG #19621: Unexpected results of JSON_VALUE with DEFAULT ON EMPTY

Amit, thnx for pushing.
https://commitfest.postgresql.org/patch/7414/ marked as committed.

--
Regards,
Rachitskiy Andrey