Freeing plan memory - Mailing list pgsql-hackers

From Nigel J. Andrews
Subject Freeing plan memory
Date
Msg-id Pine.LNX.4.21.0210191646260.26324-100000@ponder.fairway2k.co.uk
Whole thread Raw
Responses Re: Freeing plan memory
List pgsql-hackers

I notice there's a leak of memory in SPI_prepare().

The full fix is nontrival and I don't want to submit a half solution so I
thought I'd check whether people think it's worth worrying about.

The leak is that memory is grabbed in SPI_prepare() for a plan within whatever
context is current when it does the palloc(). It may be the caller's or it may
be the relevent SPI one. The plan is then copied out of this memory [and
context] into a child of the procedure's context and forgotten about, or just
plain forgotten. Obviously the intention is that this memory is freed when the
context is deleted and is probably not a problem unless someone does something
like:

i = 100000;
while (i--)
{  plan = SPI_prepare("SELECT 1", 0, (Oid *)NULL);  SPI_freeplan(plan);  /* SPI_freeplan() is not just for
SPI_saveplan()*/
 
}

Is this worth worrying about?

Any busy person can stop reading now as the above defines the problem while the
below only shows an easily reproducable example.

FWIW, I found it while testing something like, which is a little less daft
than the above example:

create function atest1 ( ) returns int as 'a = 0while a < 10000: plan = plpy.prepare("SELECT " + repr(a)) a = a + 1
' language 'plpython';

Here the plpython code uses SPI_freeplan to release the context holding the
plan memory when each plan object returned by plpy.prepare() is garbage
collected. This seems sensibly to happen when the plan variable is
reassigned. However I was baffled why the process still had an obvious memory
leak so looked a little closer at SPI.


-- 
Nigel J. Andrews



pgsql-hackers by date:

Previous
From: Tom Lane
Date:
Subject: Re: /contrib/retep to gborg
Next
From: Tom Lane
Date:
Subject: Re: Postgresql and multithreading