pg.ddx.io pgsql-jdbc@postgresql.org mailing list archive
help / color / mirror / Atom feedPrepared statement leak
5+ messages / 3 participants
[nested] [flat]
* Prepared statement leak
@ 2006-04-04 13:38 Peter Eisentraut <peter_e@gmx.net>
2006-04-04 22:33 ` Re: Prepared statement leak Oliver Jowett <oliver@opencloud.com>
2006-04-04 22:35 ` Re: Prepared statement leak Kris Jurka <books@ejurka.com>
0 siblings, 2 replies; 5+ messages in thread
From: Peter Eisentraut @ 2006-04-04 13:38 UTC (permalink / raw)
To: pgsql-jdbc
We seem to have identified a prepared statement leak in the JDBC driver. The
actual application runs through Hibernate, so we have attempted to isolate
the problem here. In the field, the problem causes the PostgreSQL server to
run out of memory in linear time.
We have tested with versions
postgresql-8.0-315.jdbc3.jar
postgresql-8.1-405.jdbc3.jar
postgresql-8.2dev-501.jdbc3.jar
with no difference.
The two prerequisites for this problem to appear are:
1. PreparedStatement objects are rebound with different types, which causes
the JDBC driver to replan the statement.
2. Batches are used.
Attached is a test program that exhibits this. Create a database test with a
table
create table test (a int, b text);
and run the program.
I was initially at a loss about how to debug this problem so I wrote a patch
for the backend to trace the prepared statements table, which turns out to
clearly show the leak. The attached patch is for PostgreSQL 8.0 and writes
the interesting output if log_min_messages is debug1. (There is some extra
memory debugging code in there that I would not advise you to use.)
Running the test program you see this in the server log near the end:
DEBUG: prepared statement hash table size = 100
It should be near 0, of course.
In the JDBC driver log output you see blocks like this:
batch execute 3 queries,
handler=org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler@750159,
maxRows=0, fetchSiz
FE=> Parse(stmt=S_1,query="INSERT INTO test VALUES ($1, $2)",oids={23,1042})
FE=> Bind(stmt=S_1,portal=null,$1=<101>,$2=<test>)
FE=> Describe(portal=null)
FE=> Execute(portal=null,limit=1)
FE=> Parse(stmt=S_2,query="INSERT INTO test VALUES ($1, $2)",oids={23,1043})
FE=> Bind(stmt=S_2,portal=null,$1=<201>,$2=<test>)
FE=> Describe(portal=null)
FE=> Execute(portal=null,limit=1)
FE=> Parse(stmt=S_3,query="INSERT INTO test VALUES ($1, $2)",oids={23,1042})
FE=> Bind(stmt=S_3,portal=null,$1=<301>,$2=<test>)
FE=> Describe(portal=null)
FE=> Execute(portal=null,limit=1)
FE=> Sync
<=BE ParseComplete [S_3]
<=BE BindComplete [null]
<=BE NoData
<=BE CommandStatus(INSERT 20239 1)
<=BE ParseComplete [S_3]
<=BE BindComplete [null]
<=BE NoData
<=BE CommandStatus(INSERT 20240 1)
<=BE ParseComplete [S_3]
<=BE BindComplete [null]
<=BE NoData
<=BE CommandStatus(INSERT 20241 1)
<=BE ReadyForQuery(I)
Notice that it seems to forget out S_1 and S_2 along the way.
--
Peter Eisentraut
http://developer.postgresql.org/~petere/
Attachments:
Test.java (text/x-java, 834B) download
import java.sql.*;
class Test {
public static void main(String[] args) throws Exception {
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:6543/test?loglevel=2", "pei", "");
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO test VALUES (?, ?);");
for (int i = 0; i < 100; i++) {
pstmt.setInt(1, 100 + i);
pstmt.setObject(2, "test", Types.CHAR);
pstmt.addBatch();
pstmt.setInt(1, 200 + i);
pstmt.setObject(2, "test", Types.VARCHAR);
pstmt.addBatch();
pstmt.setInt(1, 300 + i);
pstmt.setObject(2, "test", Types.CHAR);
pstmt.addBatch();
pstmt.executeBatch();
pstmt.clearBatch();
}
pstmt.close();
pstmt = conn.prepareStatement("SELECT * FROM test;");
pstmt.execute();
pstmt.close();
conn.close();
}
}
prepstmt-debug.patch (text/x-diff, 2.4K) download
diff -ur ../cvs-pgsql/src/backend/commands/prepare.c ./src/backend/commands/prepare.c
--- ../cvs-pgsql/src/backend/commands/prepare.c 2006-01-14 17:09:45.000000000 +0100
+++ ./src/backend/commands/prepare.c 2006-03-31 22:41:45.000000000 +0200
@@ -357,6 +357,9 @@
entry->context = entrycxt;
MemoryContextSwitchTo(oldcxt);
+
+ elog(DEBUG1, "StorePreparedStatement(%s, %s, ...)", stmt_name, query_string);
+ elog(DEBUG1, "prepared statement hash table size = %ld", prepared_queries->hctl->nentries);
}
/*
@@ -500,6 +503,9 @@
/* Now we can remove the hash table entry */
hash_search(prepared_queries, entry->stmt_name, HASH_REMOVE, NULL);
}
+
+ elog(DEBUG1, "DropPreparedStatement(%s)", stmt_name);
+ elog(DEBUG1, "prepared statement hash table size = %ld", prepared_queries->hctl->nentries);
}
/*
diff -ur ../cvs-pgsql/src/backend/tcop/postgres.c ./src/backend/tcop/postgres.c
--- ../cvs-pgsql/src/backend/tcop/postgres.c 2006-01-14 17:09:48.000000000 +0100
+++ ./src/backend/tcop/postgres.c 2006-03-31 23:18:35.000000000 +0200
@@ -1162,6 +1162,8 @@
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
+
+ elog(DEBUG1, "unnamed prepared statement setup");
}
QueryContext = CurrentMemoryContext;
diff -ur ../cvs-pgsql/src/backend/utils/mmgr/mcxt.c ./src/backend/utils/mmgr/mcxt.c
--- ../cvs-pgsql/src/backend/utils/mmgr/mcxt.c 2005-01-04 20:40:57.000000000 +0100
+++ ./src/backend/utils/mmgr/mcxt.c 2006-04-01 13:11:16.000000000 +0200
@@ -23,6 +23,28 @@
#include "nodes/memnodes.h"
#include "utils/memutils.h"
+#include "utils/guc.h"
+
+#include <execinfo.h>
+
+
+/* Obtain a backtrace and print it to stderr. */
+static void
+print_trace(void)
+{
+ void *array[10];
+ size_t size;
+ char **strings;
+ size_t i;
+
+ size = backtrace(array, 10);
+ strings = backtrace_symbols(array, size);
+
+ for (i = 0; i < size; i++)
+ fprintf (stderr, "BT(%d): %s\n", i, strings[i]);
+
+ free (strings);
+}
/*****************************************************************************
@@ -502,6 +524,13 @@
elog(ERROR, "invalid memory alloc request size %lu",
(unsigned long) size);
+ if (log_min_messages <= DEBUG2)
+ {
+ fprintf(stderr, "MemoryContextAlloc(%s, %u)\n", context->name, size);
+ print_trace();
+ MemoryContextStats(TopMemoryContext);
+ }
+
return (*context->methods->alloc) (context, size);
}
^ permalink raw reply [nested|flat] 5+ messages in thread
* Re: Prepared statement leak
2006-04-04 13:38 Prepared statement leak Peter Eisentraut <peter_e@gmx.net>
@ 2006-04-04 22:33 ` Oliver Jowett <oliver@opencloud.com>
1 sibling, 0 replies; 5+ messages in thread
From: Oliver Jowett @ 2006-04-04 22:33 UTC (permalink / raw)
To: Peter Eisentraut <peter_e@gmx.net>; +Cc: pgsql-jdbc
Peter Eisentraut wrote:
> We seem to have identified a prepared statement leak in the JDBC driver. The
> actual application runs through Hibernate, so we have attempted to isolate
> the problem here. In the field, the problem causes the PostgreSQL server to
> run out of memory in linear time.
If you force a full GC on the Java side (i.e. call System.gc()), does
the driver clean up those leaked statements on the next query? In
theory, if the driver leaks references to a server-side prepared
statement it should reclaim the server statements when weak references
next get collected, which may take some time if the Java side is not
generating much garbage (weak references only get collected on a full
GC). Obviously we don't want to leak them in the first place, but I put
that mechanism in place in case we did.
-O
^ permalink raw reply [nested|flat] 5+ messages in thread
* Re: Prepared statement leak
2006-04-04 13:38 Prepared statement leak Peter Eisentraut <peter_e@gmx.net>
@ 2006-04-04 22:35 ` Kris Jurka <books@ejurka.com>
2006-04-10 09:35 ` Re: Prepared statement leak Peter Eisentraut <peter_e@gmx.net>
2006-04-26 20:25 ` Re: Prepared statement leak Kris Jurka <books@ejurka.com>
1 sibling, 2 replies; 5+ messages in thread
From: Kris Jurka @ 2006-04-04 22:35 UTC (permalink / raw)
To: Peter Eisentraut <peter_e@gmx.net>; +Cc: pgsql-jdbc; oliver@opencloud.com
On Tue, 4 Apr 2006, Peter Eisentraut wrote:
> We seem to have identified a prepared statement leak in the JDBC driver. The
> actual application runs through Hibernate, so we have attempted to isolate
> the problem here. In the field, the problem causes the PostgreSQL server to
> run out of memory in linear time.
>
> The two prerequisites for this problem to appear are:
>
> 1. PreparedStatement objects are rebound with different types, which causes
> the JDBC driver to replan the statement.
>
> 2. Batches are used.
>
To cleanup prepared statements the driver records a reference to a query
object in response to the ParseComplete message. The problem in this case
was that since the driver sends multiple Parse messages before a Sync,
when the driver receives the first ParseComplete message the query object
now contains a reference to the latest parsed statement, not the first.
So it was only cleaning up the last parsed statement not all of them.
I believe the attached patch fixes this, but I'd like Oliver to take a
look at it. I've made included the original statement name in the list of
things available to the ParseComplete receiver so it can record the
correct original statement to be destroyed.
An ideal driver would keep only two prepared plans around, one for each
set of parameter types, but that's more complicated and for a rather
unusual situation.
Kris Jurka
Attachments:
batch-replan.patch (text/plain, 4.9K) download
? org/postgresql/core/v3/.QueryExecutorImpl.java.swp
? org/postgresql/core/v3/.SimpleQuery.java.swp
Index: org/postgresql/core/v3/QueryExecutorImpl.java
===================================================================
RCS file: /usr/local/cvsroot/pgjdbc/pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java,v
retrieving revision 1.27
diff -c -r1.27 QueryExecutorImpl.java
*** org/postgresql/core/v3/QueryExecutorImpl.java 30 Jan 2006 20:12:06 -0000 1.27
--- org/postgresql/core/v3/QueryExecutorImpl.java 4 Apr 2006 22:34:10 -0000
***************
*** 682,687 ****
--- 682,688 ----
// Clean up any existing statement, as we can't use it.
query.unprepare();
+ processDeadParsedQueries();
String statementName = null;
if (!oneShot)
***************
*** 768,774 ****
for (int i = 1; i <= params.getParameterCount(); ++i)
pgStream.SendInteger4(params.getTypeOID(i));
! pendingParseQueue.add(query);
}
private void sendBind(SimpleQuery query, SimpleParameterList params, Portal portal) throws IOException {
--- 769,775 ----
for (int i = 1; i <= params.getParameterCount(); ++i)
pgStream.SendInteger4(params.getTypeOID(i));
! pendingParseQueue.add(new Object[]{query, query.getStatementName()});
}
private void sendBind(SimpleQuery query, SimpleParameterList params, Portal portal) throws IOException {
***************
*** 1085,1092 ****
private final HashMap parsedQueryMap = new HashMap();
private final ReferenceQueue parsedQueryCleanupQueue = new ReferenceQueue();
! private void registerParsedQuery(SimpleQuery query) {
! String statementName = query.getStatementName();
if (statementName == null)
return ;
--- 1086,1092 ----
private final HashMap parsedQueryMap = new HashMap();
private final ReferenceQueue parsedQueryCleanupQueue = new ReferenceQueue();
! private void registerParsedQuery(SimpleQuery query, String statementName) {
if (statementName == null)
return ;
***************
*** 1171,1181 ****
case '1': // Parse Complete (response to Parse)
pgStream.ReceiveIntegerR(4); // len, discarded
! SimpleQuery parsedQuery = (SimpleQuery)pendingParseQueue.get(parseIndex++);
if (logger.logDebug())
! logger.debug(" <=BE ParseComplete [" + parsedQuery.getStatementName() + "]");
! registerParsedQuery(parsedQuery);
break;
case 't': // ParameterDescription
--- 1171,1185 ----
case '1': // Parse Complete (response to Parse)
pgStream.ReceiveIntegerR(4); // len, discarded
! Object[] parsedQueryAndStatement = (Object[])pendingParseQueue.get(parseIndex++);
!
! SimpleQuery parsedQuery = (SimpleQuery)parsedQueryAndStatement[0];
! String parsedStatementName = (String)parsedQueryAndStatement[1];
!
if (logger.logDebug())
! logger.debug(" <=BE ParseComplete [" + parsedStatementName + "]");
! registerParsedQuery(parsedQuery, parsedStatementName);
break;
case 't': // ParameterDescription
***************
*** 1368,1374 ****
// Reset the statement name of Parses that failed.
while (parseIndex < pendingParseQueue.size())
{
! SimpleQuery failedQuery = (SimpleQuery)pendingParseQueue.get(parseIndex++);
failedQuery.unprepare();
}
--- 1372,1379 ----
// Reset the statement name of Parses that failed.
while (parseIndex < pendingParseQueue.size())
{
! Object[] failedQueryAndStatement = (Object[])pendingParseQueue.get(parseIndex++);
! SimpleQuery failedQuery = (SimpleQuery)failedQueryAndStatement[0];
failedQuery.unprepare();
}
Index: org/postgresql/core/v3/SimpleQuery.java
===================================================================
RCS file: /usr/local/cvsroot/pgjdbc/pgjdbc/org/postgresql/core/v3/SimpleQuery.java,v
retrieving revision 1.9
diff -c -r1.9 SimpleQuery.java
*** org/postgresql/core/v3/SimpleQuery.java 4 Jul 2005 18:50:29 -0000 1.9
--- org/postgresql/core/v3/SimpleQuery.java 4 Apr 2006 22:34:10 -0000
***************
*** 102,107 ****
--- 102,111 ----
}
void setCleanupRef(PhantomReference cleanupRef) {
+ if (this.cleanupRef != null) {
+ this.cleanupRef.clear();
+ this.cleanupRef.enqueue();
+ }
this.cleanupRef = cleanupRef;
}
^ permalink raw reply [nested|flat] 5+ messages in thread
* Re: Prepared statement leak
2006-04-04 13:38 Prepared statement leak Peter Eisentraut <peter_e@gmx.net>
2006-04-04 22:35 ` Re: Prepared statement leak Kris Jurka <books@ejurka.com>
@ 2006-04-10 09:35 ` Peter Eisentraut <peter_e@gmx.net>
1 sibling, 0 replies; 5+ messages in thread
From: Peter Eisentraut @ 2006-04-10 09:35 UTC (permalink / raw)
To: Kris Jurka <books@ejurka.com>; +Cc: pgsql-jdbc; oliver@opencloud.com
Am Mittwoch, 5. April 2006 00:35 schrieb Kris Jurka:
> I believe the attached patch fixes this, but I'd like Oliver to take a
> look at it. I've made included the original statement name in the list of
> things available to the ParseComplete receiver so it can record the
> correct original statement to be destroyed.
Your patch fixes my test case.
--
Peter Eisentraut
http://developer.postgresql.org/~petere/
^ permalink raw reply [nested|flat] 5+ messages in thread
* Re: Prepared statement leak
2006-04-04 13:38 Prepared statement leak Peter Eisentraut <peter_e@gmx.net>
2006-04-04 22:35 ` Re: Prepared statement leak Kris Jurka <books@ejurka.com>
@ 2006-04-26 20:25 ` Kris Jurka <books@ejurka.com>
1 sibling, 0 replies; 5+ messages in thread
From: Kris Jurka @ 2006-04-26 20:25 UTC (permalink / raw)
To: Peter Eisentraut <peter_e@gmx.net>; +Cc: pgsql-jdbc; oliver@opencloud.com
On Tue, 4 Apr 2006, Kris Jurka wrote:
> On Tue, 4 Apr 2006, Peter Eisentraut wrote:
>
>> We seem to have identified a prepared statement leak in the JDBC driver.
>
> I believe the attached patch fixes this, but I'd like Oliver to take a look
> at it. I've made included the original statement name in the list of things
> available to the ParseComplete receiver so it can record the correct original
> statement to be destroyed.
>
I've applied this patch to 8.0, 8.1, and head cvs branches and will try to
put out a new release this week.
Kris Jurka
^ permalink raw reply [nested|flat] 5+ messages in thread
end of thread, other threads:[~2006-04-26 20:25 UTC | newest]
Thread overview: 5+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2006-04-04 13:38 Prepared statement leak Peter Eisentraut <peter_e@gmx.net>
2006-04-04 22:33 ` Oliver Jowett <oliver@opencloud.com>
2006-04-04 22:35 ` Kris Jurka <books@ejurka.com>
2006-04-10 09:35 ` Peter Eisentraut <peter_e@gmx.net>
2006-04-26 20:25 ` Kris Jurka <books@ejurka.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox