From 39e4bb039900c270b42475648c8bb0ae64a3f14c Mon Sep 17 00:00:00 2001
From: Melih Mutlu <m.melihmutlu@gmail.com>
Date: Mon, 1 Jul 2024 16:06:03 +0300
Subject: [PATCH v6 2/2] Add total_bytes_including_children column

Add a new column total_bytes_including_children into
pg_backend_memory_contexts.
---
 doc/src/sgml/system-views.sgml         |  9 +++++++++
 src/backend/utils/adt/mcxtfuncs.c      | 28 +++++++++++++++++---------
 src/include/catalog/pg_proc.dat        |  6 +++---
 src/test/regress/expected/rules.out    |  3 ++-
 src/test/regress/expected/sysviews.out | 14 +++++++++++++
 src/test/regress/sql/sysviews.sql      | 10 +++++++++
 6 files changed, 56 insertions(+), 14 deletions(-)

diff --git a/doc/src/sgml/system-views.sgml b/doc/src/sgml/system-views.sgml
index f818aba974..ad2cb71a88 100644
--- a/doc/src/sgml/system-views.sgml
+++ b/doc/src/sgml/system-views.sgml
@@ -530,6 +530,15 @@
       </para></entry>
      </row>
 
+     <row>
+      <entry role="catalog_table_entry"><para role="column_definition">
+       <structfield>total_bytes_including_children</structfield> <type>int8</type>
+      </para>
+      <para>
+       Total bytes allocated for this memory context including its children
+      </para></entry>
+     </row>
+
      <row>
       <entry role="catalog_table_entry"><para role="column_definition">
        <structfield>total_nblocks</structfield> <type>int8</type>
