From 2805b09ebb5e71908ca34e4c355f1eaccab97ef4 Mon Sep 17 00:00:00 2001
From: Vaibhav Jain <jainva@google.com>
Date: Mon, 22 Sep 2025 18:11:08 +0530
Subject: Fix overflow of nbatch

With a1b4f28, to compute current_space, nbatch is being multiplied
by BLCKSZ. nbatch is int and when multiplied with BLCKSZ, it can
easily overflow the int limit. To keep the calculation safe for
current_space, convert nbatch to size_t.

---
 src/backend/executor/nodeHash.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/backend/executor/nodeHash.c b/src/backend/executor/nodeHash.c
index a3415db4e20..4e0e18314d1 100644
--- a/src/backend/executor/nodeHash.c
+++ b/src/backend/executor/nodeHash.c
@@ -912,10 +912,10 @@ ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew,
 	while (nbatch > 0)
 	{
 		/* how much memory are we using with current nbatch value */
-		size_t		current_space = hash_table_bytes + (2 * nbatch * BLCKSZ);
+		size_t		current_space = hash_table_bytes + (2 * (size_t) nbatch * BLCKSZ);
 
 		/* how much memory would we use with half the batches */
-		size_t		new_space = hash_table_bytes * 2 + (nbatch * BLCKSZ);
+		size_t		new_space = hash_table_bytes * 2 + ((size_t) nbatch * BLCKSZ);
 
 		/* If the memory usage would not decrease, we found the optimum. */
 		if (current_space < new_space)
@@ -994,7 +994,7 @@ ExecHashIncreaseBatchSize(HashJoinTable hashtable)
 	 * How much additional memory would doubling nbatch use? Each batch may
 	 * require two buffered files (inner/outer), with a BLCKSZ buffer.
 	 */
-	size_t		batchSpace = (hashtable->nbatch * 2 * BLCKSZ);
+	size_t		batchSpace = ((size_t) hashtable->nbatch * 2 * BLCKSZ);
 
 	/*
 	 * Compare the new space needed for doubling nbatch and for enlarging the

