From a63aa21bd15975ea686840c1f8f7d1f2485a8d81 Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Wed, 25 Nov 2026 09:28:52 +0800
Subject: [PATCH v1 2/2] Simplify the read conditions in copy_read_data()

Assert that minread is positive and does not exceed maxread on entry.
Each copy increases bytesread by the same amount it subtracts from
maxread. As long as bytesread is below minread, there must still be
room in the output buffer.

Remove the redundant maxread checks from the loop and its early return.

Author: Chao Li <lic@highgo.com>
---
 src/backend/replication/logical/tablesync.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/backend/replication/logical/tablesync.c b/src/backend/replication/logical/tablesync.c
index 77917c89133..0dd3cdeb851 100644
--- a/src/backend/replication/logical/tablesync.c
+++ b/src/backend/replication/logical/tablesync.c
@@ -651,6 +651,8 @@ copy_read_data(void *outbuf, int minread, int maxread)
 	int			bytesread = 0;
 	int			avail;
 
+	Assert(minread > 0 && maxread >= minread);
+
 	/* If there are some leftover data from previous read, use it. */
 	avail = copybuf.len - copybuf.cursor;
 	if (avail)
@@ -664,7 +666,7 @@ copy_read_data(void *outbuf, int minread, int maxread)
 		bytesread += avail;
 	}
 
-	while (maxread > 0 && bytesread < minread)
+	while (bytesread < minread)
 	{
 		pgsocket	fd = PGINVALID_SOCKET;
 		int			len;
@@ -697,7 +699,7 @@ copy_read_data(void *outbuf, int minread, int maxread)
 				bytesread += avail;
 			}
 
-			if (maxread <= 0 || bytesread >= minread)
+			if (bytesread >= minread)
 				return bytesread;
 		}
 
-- 
2.50.1 (Apple Git-155)

