[PG19] jsonb_object_agg as a window function returns stale values

Started by shihao zhongabout 1 month ago6 messageshackers
Jump to latest
#1shihao zhong
zhong950419@gmail.com

Hi,

This is High 2 from my list in [1]/messages/by-id/CAGRkXqSFdjqZP_kwRz7dv6LHX-CSrkDnynNXgntRsCEnQTKxmg@mail.gmail.com.

Since b61aa76e458, jsonb_object_agg as a window function can return
an old value for a key.

select g, jsonb_object_agg(k, v) over (order by g)
from (values (1,'a',1),(1,'a',2),(1,'a',3),(1,'b',5),(2,'b',6),
(3,'a',7)) t(g,k,v);

For g=2 master gives {"a": 3, "b": 5}. 18 gives {"a": 3, "b": 6}.
The second query in 0002 runs over 120 rows with 8 keys, and 97 rows
come back wrong.

In a window the final function runs once per row. Each run ends the
object on the shared state, which sorts the pairs array and removes
duplicate keys in place. A pair added after that can lose to an older
pair with the same key. The comment there assumes this step can run
many times on the same state, and that does not hold.

0001 makes the final function work on a copy of the pairs array. The
cost is one memcpy per final call. 0002 adds a test. jsonb_agg is not
affected. The patches apply to master and REL_19_STABLE.

The commit came from [2]/messages/by-id/1060917.1753202222@sss.pgh.pa.us.

A smaller fix is to renumber the pairs after the dedup. That fixes
the queries above. But the same step drops null pairs from the state,
so this still differs from 18:

select g, jsonb_object_agg_unique_strict(k, v) over (order by g)
from (values (1, 'a', null::int), (2, 'a', 1)) t(g, k, v);

18 and 0001 report a duplicate key. master and the smaller fix return
{"a": 1} for g=2.

[1]: /messages/by-id/CAGRkXqSFdjqZP_kwRz7dv6LHX-CSrkDnynNXgntRsCEnQTKxmg@mail.gmail.com
/messages/by-id/CAGRkXqSFdjqZP_kwRz7dv6LHX-CSrkDnynNXgntRsCEnQTKxmg@mail.gmail.com
[2]: /messages/by-id/1060917.1753202222@sss.pgh.pa.us

Thanks,
Shihao

Attachments:

