OOM kill in xmlelement() with large arrays

Started by Jim Jones4 days ago10 messageshackers

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1Jim Jones
jim.jones@uni-muenster.de

Hi

While answering a review in [1] I noticed that xmlelement() accumulates
the intermediate data produced for every array element until the end of
the statement. For large arrays this can quickly exhaust the server's
memory, and the loop does not check for interrupts, so it cannot be
cancelled while memory grows..

== PG19 =

psql (19.0 (Debian 19.0-2.pgdg13+1))
Type "help" for help.

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[56000000]))::text);
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
!?>
\q

$ journalctl -k --since -1min | grep -i 'out of memory'
kernel: Out of memory: Killed process 350541 (postgres)
total-vm:57378464kB, anon-rss:55284684kB, file-rss:12kB,
shmem-rss:4044kB, UID:525286 pgtables:111956kB oom_score_adj:200

v1 patch converts each element in a temporary memory context
that is reset after every itertion, and adds CHECK_FOR_INTERRUPTS()
to the loop.

== patched ==

psql (20devel)
Type "help" for help.

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[56000000]))::text);
length
------------
1064000007
(1 row)

Thoughts?

Best, Jim

1 -
/messages/by-id/57a5a9ef-3436-4dda-8c7e-ec32813e6a84@uni-muenster.de

Attachments:

t259786_1
v1-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchtext/x-patch; charset=UTF-8; name=v1-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchDownload+22-4
#2Jim Jones
jim.jones@uni-muenster.de
In reply to: Jim Jones (#1)
Re: OOM kill in xmlelement() with large arrays

On 25/11/2026 12:50, Jim Jones wrote:

psql (19.0 (Debian 19.0-2.pgdg13+1))
Type "help" for help.

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[56000000]))::text);
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
!?>
\q

BTW the *_to_xml functions seem to share the same issue:

psql (19.0 (Debian 19.0-2.pgdg13+1))
Type "help" for help.

postgres=# select length(query_to_xml('SELECT g,g,g,g,g,g FROM
generate_series(1, 10000000) g', false, false, '')::text);
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
!?>

I'll take a look at them once we agree on the approach.

Best, Jim

#3Jakub Wartak
jakub.wartak@enterprisedb.com
In reply to: Jim Jones (#1)
Re: OOM kill in xmlelement() with large arrays

On Wed, Nov 25, 2026 at 12:50 PM Jim Jones <jim.jones@uni-muenster.de> wrote:

Hi

While answering a review in [1] I noticed that xmlelement() accumulates
the intermediate data produced for every array element until the end of
the statement. For large arrays this can quickly exhaust the server's
memory, and the loop does not check for interrupts, so it cannot be
cancelled while memory grows..

== PG19 =

psql (19.0 (Debian 19.0-2.pgdg13+1))
Type "help" for help.

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[56000000]))::text);
server closed the connection unexpectedly

