From a076bd8c5dc50679c30cd0b4b6cff7ad24936e5c Mon Sep 17 00:00:00 2001 From: Goutham Reddy Aenugu Date: Sat, 21 Nov 2026 03:37:48 -0800 Subject: [PATCH v1 2/3] Expose end-of-recovery progress in pg_stat_recovery While a standby promotion is finishing, connections can still report that recovery is in progress. Expose whether WAL replay has ended and whether startup has reached the step that removes the signal files. Show the new timeline as soon as startup publishes its selection. Collect these values with the rest of the recovery statistics under the same spinlock. Exercise the states on a standby with and without injection points. --- doc/src/sgml/monitoring.sgml | 53 ++++++++++++++ src/backend/access/transam/xlog.c | 8 +++ src/backend/access/transam/xlogfuncs.c | 36 ++++++++++ src/backend/access/transam/xlogrecovery.c | 15 ++++ src/backend/catalog/system_views.sql | 4 +- src/include/access/xlogrecovery.h | 13 ++++ src/include/catalog/pg_proc.dat | 6 +- src/test/recovery/meson.build | 1 + src/test/recovery/t/062_promotion_state.pl | 81 ++++++++++++++++++++++ src/test/regress/expected/rules.out | 6 +- src/tools/pgindent/typedefs.list | 1 + 11 files changed, 218 insertions(+), 6 deletions(-) create mode 100644 src/test/recovery/t/062_promotion_state.pl diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index 445fbc9..70c3640 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -2250,6 +2250,59 @@ description | Waiting for a newly initialized WAL file to reach durable storage + + + recovery_end_state text + + + The startup process's progress toward ending recovery. + + + + + With replaying, the startup process is replaying, + waiting for, or paused before applying more WAL. A restart of a + standby at this stage starts it in standby mode again. + + + + + With ending, the startup process has finished + WAL replay and is preparing to end recovery. This includes a pause + at a recovery target. A restart at this stage follows the mode + requested by the existing signal files, if any. + + + + + With timeline switched, the startup process has + selected a new timeline and reached the step that durably removes + the recovery signal files. This state is reported just before + removing the files so that the shared state reflects the transition + by the time restarting can bring up a primary. A failover controller + should treat this state as a switch that may already have taken + effect. If the server stops during removal, its restart behavior + depends on which signal files remain. Once the removal is durable, + a restart brings up a primary unless archive recovery is requested + again. + + + + + + + + + new_timeline integer + + + Timeline selected for the end of archive recovery. This is NULL until + the startup process reports the selected timeline. Ordinary crash + recovery keeps the existing timeline. + + + + diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index fd37ea4..5ba6bee 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -6559,7 +6559,10 @@ StartupXLOG(void) performedWalRecovery = true; } else + { performedWalRecovery = false; + SetRecoveryEndState(RECOVERY_END_STARTED, 0); + } /* * Finish WAL recovery. @@ -6659,8 +6662,10 @@ StartupXLOG(void) if (ArchiveRecoveryRequested) { newTLI = findNewestTimeLine(recoveryTargetTLI) + 1; + INJECTION_POINT("promotion-before-timeline-switch", NULL); ereport(LOG, (errmsg("selected new timeline ID: %u", newTLI))); + SetRecoveryEndState(RECOVERY_END_STARTED, newTLI); /* * Make a writable copy of the last WAL segment. (Note that we also @@ -6672,7 +6677,10 @@ StartupXLOG(void) /* * Remove the signal files out of the way, so that we don't * accidentally re-enter archive recovery mode in a subsequent crash. + * Publish the transition first, so the shared state marks the + * timeline switch before the restart behavior changes. */ + SetRecoveryEndState(RECOVERY_END_TIMELINE_SWITCHED, newTLI); if (endOfRecoveryInfo->standby_signal_file_found) durable_unlink(STANDBY_SIGNAL_FILE, FATAL); diff --git a/src/backend/access/transam/xlogfuncs.c b/src/backend/access/transam/xlogfuncs.c index 1f52bf7..a66f1e1 100644 --- a/src/backend/access/transam/xlogfuncs.c +++ b/src/backend/access/transam/xlogfuncs.c @@ -74,6 +74,32 @@ GetRecoveryPauseStateString(RecoveryPauseState pause_state) return statestr; } +/* + * Return a string constant representing the end-of-recovery state. This is + * used in a system view, and should *not* be translated. + */ +static const char * +GetRecoveryEndStateString(RecoveryEndState end_state) +{ + const char *statestr = NULL; + + switch (end_state) + { + case RECOVERY_END_NOT_STARTED: + statestr = "replaying"; + break; + case RECOVERY_END_STARTED: + statestr = "ending"; + break; + case RECOVERY_END_TIMELINE_SWITCHED: + statestr = "timeline switched"; + break; + } + + Assert(statestr != NULL); + return statestr; +} + /* * pg_backup_start: set up for taking an on-line backup dump * @@ -791,6 +817,8 @@ pg_stat_get_recovery(PG_FUNCTION_ARGS) TimestampTz recovery_last_xact_time; TimestampTz current_chunk_start_time; RecoveryPauseState pause_state; + RecoveryEndState end_state; + TimeLineID new_timeline; if (!RecoveryInProgress()) PG_RETURN_NULL(); @@ -809,6 +837,8 @@ pg_stat_get_recovery(PG_FUNCTION_ARGS) recovery_last_xact_time = XLogRecoveryCtl->recoveryLastXTime; current_chunk_start_time = XLogRecoveryCtl->currentChunkStartTime; pause_state = XLogRecoveryCtl->recoveryPauseState; + end_state = XLogRecoveryCtl->recoveryEndState; + new_timeline = XLogRecoveryCtl->recoveryEndNewTLI; SpinLockRelease(&XLogRecoveryCtl->info_lck); if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) @@ -855,6 +885,12 @@ pg_stat_get_recovery(PG_FUNCTION_ARGS) nulls[7] = true; values[8] = CStringGetTextDatum(GetRecoveryPauseStateString(pause_state)); + values[9] = CStringGetTextDatum(GetRecoveryEndStateString(end_state)); + + if (new_timeline != 0) + values[10] = Int32GetDatum(new_timeline); + else + nulls[10] = true; PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls))); } diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c index e091a3e..2c6a7e1 100644 --- a/src/backend/access/transam/xlogrecovery.c +++ b/src/backend/access/transam/xlogrecovery.c @@ -411,6 +411,7 @@ static void XLogRecoveryShmemInit(void *arg) { memset(XLogRecoveryCtl, 0, sizeof(XLogRecoveryCtlData)); + XLogRecoveryCtl->recoveryEndState = RECOVERY_END_NOT_STARTED; SpinLockInit(&XLogRecoveryCtl->info_lck); InitSharedLatch(&XLogRecoveryCtl->recoveryWakeupLatch); @@ -1830,6 +1831,7 @@ PerformWalRecovery(void) /* * end of main redo apply loop */ + SetRecoveryEndState(RECOVERY_END_STARTED, 0); if (reachedRecoveryTarget) { @@ -1882,6 +1884,7 @@ PerformWalRecovery(void) else { /* there are no WAL records following the checkpoint */ + SetRecoveryEndState(RECOVERY_END_STARTED, 0); ereport(LOG, (errmsg("redo is not required"))); } @@ -3083,6 +3086,18 @@ GetRecoveryPauseState(void) return state; } +/* + * Publish end-of-recovery progress from the startup process. + */ +void +SetRecoveryEndState(RecoveryEndState state, TimeLineID newTLI) +{ + SpinLockAcquire(&XLogRecoveryCtl->info_lck); + XLogRecoveryCtl->recoveryEndState = state; + XLogRecoveryCtl->recoveryEndNewTLI = newTLI; + SpinLockRelease(&XLogRecoveryCtl->info_lck); +} + /* * Set the recovery pause state. * diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql index 6dce919..2368928 100644 --- a/src/backend/catalog/system_views.sql +++ b/src/backend/catalog/system_views.sql @@ -1042,7 +1042,9 @@ CREATE VIEW pg_stat_recovery AS s.replay_end_tli, s.recovery_last_xact_time, s.current_chunk_start_time, - s.pause_state + s.pause_state, + s.recovery_end_state, + s.new_timeline FROM pg_stat_get_recovery() s WHERE s.promote_triggered IS NOT NULL; diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h index 11d3ead..a571368 100644 --- a/src/include/access/xlogrecovery.h +++ b/src/include/access/xlogrecovery.h @@ -60,6 +60,14 @@ typedef enum RecoveryPauseState RECOVERY_PAUSED, /* recovery is paused */ } RecoveryPauseState; +/* Progress through the end of recovery. */ +typedef enum RecoveryEndState +{ + RECOVERY_END_NOT_STARTED, + RECOVERY_END_STARTED, + RECOVERY_END_TIMELINE_SWITCHED, +} RecoveryEndState; + /* * Shared-memory state for WAL recovery. */ @@ -126,6 +134,10 @@ typedef struct XLogRecoveryCtlData RecoveryPauseState recoveryPauseState; ConditionVariable recoveryNotPausedCV; + /* End-of-recovery progress and the new timeline (zero until selected). */ + RecoveryEndState recoveryEndState; + TimeLineID recoveryEndNewTLI; + slock_t info_lck; /* locks shared variables shown above */ } XLogRecoveryCtlData; @@ -220,6 +232,7 @@ extern bool HotStandbyActiveInReplay(void); extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI); extern RecoveryPauseState GetRecoveryPauseState(void); extern void SetRecoveryPause(bool recoveryPause); +extern void SetRecoveryEndState(RecoveryEndState state, TimeLineID newTLI); extern void GetXLogReceiptTime(TimestampTz *rtime, bool *fromStream); extern TimestampTz GetLatestXTime(void); extern TimestampTz GetCurrentChunkReplayStartTime(void); diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 50fb182..a963ed9 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -5722,9 +5722,9 @@ { oid => '6514', descr => 'statistics: information about WAL recovery', proname => 'pg_stat_get_recovery', proisstrict => 'f', provolatile => 's', proparallel => 'r', prorettype => 'record', proargtypes => '', - proallargtypes => '{bool,pg_lsn,pg_lsn,int4,pg_lsn,int4,timestamptz,timestamptz,text}', - proargmodes => '{o,o,o,o,o,o,o,o,o}', - proargnames => '{promote_triggered,last_replayed_read_lsn,last_replayed_end_lsn,last_replayed_tli,replay_end_lsn,replay_end_tli,recovery_last_xact_time,current_chunk_start_time,pause_state}', + proallargtypes => '{bool,pg_lsn,pg_lsn,int4,pg_lsn,int4,timestamptz,timestamptz,text,text,int4}', + proargmodes => '{o,o,o,o,o,o,o,o,o,o,o}', + proargnames => '{promote_triggered,last_replayed_read_lsn,last_replayed_end_lsn,last_replayed_tli,replay_end_lsn,replay_end_tli,recovery_last_xact_time,current_chunk_start_time,pause_state,recovery_end_state,new_timeline}', prosrc => 'pg_stat_get_recovery' }, { oid => '6169', descr => 'statistics: information about replication slot', proname => 'pg_stat_get_replication_slot', provolatile => 's', diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index cb3df6e..7b9d3e8 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -70,6 +70,7 @@ tests += { 't/059_remote_apply_status_interval.pl', 't/060_multixact_crashed_updater.pl', 't/061_recovery_target_prefetch.pl', + 't/062_promotion_state.pl', ], }, } diff --git a/src/test/recovery/t/062_promotion_state.pl b/src/test/recovery/t/062_promotion_state.pl new file mode 100644 index 0000000..b4b8929 --- /dev/null +++ b/src/test/recovery/t/062_promotion_state.pl @@ -0,0 +1,81 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Test how pg_stat_recovery reports standby promotion. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $primary = PostgreSQL::Test::Cluster->new('primary'); +$primary->init(allows_streaming => 1); +$primary->start; + +# The extension may be absent in an installcheck run. +my $injection_points_enabled = ($ENV{enable_injection_points} // '') eq 'yes'; +my $have_injection_points = $injection_points_enabled + && $primary->check_extension('injection_points'); +$primary->safe_psql('postgres', 'CREATE EXTENSION injection_points') + if $have_injection_points; + +$primary->backup('backup'); +my $standby = PostgreSQL::Test::Cluster->new('standby'); +$standby->init_from_backup($primary, 'backup', has_streaming => 1); +$standby->start; +$primary->wait_for_replay_catchup($standby); + +my $state_query = q[ + SELECT pg_is_in_recovery(), promote_triggered, recovery_end_state, + new_timeline + FROM pg_stat_recovery]; + +is($standby->safe_psql('postgres', $state_query), + 't|f|replaying|', 'standby is replaying before promotion'); +is( $standby->safe_psql( + 'postgres', + 'SET ROLE pg_read_all_data; SELECT count(*) FROM pg_stat_recovery'), + '0', + 'recovery state requires pg_read_all_stats privileges'); + +SKIP: +{ + skip 'Injection points not supported by this build', 3 + unless $injection_points_enabled; + skip 'Extension injection_points not installed', 3 + unless $have_injection_points; + + my $before_switch = 'promotion-before-timeline-switch'; + $standby->safe_psql('postgres', + "SELECT injection_points_attach('$before_switch', 'wait')"); + $standby->safe_psql('postgres', 'SELECT pg_promote(false)'); + $standby->wait_for_event('startup', $before_switch); + is($standby->safe_psql('postgres', $state_query), + 't|t|ending|', 'recovery is ending before timeline selection'); + + # Simulate a crash before the timeline switch. Recovery resumes as a + # standby and the state from the interrupted promotion is cleared. + $standby->stop('immediate'); + $standby->start; + $primary->wait_for_replay_catchup($standby); + is($standby->safe_psql('postgres', $state_query), + 't|f|replaying|', + 'restart before the timeline switch remains a standby'); + + my $after_switch = 'promotion-after-wal-segment-cleanup'; + $standby->safe_psql('postgres', + "SELECT injection_points_attach('$after_switch', 'wait')"); + $standby->safe_psql('postgres', 'SELECT pg_promote(false)'); + $standby->wait_for_event('startup', $after_switch); + is( $standby->safe_psql('postgres', $state_query), + 't|t|timeline switched|2', + 'timeline switched while still in recovery'); + $standby->safe_psql('postgres', + "SELECT injection_points_wakeup('$after_switch')"); +} + +$standby->promote unless $have_injection_points; +ok( $standby->poll_query_until( + 'postgres', 'SELECT count(*) = 0 FROM pg_stat_recovery'), + 'no recovery state after promotion completes'); + +done_testing(); diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index acbe466..bd8720b 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -2231,8 +2231,10 @@ pg_stat_recovery| SELECT promote_triggered, replay_end_tli, recovery_last_xact_time, current_chunk_start_time, - pause_state - FROM pg_stat_get_recovery() s(promote_triggered, last_replayed_read_lsn, last_replayed_end_lsn, last_replayed_tli, replay_end_lsn, replay_end_tli, recovery_last_xact_time, current_chunk_start_time, pause_state) + pause_state, + recovery_end_state, + new_timeline + FROM pg_stat_get_recovery() s(promote_triggered, last_replayed_read_lsn, last_replayed_end_lsn, last_replayed_tli, replay_end_lsn, replay_end_tli, recovery_last_xact_time, current_chunk_start_time, pause_state, recovery_end_state, new_timeline) WHERE (promote_triggered IS NOT NULL); pg_stat_recovery_prefetch| SELECT stats_reset, prefetch, diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb46..4a79fae 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2555,6 +2555,7 @@ RecordCacheEntry RecordCompareData RecordIOData RecoveryConflictReason +RecoveryEndState RecoveryLockEntry RecoveryLockXidEntry RecoveryPauseState -- 2.56.1