WAL_LOG-2-PG_VERSION-sync-v1.patch

text/plain

Filename: WAL_LOG-2-PG_VERSION-sync-v1.patch
Type: text/plain
Part: 1
Message: STRATEGY=WAL_LOG missing checkpoint interlocks and sync

Patch

Format: unified
Series: patch v1
File+
src/backend/commands/dbcommands.c 8 0
src/backend/utils/activity/wait_event_names.txt 1 0
Author:     Noah Misch <noah@leadboat.com>
Commit:     Noah Misch <noah@leadboat.com>

    Sync PG_VERSION file in CREATE DATABASE.
    
    An OS crash could leave PG_VERSION empty or missing.  The same symptom
    appeared in a backup by block device snapshot, taken after the next
    checkpoint and before the OS flushes the PG_VERSION blocks.  Device
    snapshots are not a documented backup method, however.  Back-patch to
    v15, where commit 9c08aea6a3090a396be334cc58c511edab05776a introduced
    STRATEGY=WAL_LOG and made it the default.
    
    Reviewed by FIXME.
    
    Discussion: https://postgr.es/m/FIXME

diff --git a/src/backend/commands/dbcommands.c b/src/backend/commands/dbcommands.c
index dc420ac..41ed2d3 100644
--- a/src/backend/commands/dbcommands.c
+++ b/src/backend/commands/dbcommands.c
@@ -508,6 +508,14 @@ CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
 	}
 	pgstat_report_wait_end();
 
+	pgstat_report_wait_start(WAIT_EVENT_VERSION_FILE_SYNC);
+	if (pg_fsync(fd) != 0)
+		ereport(data_sync_elevel(ERROR),
+				(errcode_for_file_access(),
+				 errmsg("could not fsync file \"%s\": %m", versionfile)));
+	fsync_fname(dbpath, true);
+	pgstat_report_wait_end();
+
 	/* Close the version file. */
 	CloseTransientFile(fd);
 
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index a5df835..6255877 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -236,6 +236,7 @@ TIMELINE_HISTORY_WRITE	"Waiting for a write of a newly created timeline history
 TWOPHASE_FILE_READ	"Waiting for a read of a two phase state file."
 TWOPHASE_FILE_SYNC	"Waiting for a two phase state file to reach durable storage."
 TWOPHASE_FILE_WRITE	"Waiting for a write of a two phase state file."
+VERSION_FILE_SYNC	"Waiting for the version file to reach durable storage while creating a database."
 VERSION_FILE_WRITE	"Waiting for the version file to be written while creating a database."
 WALSENDER_TIMELINE_HISTORY_READ	"Waiting for a read from a timeline history file during a walsender timeline command."
 WAL_BOOTSTRAP_SYNC	"Waiting for WAL to reach durable storage during bootstrapping."