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

From: Dmitry Dolgov <9erthalion6(at)gmail(dot)com>
To: Ishjaap Singh <ishjaap(dot)singh07(at)gmail(dot)com>
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org, 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 17:06:40
Message-ID: aw2qnvhri0VzE10N@ddolgov-thinkpadt14sgen1.rmtde.csb
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

> On Mon, Nov 30, 2026 at 06:09:53PM +0530, Ishjaap Singh wrote:
> Hi,
>
> 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].

Good catch, thanks. The solution looks fine to me, and the only thing
I'm wondering about if it's possible to refactor jpiIndexArray branch a
little. Generally speaking operations on JsonPathExecContext seems to be
following the same patter throughout jsonpath_exec: temporary change in
the context, one or two simple function calls without any conditions in
between, then the change gets reset. Looks like jpiIndexArray is the
only exception, but maybe the loop jsp->content.array.nelems as a whole
could be moved out to a separate static inlineable function to prevent
any possibility of such issues in the future?

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Sami Imseih 2026-11-30 17:18:22 Re: Anti-wraparound autovacuum stops for good after no slot available for new autovacuum worker process
Previous Message Nathan Bossart 2026-11-30 17:05:45 Re: BUG #19688: pg_dump --schema scans all sequences in PostgreSQL 18, causing severe performance regression