Re: BUG #19957: jsonpath `last` returns the wrong index after a filter containing `exists($x[0])`

From: Ishjaap Singh <ishjaap(dot)singh07(at)gmail(dot)com>
To: pgsql-bugs(at)lists(dot)postgresql(dot)org
Cc: e1638616(at)u(dot)nus(dot)edu
Subject: Re: BUG #19957: jsonpath `last` returns the wrong index after a filter containing `exists($x[0])`
Date: 2026-11-30 12:39:53
Message-ID: CA+Y2BmdrquM-n_2d8L4DvWyi5fCTLVEP1MRyuZJ4j2F4x+KFNw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Hi,

I can reproduce this on 15 through 19 and master.

The array subscript case in executeItemOptUnwrapTarget() sets
innermostArraySize for LAST and restores it after its subscript loop,
but two exits return before the restore. One is the early return when
no result is wanted. In lax mode exists() evaluates its argument that
way, so $x[0] leaves the size of $x behind and the outer LAST uses it.
$x[*] is not an array subscript, so it doesn't touch
innermostArraySize. The other is the out-of-bounds error when errors
are suppressed, as when the path is strict and exists() hides the
error:

select jsonb_path_query_array('[10, 20, 30]',
'strict $[0 ? (exists($x[5]) || @ == 0), last]', '{"x": [1, 2]}');

also returns [10, 20]. When $x is longer than the outer array, lax
mode drops the element silently, since LAST points past the end:
with $x = [1, 2, 3, 4, 5] the query from the report returns [10].

The attached patch restores innermostArraySize on both paths and adds
three tests to jsonb_jsonpath.sql, which fail without the fix. Both
exits go back to the original jsonpath commit 72b6460336e. The patch
applies to master and REL_19_STABLE. I also have versions for 15 to
18, where only the context differs; make check passes with the fix on
all six branches. I can post them if that helps.

Regards,
Ishjaap Singh

Attachment Content-Type Size
v1-0001-Fix-jsonpath-LAST-after-an-array-subscript-inside.patch application/octet-stream 4.2 KB

In response to

Browse pgsql-bugs by date

  From Date Subject
Previous Message Matheus Alcantara 2026-11-30 11:57:34 Re: BUG #19789: "expression not found in statistics object" for a boolean domain column in an MCV statistics object