diff --git a/src/backend/utils/adt/mcxtfuncs.c b/src/backend/utils/adt/mcxtfuncs.c
index 82b863341c..ca1eb0840e 100644
--- a/src/backend/utils/adt/mcxtfuncs.c
+++ b/src/backend/utils/adt/mcxtfuncs.c
@@ -38,9 +38,9 @@ static void
 PutMemoryContextsStatsTupleStore(Tuplestorestate *tupstore,
 								 TupleDesc tupdesc, MemoryContext context,
 								 const char *parent, int level, int *context_id,
-								 List *path)
+								 List *path, Size *total_bytes_inc_children)
 {
-#define PG_GET_BACKEND_MEMORY_CONTEXTS_COLS	11
+#define PG_GET_BACKEND_MEMORY_CONTEXTS_COLS	12
 
 	Datum		values[PG_GET_BACKEND_MEMORY_CONTEXTS_COLS];
 	bool		nulls[PG_GET_BACKEND_MEMORY_CONTEXTS_COLS];
@@ -50,6 +50,7 @@ PutMemoryContextsStatsTupleStore(Tuplestorestate *tupstore,
 	const char *ident;
 	const char *type;
 	int  current_context_id = (*context_id)++;
+	Size total_bytes_children = 0;
 
 	Assert(MemoryContextIsValid(context));
 
@@ -127,20 +128,26 @@ PutMemoryContextsStatsTupleStore(Tuplestorestate *tupstore,
 	path = lappend_int(path, current_context_id);
 	values[5] = convert_path_to_datum(path);
 
-	values[6] = Int64GetDatum(stat.totalspace);
-	values[7] = Int64GetDatum(stat.nblocks);
-	values[8] = Int64GetDatum(stat.freespace);
-	values[9] = Int64GetDatum(stat.freechunks);
-	values[10] = Int64GetDatum(stat.totalspace - stat.freespace);
-
+	total_bytes_children += stat.totalspace;
 	for (child = context->firstchild; child != NULL; child = child->nextchild)
 	{
 		PutMemoryContextsStatsTupleStore(tupstore, tupdesc, child, name,
-										 level+1, context_id, path);
+										 level+1, context_id, path,
+										 &total_bytes_children);
 	}
 	path = list_delete_last(path);
+
+	values[6] = Int64GetDatum(stat.totalspace);
+	values[7] = Int64GetDatum(total_bytes_children);
+	values[8] = Int64GetDatum(stat.nblocks);
+	values[9] = Int64GetDatum(stat.freespace);
+	values[10] = Int64GetDatum(stat.freechunks);
+	values[11] = Int64GetDatum(stat.totalspace - stat.freespace);
+
 	
 	tuplestore_putvalues(tupstore, tupdesc, values, nulls);
+
+	*total_bytes_inc_children += total_bytes_children;
 }
 
 /*
@@ -153,11 +160,12 @@ pg_get_backend_memory_contexts(PG_FUNCTION_ARGS)
 	ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
 	int context_id = 0;
 	List *path = NIL;
+	Size total_bytes_inc_children = 0;
 
 	InitMaterializedSRF(fcinfo, 0);
 	PutMemoryContextsStatsTupleStore(rsinfo->setResult, rsinfo->setDesc,
 									 TopMemoryContext, NULL, 0, &context_id,
-									 path);
+									 path, &total_bytes_inc_children);
 
 	return (Datum) 0;
 }
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 202a0b7567..be31190f62 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -8279,9 +8279,9 @@
   proname => 'pg_get_backend_memory_contexts', prorows => '100',
   proretset => 't', provolatile => 'v', proparallel => 'r',
   prorettype => 'record', proargtypes => '',
-  proallargtypes => '{text,text,text,text,int4,_int4,int8,int8,int8,int8,int8}',
-  proargmodes => '{o,o,o,o,o,o,o,o,o,o,o}',
-  proargnames => '{name, ident, parent, type, level, path, total_bytes, total_nblocks, free_bytes, free_chunks, used_bytes}',
+  proallargtypes => '{text,text,text,text,int4,_int4,int8,int8,int8,int8,int8,int8}',
+  proargmodes => '{o,o,o,o,o,o,o,o,o,o,o,o}',
+  proargnames => '{name, ident, parent, type, level, path, total_bytes, total_bytes_including_children, total_nblocks, free_bytes, free_chunks, used_bytes}',
   prosrc => 'pg_get_backend_memory_contexts' },
 
 # logging memory contexts of the specified backend
diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out
index 5201280669..9318cb5212 100644
--- a/src/test/regress/expected/rules.out
+++ b/src/test/regress/expected/rules.out
@@ -1310,11 +1310,12 @@ pg_backend_memory_contexts| SELECT name,
     level,
     path,
     total_bytes,
+    total_bytes_including_children,
     total_nblocks,
     free_bytes,
     free_chunks,
     used_bytes
-   FROM pg_get_backend_memory_contexts() pg_get_backend_memory_contexts(name, ident, parent, type, level, path, total_bytes, total_nblocks, free_bytes, free_chunks, used_bytes);
+   FROM pg_get_backend_memory_contexts() pg_get_backend_memory_contexts(name, ident, parent, type, level, path, total_bytes, total_bytes_including_children, total_nblocks, free_bytes, free_chunks, used_bytes);
 pg_config| SELECT name,
     setting
    FROM pg_config() pg_config(name, setting);
diff --git a/src/test/regress/expected/sysviews.out b/src/test/regress/expected/sysviews.out
index b27b7dca4b..fa64b6de9b 100644
--- a/src/test/regress/expected/sysviews.out
+++ b/src/test/regress/expected/sysviews.out
@@ -64,6 +64,20 @@ where array[(select path[level+1] from contexts where name = 'CacheMemoryContext
  t
 (1 row)
 
+-- Test whether total_bytes_including_children really sums up to the total
+-- bytes used by all child contexts of CacheMemoryContext.
+with contexts as (
+  select * from pg_backend_memory_contexts
+)
+select sum(total_bytes) = 
+      (select total_bytes_including_children from contexts where name = 'CacheMemoryContext')
+from contexts
+where array[(select path[level+1] from contexts where name = 'CacheMemoryContext')] <@ path;
+ ?column? 
+----------
+ t
+(1 row)
+
 -- At introduction, pg_config had 23 entries; it may grow
 select count(*) > 20 as ok from pg_config;
  ok 
diff --git a/src/test/regress/sql/sysviews.sql b/src/test/regress/sql/sysviews.sql
index 0953d3e2c7..91da7eb5bb 100644
--- a/src/test/regress/sql/sysviews.sql
+++ b/src/test/regress/sql/sysviews.sql
@@ -41,6 +41,16 @@ select count(*) > 0
 from contexts
 where array[(select path[level+1] from contexts where name = 'CacheMemoryContext')] <@ path;
 
+-- Test whether total_bytes_including_children really sums up to the total
+-- bytes used by all child contexts of CacheMemoryContext.
+with contexts as (
+  select * from pg_backend_memory_contexts
+)
+select sum(total_bytes) = 
+      (select total_bytes_including_children from contexts where name = 'CacheMemoryContext')
+from contexts
+where array[(select path[level+1] from contexts where name = 'CacheMemoryContext')] <@ path;
+
 -- At introduction, pg_config had 23 entries; it may grow
 select count(*) > 20 as ok from pg_config;
 
-- 
2.34.1

