Report planning memory in EXPLAIN ANALYZE

Started by Ashutosh Bapatover 3 years ago43 messageshackers
Jump to latest
#1Ashutosh Bapat
ashutosh.bapat.oss@gmail.com

Attachments:

0001-Report-memory-used-for-planning-a-query-in--20230808.patchtext/x-patch; charset=US-ASCII; name=0001-Report-memory-used-for-planning-a-query-in--20230808.patchDownload+46-9
#2Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Ashutosh Bapat (#1)
Re: Report planning memory in EXPLAIN ANALYZE

Hi David,
Replying to your comments on this thread.

On Tue, Aug 8, 2023 at 11:40 AM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:

Hi All,
I have been looking at memory consumed when planning a partitionwise join [1], [2] and [3]. I am using the attached patch to measure the memory consumption. The patch has been useful to detect an increased memory consumption in other patches e.g. [4] and [5]. The patch looks useful by itself. So I propose this enhancement in EXPLAIN ANALYZE.

On Wed, Aug 9, 2023 at 10:12 AM David Rowley <dgrowleyml@gmail.com> wrote:

I see you're recording the difference in the CurrentMemoryContext of
palloc'd memory before and after planning. That won't really alert us
to problems if the planner briefly allocates, say 12GBs of memory
during, say the join search then quickly pfree's it again. unless
it's an oversized chunk, aset.c won't free() any memory until
MemoryContextReset(). Chunks just go onto a freelist for reuse later.
So at the end of planning, the context may still have that 12GBs
malloc'd, yet your new EXPLAIN ANALYZE property might end up just
reporting a tiny fraction of that.

I wonder if it would be more useful to just have ExplainOneQuery()
create a new memory context and switch to that and just report the
context's mem_allocated at the end.

The memory allocated but not used is still available for use in rest
of the query processing stages. The memory context which is
CurrentMemoryContext at the time of planning is also
CurrentMemoryContext at the time of its execution if it's not
PREPAREd. So it's not exactly "consumed" by memory. But your point is
valid, that it indicates how much was allocated. Just reporting
allocated memory wont' be enough since it might have been allocated
before planning began. How about reporting both used and net allocated
memory? If we use a separate memory context as you suggest, context's
mem_allocated would be net allocated.

It's also slightly annoying that these planner-related summary outputs
are linked to EXPLAIN ANALYZE. We could be showing them in EXPLAIN
without ANALYZE. If we were to change that now, it might be a bit
annoying for the regression tests as we'd need to go and add SUMMARY
OFF in a load of places...

We do report planning time when SUMMARY ON without ANALYZE. Am I
missing something?

#select version();
version
----------------------------------------------------------------------------------------------------------
PostgreSQL 16devel on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu
9.4.0-1ubuntu1~20.04.1) 9.4.0, 64-bit
(1 row)
#explain (summary on) select * from pg_class;
QUERY PLAN
-------------------------------------------------------------
Seq Scan on pg_class (cost=0.00..18.13 rows=413 width=273)
Planning Time: 0.282 ms
(2 rows)
#explain (summary off) select * from pg_class;
QUERY PLAN
-------------------------------------------------------------
Seq Scan on pg_class (cost=0.00..18.13 rows=413 width=273)
(1 row)

I need to just make sure that the Planning Memory is reported with SUMMARY ON.

--
Best Wishes,
Ashutosh Bapat

#3Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Ashutosh Bapat (#2)
Re: Report planning memory in EXPLAIN ANALYZE

On Wed, Aug 9, 2023 at 8:09 PM Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

Hi David,
Replying to your comments on this thread.

On Tue, Aug 8, 2023 at 11:40 AM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:

Hi All,
I have been looking at memory consumed when planning a partitionwise join [1], [2] and [3]. I am using the attached patch to measure the memory consumption. The patch has been useful to detect an increased memory consumption in other patches e.g. [4] and [5]. The patch looks useful by itself. So I propose this enhancement in EXPLAIN ANALYZE.

On Wed, Aug 9, 2023 at 10:12 AM David Rowley <dgrowleyml@gmail.com> wrote:

I see you're recording the difference in the CurrentMemoryContext of
palloc'd memory before and after planning. That won't really alert us
to problems if the planner briefly allocates, say 12GBs of memory
during, say the join search then quickly pfree's it again. unless
it's an oversized chunk, aset.c won't free() any memory until
MemoryContextReset(). Chunks just go onto a freelist for reuse later.
So at the end of planning, the context may still have that 12GBs
malloc'd, yet your new EXPLAIN ANALYZE property might end up just
reporting a tiny fraction of that.

I wonder if it would be more useful to just have ExplainOneQuery()
create a new memory context and switch to that and just report the
context's mem_allocated at the end.

The memory allocated but not used is still available for use in rest
of the query processing stages. The memory context which is
CurrentMemoryContext at the time of planning is also
CurrentMemoryContext at the time of its execution if it's not
PREPAREd. So it's not exactly "consumed" by memory. But your point is
valid, that it indicates how much was allocated. Just reporting
allocated memory wont' be enough since it might have been allocated
before planning began. How about reporting both used and net allocated
memory? If we use a separate memory context as you suggest, context's
mem_allocated would be net allocated.

Thinking more about it, I think memory used is the only right metrics.
It's an optimization in MemoryContext implementation that malloc'ed
memory is not freed when it is returned using pfree().

