From 1d5478914d46b60efee0d7f2c8caed377b895584 Mon Sep 17 00:00:00 2001
From: Peter Geoghegan <pg@bowt.ie>
Date: Thu, 10 Mar 2016 14:52:18 -0800
Subject: [PATCH 4/4] Add MemoryContextStats() calls for debugging

N.B.:  This patch is only intended to help demonstrate that tuplesort's
use of memory remains honest (within budget).  It may have an
appreciable overhead, and should not be applied for performance tests.

Reviewers may find it interesting to consider how commenting out the new
MemoryContextReset() calls affects palloc() fragmentation in practice.
Doing so should not cause a memory leak; bytes "used" should not change
in debug output.  The "total" bytes in tuplesort memory contexts may
balloon, though.
---
 src/backend/utils/sort/tuplesort.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c
index 0029daa..7b81f2c 100644
--- a/src/backend/utils/sort/tuplesort.c
+++ b/src/backend/utils/sort/tuplesort.c
@@ -2621,6 +2621,7 @@ mergeonerun(Tuplesortstate *state)
 	 * out, and replacing it with next tuple from same tape (if there is
 	 * another one).
 	 */
+	MemoryContextStats(state->sortcontext);
 	while (state->memtupcount > 0)
 	{
 		/* write the tuple to destTape */
@@ -2928,6 +2929,7 @@ mergebatch(Tuplesortstate *state, int64 spacePerTape)
 
 	state->batchUsed = true;
 	state->spacePerTape = spacePerTape;
+	MemoryContextStats(state->sortcontext);
 }
 
 /*
-- 
1.9.1

