From 068e1578b9cdb76ff8f576415b0ce0429ff019ad Mon Sep 17 00:00:00 2001
From: Sai Pranav <rajasaipranav0@gmail.com>
Date: Thu, 26 Nov 2026 18:10:43 +0530
Subject: [PATCH v2] pg_receivewal: Skip a completed LZ4 segment whose frame is
 incomplete

When looking for where to restart streaming, pg_receivewal decompresses
each completed .lz4 segment and accepts it if it yields exactly one
segment of data.  It did not check that the LZ4 frame was complete, so a
file cut off after its last data block but before the frame's end mark
was taken as a complete segment, and streaming restarted after it.

pg_receivewal itself flushes segments in full unless --no-sync is used,
but FindStreamingStart() also accepts segments from external sources,
so check this as a defense in depth.  LZ4F_decompress() returns 0 once a
frame is fully decoded; skip the segment, with a warning, if that never
happened.

Discussion: https://postgr.es/m/19890-293babc93c520dc8@postgresql.org
---
 src/bin/pg_basebackup/pg_receivewal.c | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index 85f3616beb..e52a70f8db 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -372,6 +372,7 @@ FindStreamingStart(uint32 *tli_p)
 			int			fd;
 			ssize_t		r;
 			size_t		uncompressed_size = 0;
+			bool		frame_complete = false;
 			char		fullpath[MAXPGPATH * 2];
 			char	   *outbuf;
 			char	   *readbuf;
@@ -424,6 +425,8 @@ FindStreamingStart(uint32 *tli_p)
 
 					readp += read_size;
 					uncompressed_size += out_size;
+					/* LZ4F_decompress() returns 0 once the frame is complete */
+					frame_complete = (status == 0);
 				}
 
 				/*
@@ -450,6 +453,12 @@ FindStreamingStart(uint32 *tli_p)
 							   dirent->d_name, uncompressed_size);
 				continue;
 			}
+			if (!frame_complete)
+			{
+				pg_log_warning("compressed segment file \"%s\" is truncated, skipping",
+							   dirent->d_name);
+				continue;
+			}
 #else
 			pg_log_error("cannot check file \"%s\": compression with %s not supported by this build",
 						 dirent->d_name, "LZ4");
-- 
2.50.1 (Apple Git-155)

