From 5b0b7a6a7fad9eccf969ecffbbbab581e3c1a33a Mon Sep 17 00:00:00 2001
From: Jehan-Guillaume de Rorthais <jgdr@dalibo.com>
Date: Tue, 21 Jul 2020 17:13:20 +0200
Subject: [PATCH] Fix explain analyse buffers for nodes on top of Gather Merge
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

During the recursive call of ExecShutdownNode, the upper nodes call
InstrStartNode *after* parallel workers buffers have been accounted in
pgBufferUsage. Because of this, pgBufferUsage doesn't move anymore before the
call to InstrStopNode and buffers from parallel workers are only accounted up
to the Gather Merge node, but not to upper node.

The Gater node was safe because it shutdowns its worker and harvest their
buffers before the ExecShutdownNode recursion happen.

Moving the call of InstrStartNode before the recurring call set the
bufusage_start of upper nodes before entering in the parallel plan, so all
buffer accumulated in pgBufferUsage are properly propagated outside of the
parallel part of the plan.

Author: Jehan-Guillaume de Rorthais <jgdr@dalibo.com>
Reported-by: Stéphane Lorek, Jehan-Guillaume de Rorthais
---
 src/backend/executor/execProcnode.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/backend/executor/execProcnode.c b/src/backend/executor/execProcnode.c
index 610cb4b8a9..6207677fbc 100644
--- a/src/backend/executor/execProcnode.c
+++ b/src/backend/executor/execProcnode.c
@@ -746,8 +746,6 @@ ExecShutdownNode(PlanState *node)
 
 	check_stack_depth();
 
-	planstate_tree_walker(node, ExecShutdownNode, NULL);
-
 	/*
 	 * Treat the node as running while we shut it down, but only if it's run
 	 * at least once already.  We don't expect much CPU consumption during
@@ -761,6 +759,8 @@ ExecShutdownNode(PlanState *node)
 	if (node->instrument && node->instrument->running)
 		InstrStartNode(node->instrument);
 
+	planstate_tree_walker(node, ExecShutdownNode, NULL);
+
 	switch (nodeTag(node))
 	{
 		case T_GatherState:
-- 
2.20.1