If we have to report allocated memory, maybe we should report as two
properties Planning Memory used, Planning Memory allocated
respectively. But again the later is an implementation detail which
may not be relevant.

--
Best Wishes,
Ashutosh Bapat

#4David Rowley
dgrowleyml@gmail.com
In reply to: Ashutosh Bapat (#3)
Re: Report planning memory in EXPLAIN ANALYZE

On Thu, 10 Aug 2023 at 03:12, Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

Thinking more about it, I think memory used is the only right metrics.
It's an optimization in MemoryContext implementation that malloc'ed
memory is not freed when it is returned using free().

I guess it depends on the problem you're trying to solve. I had
thought you were trying to do some work to reduce the memory used by
the planner, so I imagined you wanted this so you could track your
progress and also to help ensure we don't make too many mistakes in
the future which makes memory consumption worse again. For that, I
imagined you'd want to know how much memory is held to ransom by the
context with malloc(), not palloc(). Is it really useful to reduce the
palloc'd memory by the end of planning if it does not reduce the
malloc'd memory?

Another way we might go about reducing planner memory is to make
changes to the allocators themselves. For example, aset rounds up to
the next power of 2. If we decided to do something like add more
freelists to double the number so we could add a mid-way point
freelist between each power of 2, then we might find it reduces the
planner memory by, say 12.5%. If we just tracked what was consumed by
palloc() that would appear to save us nothing, but it might actually
save us several malloced blocks.

David

#5Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: David Rowley (#4)
Re: Report planning memory in EXPLAIN ANALYZE

On Wed, Aug 9, 2023 at 8:56 PM David Rowley <dgrowleyml@gmail.com> wrote:

On Thu, 10 Aug 2023 at 03:12, Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

Thinking more about it, I think memory used is the only right metrics.
It's an optimization in MemoryContext implementation that malloc'ed
memory is not freed when it is returned using free().

I guess it depends on the problem you're trying to solve. I had
thought you were trying to do some work to reduce the memory used by
the planner, so I imagined you wanted this so you could track your
progress and also to help ensure we don't make too many mistakes in
the future which makes memory consumption worse again.

Right.

For that, I
imagined you'd want to know how much memory is held to ransom by the
context with malloc(), not palloc(). Is it really useful to reduce the
palloc'd memory by the end of planning if it does not reduce the
malloc'd memory?

AFAIU, the memory freed by the end of planning can be used by later
stages of query processing. The memory malloc'ed during planning can
also be used at the time of execution if it was not palloc'ed or
palloc'ed but pfree'd. So I think it's useful to reduce palloc'ed
memory by the end of planning.

Another way we might go about reducing planner memory is to make
changes to the allocators themselves. For example, aset rounds up to
the next power of 2. If we decided to do something like add more
freelists to double the number so we could add a mid-way point
freelist between each power of 2, then we might find it reduces the
planner memory by, say 12.5%. If we just tracked what was consumed by
palloc() that would appear to save us nothing, but it might actually
save us several malloced blocks.

This won't just affect planner but every subsystem of PostgreSQL, not
just planner, unless we device a new context type for planner.

My point is what's relevant here is how much net memory planner asked
for. Internally how much memory PostgreSQL allocated seems relevant
for the memory context infra as such but not so much for planner
alone.

If you think that memory allocated is important, I will add both used
and (net) allocated memory to EXPLAIN output.

--
Best Wishes,
Ashutosh Bapat

#6Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Ashutosh Bapat (#2)
Re: Report planning memory in EXPLAIN ANALYZE

Hi David,

On Wed, Aug 9, 2023 at 8:09 PM Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

I need to just make sure that the Planning Memory is reported with SUMMARY ON.

The patch reports planning memory in EXPLAIN without ANALYZE when SUMMARY = ON.

#explain (summary on) select * from a, b where a.c1 = b.c1 and a.c1 < b.c2;
QUERY PLAN
-------------------------------------------------------------------------------
Append (cost=55.90..245.70 rows=1360 width=24)
-> Hash Join (cost=55.90..119.45 rows=680 width=24)
Hash Cond: (a_1.c1 = b_1.c1)
Join Filter: (a_1.c1 < b_1.c2)
-> Seq Scan on a_p1 a_1 (cost=0.00..30.40 rows=2040 width=12)
-> Hash (cost=30.40..30.40 rows=2040 width=12)
-> Seq Scan on b_p1 b_1 (cost=0.00..30.40 rows=2040 width=12)
-> Hash Join (cost=55.90..119.45 rows=680 width=24)
Hash Cond: (a_2.c1 = b_2.c1)
Join Filter: (a_2.c1 < b_2.c2)
-> Seq Scan on a_p2 a_2 (cost=0.00..30.40 rows=2040 width=12)
-> Hash (cost=30.40..30.40 rows=2040 width=12)
-> Seq Scan on b_p2 b_2 (cost=0.00..30.40 rows=2040 width=12)
Planning Time: 2.220 ms
Planning Memory: 124816 bytes
(15 rows)

We are good there.

--
Best Wishes,
Ashutosh Bapat

#7Andrei Lepikhov
a.lepikhov@postgrespro.ru
In reply to: Ashutosh Bapat (#5)
Re: Report planning memory in EXPLAIN ANALYZE

On 10/8/2023 15:33, Ashutosh Bapat wrote:

On Wed, Aug 9, 2023 at 8:56 PM David Rowley <dgrowleyml@gmail.com> wrote:

On Thu, 10 Aug 2023 at 03:12, Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:
I guess it depends on the problem you're trying to solve. I had
thought you were trying to do some work to reduce the memory used by
the planner, so I imagined you wanted this so you could track your
progress and also to help ensure we don't make too many mistakes in
the future which makes memory consumption worse again.
Another way we might go about reducing planner memory is to make
changes to the allocators themselves. For example, aset rounds up to
the next power of 2. If we decided to do something like add more
freelists to double the number so we could add a mid-way point
freelist between each power of 2, then we might find it reduces the
planner memory by, say 12.5%. If we just tracked what was consumed by
palloc() that would appear to save us nothing, but it might actually
save us several malloced blocks.

This won't just affect planner but every subsystem of PostgreSQL, not
just planner, unless we device a new context type for planner.

My point is what's relevant here is how much net memory planner asked
for. Internally how much memory PostgreSQL allocated seems relevant
for the memory context infra as such but not so much for planner
alone.

If you think that memory allocated is important, I will add both used
and (net) allocated memory to EXPLAIN output.

As a developer, I like having as much internal info in my EXPLAIN as
possible. But this command is designed mainly for users, not core
developers. The size of memory allocated usually doesn't make sense for
users. On the other hand, developers can watch it easily in different
ways, if needed. So, I vote for the 'memory used' metric only.

The patch looks good, passes the tests.

--
regards,
Andrey Lepikhov
Postgres Professional

#8Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Andrei Lepikhov (#7)
Re: Report planning memory in EXPLAIN ANALYZE

On Fri, Aug 11, 2023 at 10:41 AM Andrey Lepikhov
<a.lepikhov@postgrespro.ru> wrote:

This won't just affect planner but every subsystem of PostgreSQL, not
just planner, unless we device a new context type for planner.

My point is what's relevant here is how much net memory planner asked
for. Internally how much memory PostgreSQL allocated seems relevant
for the memory context infra as such but not so much for planner
alone.

If you think that memory allocated is important, I will add both used
and (net) allocated memory to EXPLAIN output.

As a developer, I like having as much internal info in my EXPLAIN as
possible. But this command is designed mainly for users, not core
developers. The size of memory allocated usually doesn't make sense for
users. On the other hand, developers can watch it easily in different
ways, if needed. So, I vote for the 'memory used' metric only.

The patch looks good, passes the tests.

Thanks Andrey.

David, are you against reporting "memory used"? If you are not against
reporting used memory and still think that memory allocated is worth
reporting, I am fine reporting allocated memory too.

--
Best Wishes,
Ashutosh Bapat

#9David Rowley
dgrowleyml@gmail.com
In reply to: Ashutosh Bapat (#5)
Re: Report planning memory in EXPLAIN ANALYZE

On Thu, 10 Aug 2023 at 20:33, Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

My point is what's relevant here is how much net memory planner asked
for.

But that's not what your patch is reporting. All you're reporting is
the difference in memory that's *currently* palloc'd from before and
after the planner ran. If we palloc'd 600 exabytes then pfree'd it
again, your metric won't change.

I'm struggling a bit to understand your goals here. If your goal is
to make a series of changes that reduces the amount of memory that's
palloc'd at the end of planning, then your patch seems to suit that
goal, but per the quote above, it seems you care about how many bytes
are palloc'd during planning and your patch does not seem track that.

With your patch as it is, to improve the metric you're reporting we
could go off and do things like pfree Paths once createplan.c is done,
but really, why would we do that? Just to make the "Planning Memory"
metric looks better doesn't seem like a worthy goal.

Instead, if we reported the context's mem_allocated, then it would
give us the flexibility to make changes to the memory context code to
have the metric look better. It might also alert us to planner
inefficiencies and problems with new code that may cause a large spike
in the amount of memory that gets allocated. Now, I'm not saying we
should add a patch that shows mem_allocated. I'm just questioning if
your proposed patch meets the goals you're trying to achieve. I just
suggested that you might want to consider something else as a metric
for your memory usage reduction work.

David

#10Andrei Lepikhov
a.lepikhov@postgrespro.ru
In reply to: David Rowley (#9)
Re: Report planning memory in EXPLAIN ANALYZE

On 14/8/2023 06:53, David Rowley wrote:

On Thu, 10 Aug 2023 at 20:33, Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

My point is what's relevant here is how much net memory planner asked
for.

But that's not what your patch is reporting. All you're reporting is
the difference in memory that's *currently* palloc'd from before and
after the planner ran. If we palloc'd 600 exabytes then pfree'd it
again, your metric won't change.

I'm struggling a bit to understand your goals here. If your goal is
to make a series of changes that reduces the amount of memory that's
palloc'd at the end of planning, then your patch seems to suit that
goal, but per the quote above, it seems you care about how many bytes
are palloc'd during planning and your patch does not seem track that.

With your patch as it is, to improve the metric you're reporting we
could go off and do things like pfree Paths once createplan.c is done,
but really, why would we do that? Just to make the "Planning Memory"
metric looks better doesn't seem like a worthy goal.

Instead, if we reported the context's mem_allocated, then it would
give us the flexibility to make changes to the memory context code to
have the metric look better. It might also alert us to planner
inefficiencies and problems with new code that may cause a large spike
in the amount of memory that gets allocated. Now, I'm not saying we
should add a patch that shows mem_allocated. I'm just questioning if
your proposed patch meets the goals you're trying to achieve. I just
suggested that you might want to consider something else as a metric
for your memory usage reduction work.

Really, the current approach with the final value of consumed memory
smooths peaks of memory consumption. I recall examples likewise massive
million-sized arrays or reparameterization with many partitions where
the optimizer consumes much additional memory during planning.
Ideally, to dive into the planner issues, we should have something like
a report-in-progress in the vacuum, reporting on memory consumption at
each subquery and join level. But it looks too much for typical queries.

--
regards,
Andrey Lepikhov
Postgres Professional

#11Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: David Rowley (#9)
Re: Report planning memory in EXPLAIN ANALYZE

On Mon, Aug 14, 2023 at 5:23 AM David Rowley <dgrowleyml@gmail.com> wrote:

On Thu, 10 Aug 2023 at 20:33, Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

My point is what's relevant here is how much net memory planner asked
for.

But that's not what your patch is reporting. All you're reporting is
the difference in memory that's *currently* palloc'd from before and
after the planner ran. If we palloc'd 600 exabytes then pfree'd it
again, your metric won't change.

May be I didn't use the right phrase "asked for". But I expected that
to be read in the context of "net memory" - net as an adjective.
Anyway, I will make it more clear below.

I'm struggling a bit to understand your goals here. If your goal is
to make a series of changes that reduces the amount of memory that's
palloc'd at the end of planning, then your patch seems to suit that
goal, but per the quote above, it seems you care about how many bytes
are palloc'd during planning and your patch does not seem track that.

There are three metrics here. M1: The total number of bytes that the
planner "requests". M2: The total number of bytes that "remain
palloc'ed" at a given point in time. M3: Maximum number of bytes that
were palloc'ed at any point in time during planning. Following
sequence of operations will explain the difference
p1 palloc: 100 - M1 = 100, M2 = 100, M3 = 100
p2 palloc: 100, M1 = 200, M2 = 200, M3 = 200
p3 pfree: 100, M1 = 200, M2 = 100, M3 = 200
p4 palloc: 100, M1 = 300, M2 = 200, M3 = 200
p5 palloc: 100, M1 = 400, M2 = 300, M3 = 300
p6 pfree: 100, M1 = 400, M2 = 200, M3 = 300

The patch reports M2 at the end of planning.
MemoryContextData::mem_allocated is not exactly the same as M3 but
gives indication of M3.

My goal is to reduce all three M1, M2 and M3. I don't it's easy to
track M1 and also worth the complexity. M2 and M3 instead act as rough
indicators of M1.

With your patch as it is, to improve the metric you're reporting we
could go off and do things like pfree Paths once createplan.c is done,
but really, why would we do that? Just to make the "Planning Memory"
metric looks better doesn't seem like a worthy goal.

As I mentioned earlier the CurrentMemoryContext at the time of
planning is also used during query execution. There are other contexts
like per row, per operator contexts but anything which is specific to
the running query and does not fit those contexts is allocated in this
context. If we reduce memory that remains palloc'ed (M2) at the end of
the planning, it can be used during execution. So it looks like a
worthy goal.

Instead, if we reported the context's mem_allocated, then it would
give us the flexibility to make changes to the memory context code to
have the metric look better. It might also alert us to planner
inefficiencies and problems with new code that may cause a large spike
in the amount of memory that gets allocated.

This is M3. I agree with your reasoning here. We should report M3 as
well. I will make changes to the patch.

Now, I'm not saying we
should add a patch that shows mem_allocated. I'm just questioning if
your proposed patch meets the goals you're trying to achieve. I just
suggested that you might want to consider something else as a metric
for your memory usage reduction work.

Ok. Thanks for the suggestions. More suggestions are welcome too.

[1]: https://www.merriam-webster.com/dictionary/net

--
Best Wishes,
Ashutosh Bapat

#12Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Andrei Lepikhov (#10)
Re: Report planning memory in EXPLAIN ANALYZE

On Mon, Aug 14, 2023 at 8:22 AM Andrey Lepikhov
<a.lepikhov@postgrespro.ru> wrote:

Really, the current approach with the final value of consumed memory
smooths peaks of memory consumption. I recall examples likewise massive
million-sized arrays or reparameterization with many partitions where
the optimizer consumes much additional memory during planning.
Ideally, to dive into the planner issues, we should have something like
a report-in-progress in the vacuum, reporting on memory consumption at
each subquery and join level. But it looks too much for typical queries.

Planner finishes usually finish within a second. When partitioning is
involved it might take a few dozens of seconds but it's still within a
minute and we are working to reduce that as well to a couple hundred
milliseconds at max. Tracking memory usages during this small time may
not be worth it. The tracking itself might make the planning
in-efficient and we might still miss the spikes in memory allocations,
if they are very short lived. If the planner runs for more than a few
minutes, maybe we could add some tracking.

--
Best Wishes,
Ashutosh Bapat

#13jian he
jian.universality@gmail.com
In reply to: Ashutosh Bapat (#12)
Re: Report planning memory in EXPLAIN ANALYZE

On Mon, Aug 14, 2023 at 3:13 PM Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:

On Mon, Aug 14, 2023 at 8:22 AM Andrey Lepikhov
<a.lepikhov@postgrespro.ru> wrote:

Really, the current approach with the final value of consumed memory
smooths peaks of memory consumption. I recall examples likewise massive
million-sized arrays or reparameterization with many partitions where
the optimizer consumes much additional memory during planning.
Ideally, to dive into the planner issues, we should have something like
a report-in-progress in the vacuum, reporting on memory consumption at
each subquery and join level. But it looks too much for typical queries.

Planner finishes usually finish within a second. When partitioning is
involved it might take a few dozens of seconds but it's still within a
minute and we are working to reduce that as well to a couple hundred
milliseconds at max. Tracking memory usages during this small time may
not be worth it. The tracking itself might make the planning
in-efficient and we might still miss the spikes in memory allocations,
if they are very short lived. If the planner runs for more than a few
minutes, maybe we could add some tracking.

--
Best Wishes,
Ashutosh Bapat

Hi. I tested it.
not sure if following is desired behavior. first run with explain,
then run with explain(summary on).
the second time, Planning Memory: 0 bytes.

regression=# PREPARE q4 AS SELECT 1 AS a;
explain EXECUTE q4;
QUERY PLAN
------------------------------------------
Result (cost=0.00..0.01 rows=1 width=4)
(1 row)

regression=# explain(summary on) EXECUTE q4;
QUERY PLAN
------------------------------------------
Result (cost=0.00..0.01 rows=1 width=4)
Planning Time: 0.009 ms
Planning Memory: 0 bytes
(3 rows)
---------------------------------------------
previously, if you want stats of a given memory context and its
children, you can only use MemoryContextStatsDetail.
but it will only go to stderr or LOG_SERVER_ONLY.
Now, MemoryContextMemUsed is being exposed. I can do something like:

mem_consumed = MemoryContextMemUsed(CurrentMemoryContext);
//do stuff.
mem_consumed = MemoryContextMemUsed(CurrentMemoryContext) - mem_consumed;

it will give me the NET memory consumed by doing staff in between. Is
my understanding correct?

#14Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: jian he (#13)
Re: Report planning memory in EXPLAIN ANALYZE

Sorry for the late reply. I was working on David's suggestion.

Here's a response to your questions and also a new set of patches.

On Tue, Aug 22, 2023 at 1:16 PM jian he <jian.universality@gmail.com> wrote:

Hi. I tested it.
not sure if following is desired behavior. first run with explain,
then run with explain(summary on).
the second time, Planning Memory: 0 bytes.

regression=# PREPARE q4 AS SELECT 1 AS a;
explain EXECUTE q4;
QUERY PLAN
------------------------------------------
Result (cost=0.00..0.01 rows=1 width=4)
(1 row)

regression=# explain(summary on) EXECUTE q4;
QUERY PLAN
------------------------------------------
Result (cost=0.00..0.01 rows=1 width=4)
Planning Time: 0.009 ms
Planning Memory: 0 bytes
(3 rows)
---------------------------------------------

Yes. This is expected since the plan is already available and no
memory is required to fetch it from the cache. I imagine, if there
were parameters to the prepared plan, it would consume some memory to
evaluate those parameters and some more memory if replanning was
required.

previously, if you want stats of a given memory context and its
children, you can only use MemoryContextStatsDetail.
but it will only go to stderr or LOG_SERVER_ONLY.
Now, MemoryContextMemUsed is being exposed. I can do something like:

mem_consumed = MemoryContextMemUsed(CurrentMemoryContext);
//do stuff.
mem_consumed = MemoryContextMemUsed(CurrentMemoryContext) - mem_consumed;

it will give me the NET memory consumed by doing staff in between. Is
my understanding correct?

Yes.

Here are three patches based on the latest master.

0001
====
this is same as the previous patch with few things fixed. 1. Call
MemoryContextMemUsed() before INSTR_TIME_SET_CURRENT so that the time
taken by MemoryContextMemUsed() is not counted in planning time. 2. In
ExplainOnePlan, use a separate code block for reporting memory.

0002
====
This patch reports both memory allocated and memory used in the
CurrentMemoryContext at the time of planning. It converts "Planning
Memory" into a section with two values reported as "used" and
"allocated" as below

#explain (summary on) select * from pg_class c, pg_type t where
c.reltype = t.oid;
QUERY PLAN
--------------------------------------------------------------------------
Hash Join (cost=28.84..47.08 rows=414 width=533)
... snip ...
Planning Time: 9.274 ms
Planning Memory: used=80848 bytes allocated=90112 bytes
(7 rows)

In JSON format
#explain (summary on, format json) select * from pg_class c, pg_type t
where c.reltype = t.oid;
QUERY PLAN
-----------------------------------------------
[ +
{ +
"Plan": { +
... snip ...
}, +
"Planning Time": 0.466, +
"Planning Memory": { +
"Used": 80608, +
"Allocated": 90112 +
} +
} +
]
(1 row)

PFA explain and explain analyze output in all the formats.

The patch adds MemoryContextMemConsumed() which is similar to
MemoryContextStats() or MemoryContextStatsDetails() except 1. the
later always prints the memory statistics to either stderr or to the
server error log and 2. it doesn't return MemoryContextCounters that
it gathered. We should probably change MemoryContextStats or
MemoryContextStatsDetails() according to those two points and not add
MemoryContextMemConsumed().

I have not merged this into 0001 yet. But once we agree upon whether
this is the right thing to do, I will merge it into 0001.

0003
====
When reporting memory allocated, a confusion may arise as to whether
to report the "net" memory allocated between start and end of planner
OR only the memory that remains allocated after end. This confusion
can be avoided by using an exclusive memory context (child of
CurrentMemoryContext) for planning. That's what 0003 implements as
suggested by David. As mentioned in one of the comments in the patch,
in order to measure memory allocated accurately the new MemoryContext
has to be of the same type as the memory context that will be used
otherwise by the planner i.e. CurrentMemoryContext, and should use the
same parameters. IIUC, it will always be AllocSet. So the patch uses
AllocSet and Asserts so. But in case this changes in future, we will
need a way to create a new memory context with the same properties as
the CurrentMemoryContext, a functionality missing right now. Once we
agree upon the approach, the patch will need to be merged into 0002
and in turn 0001.

--
Best Wishes,
Ashutosh Bapat

Attachments:

explain_planning_memory.outapplication/octet-stream; name=explain_planning_memory.outDownload
0002-Report-memory-allocated-along-with-memory-u-20230824.patchtext/x-patch; charset=US-ASCII; name=0002-Report-memory-allocated-along-with-memory-u-20230824.patchDownload+102-32
0001-Report-memory-used-for-planning-a-query-in--20230824.patchtext/x-patch; charset=US-ASCII; name=0001-Report-memory-used-for-planning-a-query-in--20230824.patchDownload+46-9
0003-Separate-memory-context-for-planner-s-memor-20230824.patchtext/x-patch; charset=US-ASCII; name=0003-Separate-memory-context-for-planner-s-memor-20230824.patchDownload+34-5
#15Andrei Lepikhov
a.lepikhov@postgrespro.ru
In reply to: Ashutosh Bapat (#14)
Re: Report planning memory in EXPLAIN ANALYZE

Using your patch I found out one redundant memory usage in the planner [1]Optimize planner memory consumption for huge arrays /messages/by-id/em9939439a-441a-4b27-a977-ebdf5987dc49@7d14f008.com. It can be interesting as an example of how this patch can detect problems.

[1]: Optimize planner memory consumption for huge arrays /messages/by-id/em9939439a-441a-4b27-a977-ebdf5987dc49@7d14f008.com
/messages/by-id/em9939439a-441a-4b27-a977-ebdf5987dc49@7d14f008.com

--
Regards,
Andrei Lepikhov

Show quoted text

On Thu, Aug 24, 2023, at 5:31 PM, Ashutosh Bapat wrote:

Sorry for the late reply. I was working on David's suggestion.

Here's a response to your questions and also a new set of patches.

On Tue, Aug 22, 2023 at 1:16 PM jian he <jian.universality@gmail.com> wrote:

Hi. I tested it.
not sure if following is desired behavior. first run with explain,
then run with explain(summary on).
the second time, Planning Memory: 0 bytes.

regression=# PREPARE q4 AS SELECT 1 AS a;
explain EXECUTE q4;
QUERY PLAN
------------------------------------------
Result (cost=0.00..0.01 rows=1 width=4)
(1 row)

regression=# explain(summary on) EXECUTE q4;
QUERY PLAN
------------------------------------------
Result (cost=0.00..0.01 rows=1 width=4)
Planning Time: 0.009 ms
Planning Memory: 0 bytes
(3 rows)
---------------------------------------------

Yes. This is expected since the plan is already available and no
memory is required to fetch it from the cache. I imagine, if there
were parameters to the prepared plan, it would consume some memory to
evaluate those parameters and some more memory if replanning was
required.

previously, if you want stats of a given memory context and its
children, you can only use MemoryContextStatsDetail.
but it will only go to stderr or LOG_SERVER_ONLY.
Now, MemoryContextMemUsed is being exposed. I can do something like:

mem_consumed = MemoryContextMemUsed(CurrentMemoryContext);
//do stuff.
mem_consumed = MemoryContextMemUsed(CurrentMemoryContext) - mem_consumed;

it will give me the NET memory consumed by doing staff in between. Is
my understanding correct?

Yes.

Here are three patches based on the latest master.

0001
====
this is same as the previous patch with few things fixed. 1. Call
MemoryContextMemUsed() before INSTR_TIME_SET_CURRENT so that the time
taken by MemoryContextMemUsed() is not counted in planning time. 2. In
ExplainOnePlan, use a separate code block for reporting memory.

0002
====
This patch reports both memory allocated and memory used in the
CurrentMemoryContext at the time of planning. It converts "Planning
Memory" into a section with two values reported as "used" and
"allocated" as below

#explain (summary on) select * from pg_class c, pg_type t where
c.reltype = t.oid;
QUERY PLAN
--------------------------------------------------------------------------
Hash Join (cost=28.84..47.08 rows=414 width=533)
... snip ...
Planning Time: 9.274 ms
Planning Memory: used=80848 bytes allocated=90112 bytes
(7 rows)

In JSON format
#explain (summary on, format json) select * from pg_class c, pg_type t
where c.reltype = t.oid;
QUERY PLAN
-----------------------------------------------
[ +
{ +
"Plan": { +
... snip ...
}, +
"Planning Time": 0.466, +
"Planning Memory": { +
"Used": 80608, +
"Allocated": 90112 +
} +
} +
]
(1 row)

PFA explain and explain analyze output in all the formats.

The patch adds MemoryContextMemConsumed() which is similar to
MemoryContextStats() or MemoryContextStatsDetails() except 1. the
later always prints the memory statistics to either stderr or to the
server error log and 2. it doesn't return MemoryContextCounters that
it gathered. We should probably change MemoryContextStats or
MemoryContextStatsDetails() according to those two points and not add
MemoryContextMemConsumed().

I have not merged this into 0001 yet. But once we agree upon whether
this is the right thing to do, I will merge it into 0001.

0003
====
When reporting memory allocated, a confusion may arise as to whether
to report the "net" memory allocated between start and end of planner
OR only the memory that remains allocated after end. This confusion
can be avoided by using an exclusive memory context (child of
CurrentMemoryContext) for planning. That's what 0003 implements as
suggested by David. As mentioned in one of the comments in the patch,
in order to measure memory allocated accurately the new MemoryContext
has to be of the same type as the memory context that will be used
otherwise by the planner i.e. CurrentMemoryContext, and should use the
same parameters. IIUC, it will always be AllocSet. So the patch uses
AllocSet and Asserts so. But in case this changes in future, we will
need a way to create a new memory context with the same properties as
the CurrentMemoryContext, a functionality missing right now. Once we
agree upon the approach, the patch will need to be merged into 0002
and in turn 0001.

#16Andy Fan
zhihui.fan1213@gmail.com
In reply to: Andrei Lepikhov (#15)
Re: Report planning memory in EXPLAIN ANALYZE

Hi Ashutosh,

Thanks for the patch!

I think the reason why others are not excited about this is because the
benefit is not clear enough to them after the first glance and plus the
chosen wolds "Planning Memory: used " is still confusing for different
people. I admit it is clear to you absolutely, just not for others. Here
are some minor feedback from me:

1). The commit message of patch 1 just says how it does but doesn't
say why it does. After reading through the discussion, I suggest making
it clearer to others.

...
After the planning is done, it may still occupy lots of memory which is
allocated but not pfree-d. All of these memories can't be used in the later
stage. This patch will report such memory usage in order to making some
future mistakes can be found in an easier way.
...

(a description of how it works just like what you have done in the commit
message).

So if the people read the commit message, they can understand where the
function is used for.

2). at the second level, it would be cool that the user can understand the
metric without reading the commit message.

Planning Memory: used=15088 bytes allocated=16384 bytes

Word 'Planning' is kind of a time duration, so the 'used' may be the
'used' during the duration or 'used' after the duration. Obviously you
means the later one but it is not surprising others think it in the other
way. So I'd like to reword the metrics to:

Memory Occupied (Now): Parser: 1k Planner: 10k

'Now' is a cleaner signal that is a time point rather than a time
duration. 'Parser' and 'Planner' also show a timeline about the
important time point. At the same time, it cost very little coding
effort based on patch 01. Different people may have different
feelings about these words, I just hope I describe the goal clearly.

About patch 2 & patch 3, since I didn't find a good usage of it, so I
didn't put much effort on it. interesting probably is not a enough
reason for adding it IMO, since there are too many interesting things.

Personally I am pretty like patch 1, we just need to refactor some words
to make everything clearer.

--
Best Regards
Andy Fan

#17Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Andy Fan (#16)
Re: Report planning memory in EXPLAIN ANALYZE

Hi Andy,
Thanks for your feedback.

On Fri, Sep 22, 2023 at 8:22 AM Andy Fan <zhihui.fan1213@gmail.com> wrote:

1). The commit message of patch 1 just says how it does but doesn't
say why it does. After reading through the discussion, I suggest making
it clearer to others.

...
After the planning is done, it may still occupy lots of memory which is
allocated but not pfree-d. All of these memories can't be used in the later
stage. This patch will report such memory usage in order to making some
future mistakes can be found in an easier way.
...

That's a good summary of how the memory report can be used. Will
include a line about usage in the commit message.

Planning Memory: used=15088 bytes allocated=16384 bytes

Word 'Planning' is kind of a time duration, so the 'used' may be the
'used' during the duration or 'used' after the duration. Obviously you
means the later one but it is not surprising others think it in the other
way. So I'd like to reword the metrics to:

We report "PLanning Time" hence used "Planning memory". Would
"Planner" be good instead of "Planning"?

Memory Occupied (Now): Parser: 1k Planner: 10k

'Now' is a cleaner signal that is a time point rather than a time
duration. 'Parser' and 'Planner' also show a timeline about the
important time point. At the same time, it cost very little coding
effort based on patch 01. Different people may have different
feelings about these words, I just hope I describe the goal clearly.

Parsing happens before planning and that memory is not measured by
this patch. May be separately but it's out of scope of this work.
"used" and "allocated" are MemoryContext terms indicating memory
actually used vs memory allocated.

Personally I am pretty like patch 1, we just need to refactor some words
to make everything clearer.

Thanks.

--
Best Wishes,
Ashutosh Bapat

#18Andy Fan
zhihui.fan1213@gmail.com
In reply to: Ashutosh Bapat (#17)
Re: Report planning memory in EXPLAIN ANALYZE

Hi Ashutosh,

On Fri, Sep 22, 2023 at 5:56 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:

Hi Andy,
Thanks for your feedback.

On Fri, Sep 22, 2023 at 8:22 AM Andy Fan <zhihui.fan1213@gmail.com> wrote:

1). The commit message of patch 1 just says how it does but doesn't
say why it does. After reading through the discussion, I suggest making
it clearer to others.

...
After the planning is done, it may still occupy lots of memory which is
allocated but not pfree-d. All of these memories can't be used in the

later

stage. This patch will report such memory usage in order to making some
future mistakes can be found in an easier way.
...

That's a good summary of how the memory report can be used. Will
include a line about usage in the commit message.

Planning Memory: used=15088 bytes allocated=16384 bytes

Word 'Planning' is kind of a time duration, so the 'used' may be the
'used' during the duration or 'used' after the duration. Obviously you
means the later one but it is not surprising others think it in the other
way. So I'd like to reword the metrics to:

We report "PLanning Time" hence used "Planning memory". Would
"Planner" be good instead of "Planning"?

I agree "Planner" is better than "Planning" personally.

Memory Occupied (Now): Parser: 1k Planner: 10k

'Now' is a cleaner signal that is a time point rather than a time
duration. 'Parser' and 'Planner' also show a timeline about the
important time point. At the same time, it cost very little coding
effort based on patch 01. Different people may have different
feelings about these words, I just hope I describe the goal clearly.

Parsing happens before planning and that memory is not measured by
this patch. May be separately but it's out of scope of this work.
"used" and "allocated" are MemoryContext terms indicating memory
actually used vs memory allocated.

Yes, I understand the terms come from MemoryContext, the complex
thing here is between time duration vs time point case. Since English
is not my native language, so I'm not too confident about insisting on
this.
So I think we can keep it as it is.

Personally I am pretty like patch 1, we just need to refactor some words
to make everything clearer.

Thanks.

David challenged something at the begining, but IIUC he also agree the
value of patch 01 as the previous statement after discussion. Since the
patch
is mild itself, so I will mark this commitfest entry as "Ready for
committer".
Please correct me if anything is wrong.

--
Best Regards
Andy Fan

#19Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Andy Fan (#18)
Re: Report planning memory in EXPLAIN ANALYZE

David challenged something at the begining, but IIUC he also agree the
value of patch 01 as the previous statement after discussion. Since the patch
is mild itself, so I will mark this commitfest entry as "Ready for committer".
Please correct me if anything is wrong.

Thanks Andy.

Here's rebased patches. A conflict in explain.out resolved.

--
Best Wishes,
Ashutosh Bapat

Attachments:

0002-Report-memory-allocated-along-with-memory-u-20231030.patchtext/x-patch; charset=US-ASCII; name=0002-Report-memory-allocated-along-with-memory-u-20231030.patchDownload+103-32
0003-Separate-memory-context-for-planner-s-memor-20231030.patchtext/x-patch; charset=US-ASCII; name=0003-Separate-memory-context-for-planner-s-memor-20231030.patchDownload+34-5
0001-Report-memory-used-for-planning-a-query-in--20231030.patchtext/x-patch; charset=US-ASCII; name=0001-Report-memory-used-for-planning-a-query-in--20231030.patchDownload+46-9
#20Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#19)
Re: Report planning memory in EXPLAIN ANALYZE

I gave this a quick look. I think the usefulness aspect is already
established in general terms; the bit I'm not so sure about is whether
we want it enabled by default. For many cases it'd just be noise.
Perhaps we want it hidden behind something like "EXPLAIN (MEMORY)" or
such, particularly since things like "allocated" (which, per David,
seems to be the really useful metric) seems too much a PG-developer
value rather than an end-user value.

If EXPLAIN (MEMORY) is added, then probably auto_explain needs a
corresponding flag, and doc updates.

Some code looks to be in weird places. Why is calc_mem_usage, which
operates on MemoryContextCounters, in explain.c instead of mcxt.c?
why is MemUsage in explain.h instead of memnodes.h? I moved both. I
also renamed them, to MemoryContextSizeDifference() and MemoryUsage
respectively; fixup patch attached.

I see no reason for this to be three separate patches anymore.

The EXPLAIN docs (explain.sgml) need an update to mention the new flag
and the new output, too.

--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/

Attachments:

review.txttext/plain; charset=utf-8Download+67-61
#21Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Alvaro Herrera (#20)
#22Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#21)
#23Andrei Lepikhov
a.lepikhov@postgrespro.ru
In reply to: Alvaro Herrera (#22)
#24Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Andrei Lepikhov (#23)
#25jian he
jian.universality@gmail.com
In reply to: Ashutosh Bapat (#24)
#26Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: jian he (#25)
#27Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#26)
#28Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Alvaro Herrera (#27)
#29Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Alvaro Herrera (#27)
#30Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#29)
#31Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Alvaro Herrera (#30)
#32Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Ashutosh Bapat (#31)
#33Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#32)
#34Abhijit Menon-Sen
ams@toroid.org
In reply to: Alvaro Herrera (#33)
#35Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Alvaro Herrera (#33)
#36Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Ashutosh Bapat (#35)
#37Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#36)
#38Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Alvaro Herrera (#37)
#39Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#38)
#40Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Alvaro Herrera (#39)
#41Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#40)
#42Ashutosh Bapat
ashutosh.bapat.oss@gmail.com
In reply to: Alvaro Herrera (#41)
#43Alvaro Herrera
alvherre@alvh.no-ip.org
In reply to: Ashutosh Bapat (#42)