Oh my! Reproduced, this oneliner almost crashed my 32GB laptop:
Out of memory: Killed process 66563 (postgres) total-vm:29998880kB,
anon-rss:22659436kB[..]
(yeah, that's literally 22-29GB)

+1 to fixing this. Patch LGMT, maybe just two tiny things:

- perhaps move MemoryContext oldcxt to the loop
- "map_sql_value_to_xml_value temporary cxt" is a bit lengthy blob, maybe
"elements of XML array" would suffice there (or maybe check further wihtin
pg_backend_memory_contexts for better examples)

---

Not related to the thread: I wish we had a way to limit backend total RSS
somehow. I've lost count on how many occassions we hit such issues without
any safety net. Not that the patch fixes it, but it can still DoS the thing.
Andres told me that setrlimit(RLIMIT_DATA) SIGSEGVs in case of hitting the
limit when growing stack and not just overallocating memory (if I recall
correctly). I've tried to simulate such stuff, but it always worked properly
for me...

-J.

#4Daniel Gustafsson
daniel@yesql.se
In reply to: Jakub Wartak (#3)
Re: OOM kill in xmlelement() with large arrays

On 25 Nov 2026, at 14:01, Jakub Wartak <jakub.wartak@enterprisedb.com> wrote:

+1 to fixing this. Patch LGMT, maybe just two tiny things:

- perhaps move MemoryContext oldcxt to the loop
- "map_sql_value_to_xml_value temporary cxt" is a bit lengthy blob, maybe
"elements of XML array" would suffice there (or maybe check further wihtin
pg_backend_memory_contexts for better examples)

+1. Patch looks good on a first glance, expanding to the *_to_xml cases seems
like a good idea.

--
Daniel Gustafsson

#5Jim Jones
jim.jones@uni-muenster.de
In reply to: Daniel Gustafsson (#4)
Re: OOM kill in xmlelement() with large arrays

Hi Jakub & Daniel

Thanks for the reviews.

On 25/11/2026 14:12, Daniel Gustafsson wrote:

On 25 Nov 2026, at 14:01, Jakub Wartak <jakub.wartak@enterprisedb.com> wrote:
+1 to fixing this. Patch LGMT, maybe just two tiny things:

- perhaps move MemoryContext oldcxt to the loop

Done in v2-0001.

- "map_sql_value_to_xml_value temporary cxt" is a bit lengthy blob, maybe
"elements of XML array" would suffice there (or maybe check further wihtin
pg_backend_memory_contexts for better examples)

I kept the context label like this for now. My rationale is that it
makes it a bit easier to identify the context without looking into the
code.. let me know if there is a standard here.

+1. Patch looks good on a first glance, expanding to the *_to_xml cases seems
like a good idea.

Thanks.

0002 attached applies the same approach to the *to_xml functions.

== patched ==

psql (20devel)
Type "help" for help.

postgres=# select length(query_to_xml('SELECT g,g,g,g,g FROM
generate_series(1, 10000000) g', false, false, '')::text);
length
-----------
984444557
(1 row)

postgres=# create table t as select g a, g b, g c, g d, g e FROM
generate_series(1, 10000000) g;
SELECT 10000000
postgres=# SELECT length(table_to_xml('t', false, false, '')::text);
length
-----------
984444549
(1 row)

Best, Jim

Attachments:

t259786_5
v2-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchtext/x-patch; charset=UTF-8; name=v2-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchDownload+22-4
v2-0002-Fix-memory-growth-in-the-_to_xml-functions.patchtext/x-patch; charset=UTF-8; name=v2-0002-Fix-memory-growth-in-the-_to_xml-functions.patchDownload+35-1
#6Tom Lane
tgl@sss.pgh.pa.us
In reply to: Jim Jones (#5)
Re: OOM kill in xmlelement() with large arrays

Jim Jones <jim.jones@uni-muenster.de> writes:

Done in v2-0001.

I wonder whether this would be a net negative for many use-cases.
Creating and dropping a memory context is hardly free. Have you
done any performance measurements on cases that don't eat enough
memory to be OOM hazards?

One idea for limiting the damage if that does seem to be an issue
is to use a temporary context only when the VARSIZE of the input
array exceeds, say, 10kB. (I'm thinking that the VARSIZE would
be a good guide to the amount of memory we're going to use
because it tells something about the size of the array elements
as well as their number.)

A side point is that I think you don't need to switch in and out
of the temp context each time through the loop. Once the StringInfo
buffer is created it'll repalloc itself bigger in its original
context, and there's nothing saying you can't reset the current
context. This probably wouldn't be worth worrying about in itself,
but it might make it less messy to implement the first idea.

regards, tom lane

#7Tom Lane
tgl@sss.pgh.pa.us
In reply to: Tom Lane (#6)
Re: OOM kill in xmlelement() with large arrays

I wrote:

I wonder whether this would be a net negative for many use-cases.
Creating and dropping a memory context is hardly free. Have you
done any performance measurements on cases that don't eat enough
memory to be OOM hazards?

I did this simple test:

\timing on
do $$
declare arr text[] default array_fill(''::text, ARRAY[50]);
begin
for i in 1..1000000 loop
perform xmlelement(name a, arr);
end loop;
end$$;

With HEAD this takes about 6400ms for me, with the patch
about 6700ms. (These numbers are in an assert-enabled
build, so take them with a grain of salt.) That seems
like it's not really enough of a hit to justify contorting
the code, so consider this objection withdrawn.

Another thing I noticed is that we are doing the type-output
function lookup over again for each array element, though
with some refactoring we could do it just once. Since that
lookup is skipped for "bool" elements, I compared

regression=# select length(xmlelement(name a, array_fill(true,
ARRAY[16000000]))::text);
length
-----------
368000007
(1 row)

Time: 1196.610 ms (00:01.197)
regression=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
length
-----------
304000007
(1 row)

Time: 2005.366 ms (00:02.005)

Now the time taken by textout is not zero, but it still looks like
close to 50% of the runtime is going into those repeat lookups.
Maybe that's enough to worry about?

regards, tom lane

#8Kirill Reshke
reshkekirill@gmail.com
In reply to: Tom Lane (#7)
Re: OOM kill in xmlelement() with large arrays

On Wed, 25 Nov 2026 at 22:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:

I wrote:

I wonder whether this would be a net negative for many use-cases.
Creating and dropping a memory context is hardly free. Have you
done any performance measurements on cases that don't eat enough
memory to be OOM hazards?

I did this simple test:

\timing on
do $$
declare arr text[] default array_fill(''::text, ARRAY[50]);
begin
for i in 1..1000000 loop
perform xmlelement(name a, arr);
end loop;
end$$;

With HEAD this takes about 6400ms for me, with the patch
about 6700ms. (These numbers are in an assert-enabled
build, so take them with a grain of salt.) That seems
like it's not really enough of a hit to justify contorting
the code, so consider this objection withdrawn.

Another thing I noticed is that we are doing the type-output
function lookup over again for each array element, though
with some refactoring we could do it just once. Since that
lookup is skipped for "bool" elements, I compared

regression=# select length(xmlelement(name a, array_fill(true,
ARRAY[16000000]))::text);
length
-----------
368000007
(1 row)

