From 2ae24da62261d170c43157e90f70ea8c88b9808f Mon Sep 17 00:00:00 2001
From: Andrey Borodin <amborodin@acm.org>
Date: Fri, 2 May 2025 17:13:07 +0500
Subject: [PATCH 3/3] Allow reading LSN written by walreciever, but not flushed
 yet

This LSN is needed for HA tools that operate on synchronous_commit
remote_write level. When this tools perform failover, node that
have done recent flush might win instead of node that actually
acknoledged transaction. Thus such tools loos recently committed
transactions.
---
 src/backend/access/transam/xlogfuncs.c | 19 +++++++++++++++++++
 src/include/catalog/pg_proc.dat        |  4 ++++
 2 files changed, 23 insertions(+)

diff --git a/src/backend/access/transam/xlogfuncs.c b/src/backend/access/transam/xlogfuncs.c
index 8c3090165f0..ecc81e799a9 100644
--- a/src/backend/access/transam/xlogfuncs.c
+++ b/src/backend/access/transam/xlogfuncs.c
@@ -347,6 +347,25 @@ pg_last_wal_receive_lsn(PG_FUNCTION_ARGS)
 	PG_RETURN_LSN(recptr);
 }
 
+/*
+ * Report the last WAL receive location
+ *
+ * This is useful for determining how much of WAL is guaranteed to be received
+ * and written to disk by walreceiver, but not flushed yet.
+ */
+Datum
+pg_last_wal_receive_unflushed_lsn(PG_FUNCTION_ARGS)
+{
+	XLogRecPtr	recptr;
+
+	recptr = GetWalRcvWriteRecPtr();
+
+	if (recptr == 0)
+		PG_RETURN_NULL();
+
+	PG_RETURN_LSN(recptr);
+}
+
 /*
  * Report the last WAL replay location (same format as pg_backup_start etc)
  *
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 62beb71da28..e6755813b90 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6761,6 +6761,10 @@
   proname => 'pg_last_wal_receive_lsn', provolatile => 'v',
   prorettype => 'pg_lsn', proargtypes => '',
   prosrc => 'pg_last_wal_receive_lsn' },
+{ oid => '8035', descr => 'current wal receive location',
+  proname => 'pg_last_wal_receive_unflushed_lsn', provolatile => 'v',
+  prorettype => 'pg_lsn', proargtypes => '',
+  prosrc => 'pg_last_wal_receive_unflushed_lsn' },
 { oid => '3821', descr => 'last wal replay location',
   proname => 'pg_last_wal_replay_lsn', provolatile => 'v',
   prorettype => 'pg_lsn', proargtypes => '',
-- 
2.39.5 (Apple Git-154)