t254167_1
v1-0002-Add-test-for-jsonb_object_agg-as-a-window-functio.patchapplication/octet-stream; name=v1-0002-Add-test-for-jsonb_object_agg-as-a-window-functio.patchDownload+30-1
v1-0001-Fix-jsonb_object_agg-used-as-a-window-function.patchapplication/octet-stream; name=v1-0001-Fix-jsonb_object_agg-used-as-a-window-function.patchDownload+16-10
#2Tom Lane
tgl@sss.pgh.pa.us
In reply to: shihao zhong (#1)
Re: [PG19] jsonb_object_agg as a window function returns stale values

shihao zhong <zhong950419@gmail.com> writes:

Since b61aa76e458, jsonb_object_agg as a window function can return
an old value for a key.
...
In a window the final function runs once per row. Each run ends the
object on the shared state, which sorts the pairs array and removes
duplicate keys in place. A pair added after that can lose to an older
pair with the same key. The comment there assumes this step can run
many times on the same state, and that does not hold.

Ouch. Clearly I didn't think hard enough about what invariant
uniqueifyJsonbObject() actually maintains.

0001 makes the final function work on a copy of the pairs array.

This patch makes me very sad, because it looks like a big hit
performance-wise. Using this benchmark derived from your example:

\timing on
do $$ begin
perform g, jsonb_object_agg('a', g*2) over (order by g) from generate_series(1,10000) g;
end $$;

On my machine with a non-assert build, HEAD does this in about 12ms,
while the patch makes it take 7200ms. That's partly from the extra
palloc/memcpy overhead, but (I think) mostly from losing the
intermediate de-duplications. Maybe that's an edge case that nobody
will care about, but even without removable duplicates, the extra
palloc/memcpy overhead seems bad.

A smaller fix is to renumber the pairs after the dedup.

Yeah, I independently came to the same thought. That would partially
fix uniqueifyJsonbObject's failure to compose across repeat
applications.

That fixes
the queries above. But the same step drops null pairs from the state,
so this still differs from 18:

Right, and that seems seriously messy to fix.

One alternative could be to use the extra palloc/memcpy only when
skip_nulls is true, after fixing uniqueifyJsonbObject to renumber
the pairs. That at least removes the performance issue from the
simplest case.

Perhaps we could separate out the null-removal step and perform it
only later, but I don't see a simple way to do that.

(Independently of all this, the documentation for the json-object
aggregates is seriously awful. It doesn't explain how duplicate
keys are handled in the non-unique cases, and it leaves the
wrong impression about whether duplicate keys are rejected before
or after dropping nulls.)

regards, tom lane

#3shihao zhong
zhong950419@gmail.com
In reply to: shihao zhong (#1)
Re: [PG19] jsonb_object_agg as a window function returns stale values

Hi Tom,

One alternative could be to use the extra palloc/memcpy only when
skip_nulls is true, after fixing uniqueifyJsonbObject to renumber
the pairs.

v2 does that, with a narrower test for the copy. Removing null pairs
from the state is harmless unless unique_keys is also set, since the
dedup loop skips nulls before it looks for duplicates. So 0001 copies
the pairs only for jsonb_object_agg_unique_strict.

With your benchmark on a non-assert build, HEAD and v2 both take about
10 ms of backend CPU, and v1 takes 5.6 s :( .

(Independently of all this, the documentation for the json-object
aggregates is seriously awful.

0003 is a try at that. It says which value wins for a repeated key,
and that null values are dropped first but still count in the unique
check.

Thanks,
Shihao

Attachments:

t254167_2
v2-0002-Add-tests-for-jsonb_object_agg-as-a-window-functi.patchapplication/octet-stream; name=v2-0002-Add-tests-for-jsonb_object_agg-as-a-window-functi.patchDownload+37-1
v2-0003-Document-duplicate-key-handling-of-the-JSON-objec.patchapplication/octet-stream; name=v2-0003-Document-duplicate-key-handling-of-the-JSON-objec.patchDownload+9-3
v2-0001-Fix-jsonb_object_agg-used-as-a-window-function.patchapplication/octet-stream; name=v2-0001-Fix-jsonb_object_agg-used-as-a-window-function.patchDownload+27-4
#4Melanie Plageman
melanieplageman@gmail.com
In reply to: shihao zhong (#3)
Re: [PG19] jsonb_object_agg as a window function returns stale values

On Wed, Oct 14, 2026 at 12:03 AM shihao zhong <zhong950419@gmail.com> wrote:

One alternative could be to use the extra palloc/memcpy only when
skip_nulls is true, after fixing uniqueifyJsonbObject to renumber
the pairs.

v2 does that, with a narrower test for the copy. Removing null pairs
from the state is harmless unless unique_keys is also set, since the
dedup loop skips nulls before it looks for duplicates. So 0001 copies
the pairs only for jsonb_object_agg_unique_strict.

With your benchmark on a non-assert build, HEAD and v2 both take about
10 ms of backend CPU, and v1 takes 5.6 s :( .

(Independently of all this, the documentation for the json-object
aggregates is seriously awful.

0003 is a try at that. It says which value wins for a repeated key,
and that null values are dropped first but still count in the unique
check.

Should this have a PG 19 open item?

- Melanie

#5Tom Lane
tgl@sss.pgh.pa.us
In reply to: Melanie Plageman (#4)
Re: [PG19] jsonb_object_agg as a window function returns stale values

Melanie Plageman <melanieplageman@gmail.com> writes:

On Wed, Oct 14, 2026 at 12:03 AM shihao zhong <zhong950419@gmail.com> wrote:

0003 is a try at that. It says which value wins for a repeated key,
and that null values are dropped first but still count in the unique
check.

Should this have a PG 19 open item?

If you like, but I plan to resolve it today.

regards, tom lane

#6Tom Lane
tgl@sss.pgh.pa.us
In reply to: shihao zhong (#3)
Re: [PG19] jsonb_object_agg as a window function returns stale values

shihao zhong <zhong950419@gmail.com> writes:

v2 does that, with a narrower test for the copy. Removing null pairs
from the state is harmless unless unique_keys is also set, since the
dedup loop skips nulls before it looks for duplicates. So 0001 copies
the pairs only for jsonb_object_agg_unique_strict.

Right. That's good, because it pretty much resolves my concern about
the cost of repeated de-duplication. There's no win to be had there
for the jsonb_object_agg_unique variants, since they'd throw error
as soon as they see a duplicate key anyway; hence there will never
be anything that could be removed.

@@ -404,6 +404,9 @@
are coerced to text; value arguments are converted as per
<function>to_json</function> or <function>to_jsonb</function>.
Values can be null, but keys cannot.
+        If a key appears more than once, the <type>json</type> result keeps
+        every pair, while the <type>jsonb</type> result keeps only the last
+        value for that key.
</para></entry>
<entry>No</entry>
</row>

Indeed :-(. I kind of wonder why we don't regard that as a bug.
However, I suppose the JSON type doesn't enforce no-duplicate-keys
in the first place, so maybe there's an excuse for it.

Anyway, pushed it all with some minor editorialization. Thanks
again for the report and patch!

regards, tom lane