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 -
https://www.postgresql.org/message-id/flat/57a5a9ef-3436-4dda-8c7e-ec32813e6a84%40uni-muenster.de
From 76129bcdc918a65f471c6d0860b3d59ac9ca50fb Mon Sep 17 00:00:00 2001
From: Jim Jones <[email protected]>
Date: Wed, 25 Nov 2026 11:52:20 +0100
Subject: [PATCH v1] Fix memory growth when mapping arrays to XML

map_sql_value_to_xml_value() converts each array element in the
caller's memory context, so the intermediate data produced for every
element accumulates until the end of the statement.  For large arrays
this can use far more memory than the result itself.  The loop also
does not check for interrupts.

Convert each element in a temporary memory context that is reset after
every iteration, and add CHECK_FOR_INTERRUPTS() to the loop.
---
 src/backend/utils/adt/xml.c | 25 ++++++++++++++++++++++---
 1 file changed, 22 insertions(+), 3 deletions(-)

diff --git a/src/backend/utils/adt/xml.c b/src/backend/utils/adt/xml.c
index 88a2e358a15..839d444146f 100644
--- a/src/backend/utils/adt/xml.c
+++ b/src/backend/utils/adt/xml.c
@@ -99,6 +99,7 @@
 #include "utils/date.h"
 #include "utils/datetime.h"
 #include "utils/lsyscache.h"
+#include "utils/memutils.h"
 #include "utils/rel.h"
 #include "utils/syscache.h"
 #include "utils/xml.h"
@@ -2543,6 +2544,8 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 		Datum	   *elem_values;
 		bool	   *elem_nulls;
 		StringInfoData buf;
+		MemoryContext elemcxt;
+		MemoryContext oldcxt;
 		int			i;
 
 		array = DatumGetArrayTypeP(value);
@@ -2556,17 +2559,33 @@ map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings)
 
 		initStringInfo(&buf);
 
+		/* Free per-element garbage, which can be large, after each element */
+		elemcxt = AllocSetContextCreate(CurrentMemoryContext,
+										"map_sql_value_to_xml_value temporary cxt",
+										ALLOCSET_DEFAULT_SIZES);
+
 		for (i = 0; i < num_elems; i++)
 		{
+			char	   *elemstr;
+
+			CHECK_FOR_INTERRUPTS();
+
 			if (elem_nulls[i])
 				continue;
+
+			oldcxt = MemoryContextSwitchTo(elemcxt);
+			elemstr = map_sql_value_to_xml_value(elem_values[i],
+												 elmtype, true);
+			MemoryContextSwitchTo(oldcxt);
+
 			appendStringInfoString(&buf, "<element>");
-			appendStringInfoString(&buf,
-								   map_sql_value_to_xml_value(elem_values[i],
-															  elmtype, true));
+			appendStringInfoString(&buf, elemstr);
 			appendStringInfoString(&buf, "</element>");
+
+			MemoryContextReset(elemcxt);
 		}
 
+		MemoryContextDelete(elemcxt);
 		pfree(elem_values);
 		pfree(elem_nulls);
 
-- 
2.56.1

Reply via email to