Time: 1196.610 ms (00:01.197)
regression=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
length
-----------
304000007
(1 row)

Time: 2005.366 ms (00:02.005)

Now the time taken by textout is not zero, but it still looks like
close to 50% of the runtime is going into those repeat lookups.
Maybe that's enough to worry about?

regards, tom lane

From my testing, it also turns out impact is measurable.
I used the following setup:

CREATE TEMP TABLE xml_perf (v integer[]);
INSERT INTO xml_perf
SELECT ARRAY(SELECT g FROM generate_series(1, 8192) AS g);
ANALYZE xml_perf;

query:
SELECT xmlelement(name r, v)
FROM xml_perf CROSS JOIN generate_series(1, 182);

results, 15 runs:

median min max
master 150.19 148.69 153.77
+ v2-0001 223.98 221.27 226.66

--
Best regards,
Kirill Reshke

#9Jim Jones
jim.jones@uni-muenster.de
In reply to: Kirill Reshke (#8)
Re: OOM kill in xmlelement() with large arrays

On 25/11/2026 16:30, Tom Lane wrote:

A side point is that I think you don't need to switch in and out
of the temp context each time through the loop. Once the StringInfo
buffer is created it'll repalloc itself bigger in its original
context, and there's nothing saying you can't reset the current
context. This probably wouldn't be worth worrying about in itself,
but it might make it less messy to implement the first idea.

Makes total sense.. thank you for clarifying! Done that way in 0001 and
0002.

On Wed, 25 Nov 2026 at 22:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:

I did this simple test:

\timing on
do $$
declare arr text[] default array_fill(''::text, ARRAY[50]);
begin
for i in 1..1000000 loop
perform xmlelement(name a, arr);
end loop;
end$$;

With HEAD this takes about 6400ms for me, with the patch
about 6700ms. (These numbers are in an assert-enabled
build, so take them with a grain of salt.) That seems
like it's not really enough of a hit to justify contorting
the code, so consider this objection withdrawn.

I tested this query with v3-0001 in a -O2 build without --enable-cassert
and I see no slowdown:

master: n=19 min=6150.3 ms max=6617.7 ms avg=6254.1 ms
patched: n=19 min=6073.2 ms max=6188.7 ms avg=6117.0 ms

Another thing I noticed is that we are doing the type-output
function lookup over again for each array element, though
with some refactoring we could do it just once. Since that
lookup is skipped for "bool" elements, I compared

regression=# select length(xmlelement(name a, array_fill(true,
ARRAY[16000000]))::text);
length
-----------
368000007
(1 row)

