From 476a839bdbf23c00ea964826f04716df1db25bb9 Mon Sep 17 00:00:00 2001 From: "Chao Li (Evan)" Date: Mon, 23 Nov 2026 14:46:16 +0800 Subject: [PATCH v2] pg_receivewal, pg_basebackup: Fix temporary file cleanup on errors pg_receivewal and the WAL streaming process of pg_basebackup could leave temporary files behind when closing them failed, even though their removal had been requested. For example, a temporary timeline history file could remain after a write failure, unnecessarily occupying disk space. This happened because dir_close() attempted to unlink a file requested with CLOSE_UNLINK only if the preceding operations succeeded. Failures while finalizing compression, writing the final compressed data, or closing the file could therefore skip the unlink operation. Fix this by moving the unlink operation into the common cleanup path, so that it is attempted even after an earlier failure. Backpatch to all supported versions. Author: Chao Li Reviewed-by: Xuneng Zhou Discussion: https://postgr.es/m/9C37FACF-2D67-450D-864A-344F81229860@gmail.com Backpatch-through: 15 --- src/bin/pg_basebackup/walmethods.c | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/bin/pg_basebackup/walmethods.c b/src/bin/pg_basebackup/walmethods.c index 90475b299ce..8cb71b804e6 100644 --- a/src/bin/pg_basebackup/walmethods.c +++ b/src/bin/pg_basebackup/walmethods.c @@ -432,7 +432,7 @@ dir_close(Walfile *f, WalCloseMethod method) #endif r = close(df->fd); - if (r == 0) + if (r == 0 && method != CLOSE_UNLINK) { /* Build path to the current version of the file */ if (method == CLOSE_NORMAL && df->temp_suffix) @@ -467,18 +467,6 @@ dir_close(Walfile *f, WalCloseMethod method) } } } - else if (method == CLOSE_UNLINK) - { - char *filename; - - /* Unlink the file once it's closed */ - filename = dir_get_file_name(f->wwmethod, df->base.pathname, - df->temp_suffix); - snprintf(tmppath, sizeof(tmppath), "%s/%s", - dir_data->basedir, filename); - pg_free(filename); - r = unlink(tmppath); - } else { /* @@ -505,6 +493,19 @@ cleanup: LZ4F_freeCompressionContext(df->ctx); #endif + if (method == CLOSE_UNLINK) + { + /* + * If unlink fails, report its error if the preceding operations + * succeeded; otherwise, preserve the earlier error. + */ + if (unlink(df->fullpath) != 0 && r == 0) + { + f->wwmethod->lasterrno = errno; + r = -1; + } + } + pg_free(df->base.pathname); pg_free(df->fullpath); pg_free(df->temp_suffix); -- 2.56.1