From 2a3da578246769d023ff4a1bf0041e55c104c46b Mon Sep 17 00:00:00 2001 From: Ayush Tiwari Date: Thu, 26 Nov 2026 18:46:41 +0000 Subject: [PATCH v1 1/2] pg_receivewal: Truncate compressed WAL files when opening them When pg_receivewal restarts, it resumes streaming from the start of the last partial segment. For a compressed segment, the existing .partial file was opened again without O_TRUNC, and the new compressed data was written over the old data. If the new stream ended up shorter than the old one, the end of the old stream stayed in the file and was kept when the segment was completed. This is easy to hit with --synchronous, as each sync flushes the compressor, so the compressed size depends on how often the data was flushed. With LZ4, every later start of pg_receivewal then fails, as the segment cannot be decompressed anymore. With gzip, the segment gets skipped, because the uncompressed size read from the end of the file is wrong. Compressed files are never padded, so truncate them when opening them. Backpatch to all supported versions. Author: Ayush Tiwari Backpatch-through: 15 --- src/bin/pg_basebackup/walmethods.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/bin/pg_basebackup/walmethods.c b/src/bin/pg_basebackup/walmethods.c index 8cb71b804e6..c1c654a3eb4 100644 --- a/src/bin/pg_basebackup/walmethods.c +++ b/src/bin/pg_basebackup/walmethods.c @@ -120,6 +120,7 @@ dir_open_for_write(WalWriteMethod *wwmethod, const char *pathname, DirectoryMethodData *dir_data = (DirectoryMethodData *) wwmethod; char tmppath[MAXPGPATH]; char *filename; + int flags; int fd; DirectoryMethodFile *f; #ifdef HAVE_LIBZ @@ -143,8 +144,16 @@ dir_open_for_write(WalWriteMethod *wwmethod, const char *pathname, * the file descriptor is important for dir_sync() method as gzflush() * does not do any system calls to fsync() to make changes permanent on * disk. + * + * Compressed files need to be truncated, as we may be reopening a partial + * segment from an earlier run, and the new compressed data can be shorter + * than what is already there. Non-compressed segments are padded to + * their full size, so this is not a problem for them. */ - fd = open(tmppath, O_WRONLY | O_CREAT | PG_BINARY, pg_file_create_mode); + flags = O_WRONLY | O_CREAT | PG_BINARY; + if (wwmethod->compression_algorithm != PG_COMPRESSION_NONE) + flags |= O_TRUNC; + fd = open(tmppath, flags, pg_file_create_mode); if (fd < 0) { wwmethod->lasterrno = errno; -- 2.43.0