From 7d0a95be71b0513f606933e8e2923a0fc14afa31 Mon Sep 17 00:00:00 2001 From: "Chao Li (Evan)" Date: Mon, 23 Nov 2026 14:46:16 +0800 Subject: [PATCH v1] Ensure CLOSE_UNLINK removes files even after earlier failures In dir_close(), CLOSE_UNLINK previously unlinked the file only when the preceding operations succeeded. If an earlier operation failed, such as LZ4 compression finalization or closing the file, the unlink operation could be skipped, leaving a temporary WAL file behind. Move the unlink operation into the common cleanup path so that it is attempted even if an earlier operation failed. If unlinking also fails, preserve the earlier error instead of overwriting it. Author: Chao Li Reviewed-by: Discussion: https://postgr.es/m/ --- src/bin/pg_basebackup/walmethods.c | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/bin/pg_basebackup/walmethods.c b/src/bin/pg_basebackup/walmethods.c index 90475b299ce..d7465439190 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,22 @@ cleanup: LZ4F_freeCompressionContext(df->ctx); #endif + /* Honor CLOSE_UNLINK even if close failed. */ + if (method == CLOSE_UNLINK) + { + int unlink_result = unlink(df->fullpath); + + /* + * Try to preserve the first error, thus only report an unlink failure + * if the preceding operations succeeded. + */ + if (unlink_result != 0 && r == 0) + { + f->wwmethod->lasterrno = errno; + r = -1; + } + } + pg_free(df->base.pathname); pg_free(df->fullpath); pg_free(df->temp_suffix); -- 2.50.1 (Apple Git-155)