Time: 1196.610 ms (00:01.197)
regression=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
length
-----------
304000007
(1 row)

Time: 2005.366 ms (00:02.005)

Now the time taken by textout is not zero, but it still looks like
close to 50% of the runtime is going into those repeat lookups.
Maybe that's enough to worry about?

+1
I will take a look at this today or tomorrow and post a separate 0003 patch.

On 25/11/2026 18:58, Kirill Reshke wrote:

From my testing, it also turns out impact is measurable.

I used the following setup:

CREATE TEMP TABLE xml_perf (v integer[]);
INSERT INTO xml_perf
SELECT ARRAY(SELECT g FROM generate_series(1, 8192) AS g);
ANALYZE xml_perf;

query:
SELECT xmlelement(name r, v)
FROM xml_perf CROSS JOIN generate_series(1, 182);

results, 15 runs:

median min max
master 150.19 148.69 153.77
+ v2-0001 223.98 221.27 226.66

I was unable to reproduce these results with v3-0001 (now containing
Tom's suggestions). I tried your query and got these results:

master: n=19 min=155.6 ms max=161.9 ms avg=158.8 ms
patched: n=19 min=152.9 ms max=162.1 ms avg=156.9 ms

Also with -O2 and without --enable-assert. Can you share how your server
was built?

Thanks!

Best, Jim

Attachments:

t259786_9
v3-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchtext/x-patch; charset=UTF-8; name=v3-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchDownload+15-1
v3-0002-Fix-memory-growth-in-the-_to_xml-functions.patchtext/x-patch; charset=UTF-8; name=v3-0002-Fix-memory-growth-in-the-_to_xml-functions.patchDownload+33-1
#10Jim Jones
jim.jones@uni-muenster.de
In reply to: Jim Jones (#9)
Re: OOM kill in xmlelement() with large arrays

On 26/11/2026 10:28, Jim Jones wrote:

On Wed, 25 Nov 2026 at 22:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:

Another thing I noticed is that we are doing the type-output
function lookup over again for each array element, though
with some refactoring we could do it just once. Since that
lookup is skipped for "bool" elements, I compared

+1
I will take a look at this today or tomorrow and post a separate 0003 patch.

I spent some time with this today. 0003 now moves the body of
map_sql_value_to_xml_value() into map_sql_value_to_xml_value_internal(),
which does the elemnt type lookups once per array and passes the results
down to the conversion of each element -- I added some small regression
tests for that.

here some tests:

(-O2 build without assertions)

== master ==

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
length
-----------
304000007
(1 row)

Time: 6029,250 ms (00:06,029)

== patched (0001, 0002) ==

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
length
-----------
304000007
(1 row)

Time: 2247,771 ms (00:02,248)

== patched (0001, 0002, 0003)==

postgres=# select length(xmlelement(name a, array_fill(''::text,
ARRAY[16000000]))::text);
length
-----------
304000007
(1 row)

Time: 1464,118 ms (00:01,464)

0001 and 0002 remain unchanged.

Best, Jim

Attachments:

t259786_10
v4-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchtext/x-patch; charset=UTF-8; name=v4-0001-Fix-memory-growth-when-mapping-arrays-to-XML.patchDownload+15-1
v4-0002-Fix-memory-growth-in-the-_to_xml-functions.patchtext/x-patch; charset=UTF-8; name=v4-0002-Fix-memory-growth-in-the-_to_xml-functions.patchDownload+33-1
v4-0003-Look-up-element-type-information-once-when-mappin.patchtext/x-patch; charset=UTF-8; name=v4-0003-Look-up-element-type-information-once-when-mappin.patchDownload+76-8