pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
walsummarizer can get stuck when switching timelines
31+ messages / 7 participants
[nested] [flat]

Commits from this thread:
  2026-07-31 3e8a0c1b02 dfb96277d7 18f0de6b88 499d9eabb5  Prevent walsummarizer from getting stuck at a timeline switch.
* walsummarizer can get stuck when switching timelines
@ 2026-07-13 20:39  Robert Haas <robertmhaas@gmail.com>
  0 siblings, 2 replies; 31+ messages in thread

From: Robert Haas @ 2026-07-13 20:39 UTC (permalink / raw)
  To: pgsql-hackers

Hi,

My colleague, Nick Ivanov, reported to me that it's possible for WAL
summarizer to get stuck when a timeline switch occurs. As far as I can
tell, for this to happen, all of the following things need to be true:

1. There must be a standby that is summarizing WAL.
2. That standby must see a timeline change due to some other server
(not itself) being promoted.
3. That standby must be retrieving WAL via archiving, not streaming.
4. The WAL file that contains the switchpoint must be archived on the
new timeline, but not the original one.

The reason this case is a problem is that the WAL summarizer is coded
to only read WAL from a file where the TLI in the filename matches the
TLI of the WAL sought. But in this scenario, the partial segment at
the end of the old timeline is only available from the beginning of
the first file archived on the new timeline, so WAL summarization
cannot progress to, or beyond, the TLI switch.

Here is a patch, with a test case.

-- 
Robert Haas
EDB: http://www.enterprisedb.com

Attachments:

v1-0001-Prevent-walsummarizer-from-getting-stuck-at-a-tim.patch (application/octet-stream, 16.5K) download From ab083317ad17232f09c1f60c460f758d0bce1a8f Mon Sep 17 00:00:00 2001 From: Robert Haas <rhaas@postgresql.org> Date: Mon, 13 Jul 2026 16:33:57 -0400 Subject: [PATCH v1] Prevent walsummarizer from getting stuck at a timeline switch. As previously coded, walsummarizer only wants to read WAL from a file where the TimeLineID in the filename exactly matches the TimeLineID being summarized. But in some cases, when a timeline switch occurs, the WAL file from the old timeline is not archived, because it's never completely filled, so the only way to obtain the contents of that last partial segment is to read from the first segment on the new timeline. Teach WAL summarizer to do that, and add a test case to make sure that it works. Reported-by: Nick Ivanov <nick.ivanov@enterprisedb.com> --- src/backend/postmaster/walsummarizer.c | 173 ++++++++++++++++++++-- src/bin/pg_walsummary/meson.build | 1 + src/bin/pg_walsummary/t/003_tli_switch.pl | 125 ++++++++++++++++ 3 files changed, 285 insertions(+), 14 deletions(-) create mode 100644 src/bin/pg_walsummary/t/003_tli_switch.pl diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c index 4f12eaf2c85..aeee22388e7 100644 --- a/src/backend/postmaster/walsummarizer.c +++ b/src/backend/postmaster/walsummarizer.c @@ -105,6 +105,8 @@ typedef struct bool historic; XLogRecPtr read_upto; bool end_of_wal; + int num_descendant_tlis; + TimeLineID *descendant_tlis; } SummarizerReadLocalXLogPrivate; /* Pointer to shared memory state. */ @@ -156,10 +158,14 @@ int wal_summary_keep_time = 10 * HOURS_PER_DAY * MINS_PER_HOUR; static void WalSummarizerShutdown(int code, Datum arg); static XLogRecPtr GetLatestLSN(TimeLineID *tli); +static XLogRecPtr WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, + TimeLineID **descendant_tlis); static void ProcessWalSummarizerInterrupts(void); static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, XLogRecPtr switch_lsn, - XLogRecPtr maximum_lsn); + XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis); static void SummarizeDbaseRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static void SummarizeSmgrRecord(XLogReaderState *xlogreader, @@ -168,6 +174,9 @@ static void SummarizeXactRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static bool SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward); +static void summarizer_wal_segment_open(XLogReaderState *state, + XLogSegNo nextSegNo, + TimeLineID *tli_p); static int summarizer_read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, @@ -222,16 +231,19 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) * true if 'current_lsn' is known to be the start of a WAL record or WAL * segment, and false if it might be in the middle of a record someplace. * - * 'switch_lsn' and 'switch_tli', if set, are the LSN at which we need to - * switch to a new timeline and the timeline to which we need to switch. - * If not set, we either haven't figured out the answers yet or we're - * already on the latest timeline. + * 'switch_lsn', is the LSN at which we need to switch to a new timeline. + * If not set, we either haven't figured out the answer yet or we're + * already on the latest timeline. 'descendant_tlis' stores an array of + * future timeline IDs to which we know we'll need to switch, and + * 'num_descendant_tlis' is the length of that array. The first element of + * the array is the first timeline to which we will need to switch. */ XLogRecPtr current_lsn; TimeLineID current_tli; bool exact; XLogRecPtr switch_lsn = InvalidXLogRecPtr; - TimeLineID switch_tli = 0; + int num_descendant_tlis = 0; + TimeLineID *descendant_tlis = NULL; Assert(startup_data_len == 0); @@ -379,11 +391,33 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (current_tli != latest_tli && !XLogRecPtrIsValid(switch_lsn)) { List *tles = readTimeLineHistory(latest_tli); + int new_num_descendant_tlis; + TimeLineID *new_descendant_tlis; - switch_lsn = tliSwitchPoint(current_tli, tles, &switch_tli); + /* + * Make sure that the array of descendant TLIs get stored into + * TopMemoryContext. + */ + MemoryContextSwitchTo(TopMemoryContext); + switch_lsn = WalSummarizerSwitchPoint(current_tli, tles, + &new_num_descendant_tlis, + &new_descendant_tlis); + MemoryContextSwitchTo(context); + + /* + * Free any old array of descendant TLIs and install the new + * values. + */ + if (descendant_tlis != NULL) + pfree(descendant_tlis); + num_descendant_tlis = new_num_descendant_tlis; + descendant_tlis = new_descendant_tlis; + + /* Debug message. */ ereport(DEBUG1, errmsg_internal("switch point from TLI %u to TLI %u is at %X/%08X", - current_tli, switch_tli, LSN_FORMAT_ARGS(switch_lsn))); + current_tli, descendant_tlis[0], + LSN_FORMAT_ARGS(switch_lsn))); } /* @@ -394,12 +428,15 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (XLogRecPtrIsValid(switch_lsn) && current_lsn >= switch_lsn) { /* Restart summarization from switch point. */ - current_tli = switch_tli; + Assert(num_descendant_tlis > 0); + current_tli = descendant_tlis[0]; current_lsn = switch_lsn; - /* Next timeline and switch point, if any, not yet known. */ + /* Switch point, if any, and future TLIs, not yet known. */ switch_lsn = InvalidXLogRecPtr; - switch_tli = 0; + num_descendant_tlis = 0; + pfree(descendant_tlis); + descendant_tlis = NULL; /* Update (really, rewind, if needed) state in shared memory. */ LWLockAcquire(WALSummarizerLock, LW_EXCLUSIVE); @@ -415,7 +452,8 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) /* Summarize WAL. */ end_of_summary_lsn = SummarizeWAL(current_tli, current_lsn, exact, - switch_lsn, latest_lsn); + switch_lsn, latest_lsn, + num_descendant_tlis, descendant_tlis); Assert(XLogRecPtrIsValid(end_of_summary_lsn)); Assert(end_of_summary_lsn >= current_lsn); @@ -851,6 +889,62 @@ GetLatestLSN(TimeLineID *tli) } } +/* + * Compute the LSN at which we switched from current_tli to some later timeline. + * 'tles' must be the timeline history of the latest timeline. + * + * As a side effect, we set *num_descendant_tlis to the number of later TLIs that + * appear in the timeline history, and *descendant_tlis to an array of those TLIs, + * starting with immediate successor of current_tli. + */ +static XLogRecPtr +WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, TimeLineID **descendant_tlis) +{ + XLogRecPtr switch_lsn = InvalidXLogRecPtr; + int count = 0; + + /* + * Find the switch point and, at the same time, count the number of TLIs + * in this history that are descendants of that TLI. + */ + foreach_ptr(TimeLineHistoryEntry, tle, tles) + { + if (tle->tli == current_tli) + { + switch_lsn = tle->end; + break; + } + ++count; + } + + /* Sanity checks. */ + if (!XLogRecPtrIsValid(switch_lsn)) + ereport(ERROR, + (errmsg("requested timeline %u is not in this server's history", + current_tli))); + if (count == 0) + elog(ERROR, "cannot compute switch point for current TLI %u", current_tli); + + /* + * Generate an array of TLIs that are part of this history and descendants + * of current_tli. The TLE list starts with the newest timeline and works + * backward toward older timelines; we want the opposite ordering. + */ + *num_descendant_tlis = count; + *descendant_tlis = palloc_array(TimeLineID, count); + for (int i = 0; i < count; ++i) + { + TimeLineHistoryEntry *tle; + + tle = (TimeLineHistoryEntry *) list_nth(tles, count - i - 1); + (*descendant_tlis)[i] = tle->tli; + } + + /* Return value is the switchpoint. */ + return switch_lsn; +} + /* * Interrupt handler for main loop of WAL summarizer process. */ @@ -904,7 +998,8 @@ ProcessWalSummarizerInterrupts(void) */ static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, - XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn) + XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis) { SummarizerReadLocalXLogPrivate *private_data; XLogReaderState *xlogreader; @@ -922,11 +1017,13 @@ SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, private_data->tli = tli; private_data->historic = XLogRecPtrIsValid(switch_lsn); private_data->read_upto = maximum_lsn; + private_data->num_descendant_tlis = num_descendant_tlis; + private_data->descendant_tlis = descendant_tlis; /* Create xlogreader. */ xlogreader = XLogReaderAllocate(wal_segment_size, NULL, XL_ROUTINE(.page_read = &summarizer_read_local_xlog_page, - .segment_open = &wal_segment_open, + .segment_open = &summarizer_wal_segment_open, .segment_close = &wal_segment_close), private_data); if (xlogreader == NULL) @@ -1490,6 +1587,54 @@ SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward) return true; } +/* + * Similar to wal_segment_open, but checks for a file on any descendant timelines + * known to us if no file is found on the requested timeline. + */ +static void +summarizer_wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, + TimeLineID *tli_p) +{ + SummarizerReadLocalXLogPrivate *private_data = state->private_data; + int count = 0; + TimeLineID tli = *tli_p; + char path[MAXPGPATH]; + + for (;;) + { + XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize); + state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY); + if (state->seg.ws_file >= 0) + { + *tli_p = tli; + return; + } + + /* + * If the error is anything other than file-not-found, complain at + * once. + */ + if (errno != ENOENT) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open file \"%s\": %m", + path))); + + /* Try other timelines, if any remain. */ + if (count >= private_data->num_descendant_tlis) + break; + tli = private_data->descendant_tlis[count]; + ++count; + } + + /* Complain about the originally requested filename. */ + XLogFilePath(path, *tli_p, nextSegNo, state->segcxt.ws_segsize); + ereport(ERROR, + (errcode_for_file_access(), + errmsg("requested WAL segment %s has already been removed", + path))); +} + /* * Similar to read_local_xlog_page, but limited to read from one particular * timeline. If the end of WAL is reached, it will wait for more if reading diff --git a/src/bin/pg_walsummary/meson.build b/src/bin/pg_walsummary/meson.build index d012275402b..839b644ef23 100644 --- a/src/bin/pg_walsummary/meson.build +++ b/src/bin/pg_walsummary/meson.build @@ -25,6 +25,7 @@ tests += { 'tests': [ 't/001_basic.pl', 't/002_blocks.pl', + 't/003_tli_switch.pl', ], } } diff --git a/src/bin/pg_walsummary/t/003_tli_switch.pl b/src/bin/pg_walsummary/t/003_tli_switch.pl new file mode 100644 index 00000000000..6258cb44643 --- /dev/null +++ b/src/bin/pg_walsummary/t/003_tli_switch.pl @@ -0,0 +1,125 @@ +# Copyright (c) 2021-2026, PostgreSQL Global Development Group +# +# In the original version of the WAL summarizer code, we were only willing +# to read WAL for a given TLI from a file with that exact TLI encoded into +# the filename. This could result in WAL summarization running on an archiving +# standby getting stuck. +# +# The reason for the problem is that when a new primary is promoted, the +# partial file that ends the old timeline is renamed, giving it a ".partial" +# suffix, and is not archived. That's not a problem for recovery, because +# the bytes that appear at the start of that segment will be copied into the +# first segment on the new timeline, and recovery will read them from there +# and work just fine. Because the WAL summarizer was unwilling to do the same +# thing, it got stuck. This test aims to validate that this bug has been fixed. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# Set up node1 as primary. +my $node1 = PostgreSQL::Test::Cluster->new('node1'); +$node1->init(allows_streaming => 1); +$node1->append_conf('postgresql.conf', <<EOM); +autovacuum = off +EOM +$node1->start; + +# Set up node2 as a standby for node1. +$node1->backup('backup1'); +my $node2 = PostgreSQL::Test::Cluster->new('node2'); +$node2->init_from_backup($node1, 'backup1', has_streaming => 1); +$node2->enable_archiving(); +$node2->start; + +# Wait for node2 to catch up. +$node1->wait_for_replay_catchup($node2); + +# Set up node3 as a standby for node2. To get the desired behavior, we need a few +# configuration changes here. First, we must enable summarization on the new node, +# since that's what we want to test. We also set log_min_messages = debug1 since +# WAL summarization prints a bunch of diagnostics at that level that may be useful +# in case this test fails. Second, we must clear primary_conninfo, so that it can +# only obtain WAL from the archive. Finally, we lower wal_retrieve_retry_interval +# to avoid long, unnecessary waits while running the test. +$node2->backup('backup2'); +my $node3 = PostgreSQL::Test::Cluster->new('node3'); +$node3->init_from_backup($node2, 'backup2', has_restoring => 1); +$node3->append_conf('postgresql.conf', <<EOM); +summarize_wal = on +log_min_messages = debug1 +primary_conninfo = '' +wal_retrieve_retry_interval = '500ms' +EOM +$node3->start; + +# Create a new, partially-filled WAL segment on node1. +$node1->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CREATE TABLE dummy (); +EOM +$node1->wait_for_replay_catchup($node2); + +# Record the WAL insert LSN on node1, so we can later verify that summarization on +# node3 advances past this point. +my $node1_final_lsn = $node1->safe_psql('postgres', + 'SELECT pg_current_wal_insert_lsn()'); + +# Promote node2. This creates a timeline switch that node3 must follow. +$node2->promote; +$node2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 'f';"); + +# Cause the partial segment to get archived on the *new* timeline. +# +# In more detail: the WAL segment that contains the current insert LSN exists on +# timeline 1, but since all we did is CREATE TABLE dummy (), it wasn't full. We're +# now running on timeline 2, and pg_switch_wal() fills up the rest of the segment. +# So the full segment should get archived on timeline 2, but not on timeline 1. +# We do a CHECKPOINT here to make sure that the summarizer tries to progress. +$node2->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CHECKPOINT; +EOM + +# Wait for WAL summarization on node3 to advance past the pre-promotion LSN. +# If the bug is present, the summarizer gets stuck trying to open the old +# timeline's segment file. +my $result = $node3->poll_query_until('postgres', <<EOM); +SELECT EXISTS (SELECT * FROM pg_available_wal_summaries() WHERE tli = 2) +EOM +ok($result, "WAL summarization on node3 advanced past timeline switch"); + +# Verify the absence of summaries on timeline 2 starting before the final LSN +# from timeline 1. +my $too_early_summaries = $node3->safe_psql('postgres', <<EOM); +SELECT start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn < '$node1_final_lsn' ORDER BY start_lsn +EOM +is($too_early_summaries, '', "no summaries from before LSN $node1_final_lsn"); + +# Verify the presence of summaries on timeline 2 starting at or after the final +# LSN from timeline 1. +my $summaries = $node3->safe_psql('postgres', <<EOM); +SELECT tli, start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn >= '$node1_final_lsn' ORDER BY start_lsn +EOM +my @summary_lines = split(/\n/, $summaries); +ok(@summary_lines > 0, "at least one summary from LSN $node1_final_lsn or later"); + +# We expect the new summaries to be empty, because we have not actually touched +# any block data (and we disabled autovacuum from the start). +for my $line (@summary_lines) +{ + my ($tli, $start_lsn, $end_lsn) = split(/\|/, $line); + my $filename = sprintf "%s/pg_wal/summaries/%08s%08s%08s%08s%08s.summary", + $node3->data_dir, $tli, + split(m@/@, $start_lsn), + split(m@/@, $end_lsn); + my ($stdout, $stderr) = run_command([ 'pg_walsummary', $filename ]); + is($stdout, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no blocks"); + is($stderr, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no error"); +} + +done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-14 12:40  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 2 replies; 31+ messages in thread

From: Andrey Borodin @ 2026-07-14 12:40 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: pgsql-hackers



> On 14 Jul 2026, at 01:39, Robert Haas <robertmhaas@gmail.com> wrote:
> 
> Here is a patch, with a test case.


Hi Robert!

I read the patch and I think it's correct. Two small things on the new
fallback. First, the test covers a single switch; the tricky case is several
switches within one segment, where the fallback loop and the switch_lsn bound
interact per timeline. It seems correct to me: we stop at switch_lsn, so we
only read the pre-switch bytes both timelines share. But it might be worth a
test. Second, in the fallback path WALRead reopens the segment on every page,
because the requested tli never matches seg.ws_tli once
summarizer_wal_segment_open() has moved to a descendant. These open/close
might be an exatra overhead?

I think, there's a symmetric bug on the recovery side with the same root cause.
Your patch makes the summarizer fall forward to a descendant timeline, which
looks safe. XLogFileReadAnyTLI() does the opposite: when the switch-point segment
is missing on the target timeline, it falls back to an ancestor and reads the
same segno. But that segment holds divergent data continuing old timeline!
Recovery applies it silently and then can't reach the intended timeline.

The comment you added to t/003_tli_switch.pl states the assumption that breaks
here:

  # ... recovery will read them from there and work just fine.

That holds only when the new timeline's segment is already there. Concretely,
with just two timelines: TL2 forks from TL1 in segment 67, which is archived
for TL1 but not yet for TL2. Recovery targets TL2 and asks for segment 67;
TL2's copy isn't in the archive, so XLogFileReadAnyTLI() falls back to TL1 and
hands back TL1's segment 67. Past the switch point that is the old primary's
divergent WAL, recovery applies it, and now it can never get onto TL2. The
beginseg check doesn't help here - it only skips a timeline for segments older
than that timeline's start, so nothing stops the fallback to the ancestor TL1
for the very segment where the two diverge. I reported it with a fix [0].


Regards, Andrey Borodin.

[0] https://postgr.es/m/85386EF6-16B7-4D62-86BE-526A10F93825%40yandex-team.ru (CF #6525)




^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-14 12:49  Amit Kapila <amit.kapila16@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 31+ messages in thread

From: Amit Kapila @ 2026-07-14 12:49 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: pgsql-hackers

On Tue, Jul 14, 2026 at 2:09 AM Robert Haas <robertmhaas@gmail.com> wrote:
>
> Here is a patch, with a test case.
>

I tried the patch on Windows and got following failure:

# executing test in
C:\....\postgresql\build/testrun/pg_walsummary/003_tli_switch group
pg_walsummary test 003_tli_switch
# initializing database system by copying initdb template
not ok 1 - WAL summarization on node3 advanced past timeline switch
ok 2 - no summaries from before LSN 0/04016090
not ok 3 - at least one summary from LSN 0/04016090 or later
1..3
# test failed
----------------------------------- stderr -----------------------------------
# poll_query_until timed out executing this query:
# SELECT EXISTS (SELECT * FROM pg_available_wal_summaries() WHERE tli = 2)
#
# expecting this output:
# t
# last actual query output:
# f
# with stderr:
#   Failed test 'WAL summarization on node3 advanced past timeline switch'
#   at C:/Workspace/code/postgresql/src/bin/pg_walsummary/t/003_tli_switch.pl
line 92.
#   Failed test 'at least one summary from LSN 0/04016090 or later'
#   at C:/Workspace/code/postgresql/src/bin/pg_walsummary/t/003_tli_switch.pl
line 109.
# Looks like you failed 2 tests of 3.

(test program exited with status code 2)
==============================================================================

The failure log of node-3 is attached. I'll investigate this further
and share my findings but in the meantime if you have any inputs based
on the LOG then do let me know.

-- 
With Regards,
Amit Kapila.

Attachments:

  003_tli_switch_node3.log (application/octet-stream, 482.1K) download

^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-14 13:05  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Andrey Borodin @ 2026-07-14 13:05 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; pgsql-hackers



> On 14 Jul 2026, at 17:49, Amit Kapila <amit.kapila16@gmail.com> wrote:
> 
> I tried the patch on Windows and got following failure:

Hi Amit,

Thanks for testing! That output is exactly what an unpatched summarizer produces
on my machine. I suspect the fix didn't make it into your build.
Also the test passes for me on Windows CI with the patch applied [0].

Could you double-check that you observe the failure?


Best regards, Andrey Borodin.

[0] https://github.com/x4m/postgres_g/actions/runs/29330084058/job/87076116050





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-15 06:28  Amit Kapila <amit.kapila16@gmail.com>
  parent: Andrey Borodin <x4mmm@yandex-team.ru>
  0 siblings, 1 reply; 31+ messages in thread

From: Amit Kapila @ 2026-07-15 06:28 UTC (permalink / raw)
  To: Andrey Borodin <x4mmm@yandex-team.ru>; +Cc: Robert Haas <robertmhaas@gmail.com>; pgsql-hackers

On Tue, Jul 14, 2026 at 6:35 PM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
>
> > On 14 Jul 2026, at 17:49, Amit Kapila <amit.kapila16@gmail.com> wrote:
> >
> > I tried the patch on Windows and got following failure:
>
> Hi Amit,
>
> Thanks for testing! That output is exactly what an unpatched summarizer produces
> on my machine. I suspect the fix didn't make it into your build.
> Also the test passes for me on Windows CI with the patch applied [0].
>
> Could you double-check that you observe the failure?
>

Yes. This time I tried adding some basic log in walsummarizer.c to
ensure that the test picks up new code. See
extra_debuglog_walsummary_1.txt patch atop the main patch. You can see
the node-3 LOG file (003_tli_switch_node3) attached which has this
following new LOG:
2026-07-15 10:46:56.439 IST walsummarizer[14680] DEBUG:  modified WAL
summarizer started
2026-07-15 10:46:56.440 IST walsummarizer[14680] LOG:  inside
summarizer_wal_segment_open

Is this a sufficient proof or do you think there could be something
else I am missing or messing up?

It passed on my mac but the test took a bit longer than other tests
and the additional observation that the Windows CI passed raises a
question whether this could be some sort of timing issue in the test.
Test timing on mac:
t/001_basic.pl ....... ok      349 ms ( 0.00 usr  0.00 sys +  0.04
cusr  0.03 csys =  0.07 CPU)
t/002_blocks.pl ...... ok     1464 ms ( 0.00 usr  0.00 sys +  0.09
cusr  0.31 csys =  0.40 CPU)
t/003_tli_switch.pl .. ok    13117 ms ( 0.00 usr  0.00 sys +  0.64
cusr  1.85 csys =  2.49 CPU)

Can we first rule out that this can't be a timing issue in the test case itself?

-- 
With Regards,
Amit Kapila.

Attachments:

extra_debuglog_walsummary_1.txt (text/plain, 854B) download diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c index aeee22388e7..b7846ecd756 100644 --- a/src/backend/postmaster/walsummarizer.c +++ b/src/backend/postmaster/walsummarizer.c @@ -250,7 +250,7 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) AuxiliaryProcessMainCommon(); ereport(DEBUG1, - (errmsg_internal("WAL summarizer started"))); + (errmsg_internal("modified WAL summarizer started"))); /* * Properly accept or ignore signals the postmaster might send us @@ -1600,6 +1600,9 @@ summarizer_wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID tli = *tli_p; char path[MAXPGPATH]; + /* Debugging output. */ + elog(LOG, "inside summarizer_wal_segment_open"); + for (;;) { XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize);
003_tli_switch_node3.log (application/octet-stream, 403.0K) download ^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-15 08:52  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Andrey Borodin @ 2026-07-15 08:52 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; pgsql-hackers



> On 15 Jul 2026, at 11:28, Amit Kapila <amit.kapila16@gmail.com> wrote:
> 
> Can we first rule out that this can't be a timing issue in the test case itself?

Thanks! That log points at the test, not the summarizer. On node3
it's "waiting for WAL to become available at 0/03000018", which
is before the switch, so recovery (and the summarizer) never gets there.
The pre-switch segment node3 needs never reaches node2's archive:
with archive_mode=on, segments node2 received only by
streaming aren't archived, and it's already gone by the time node2 is
promoted. Whether this bites depends on how much WAL precedes the
promotion, which can easily differ on Windows.

I can reproduce it locally by adding an extra WAL switch on node1
before promoting node2. It can probably be made deterministic either by
polling pg_stat_archiver before relying on the segment (as
025_stuck_on_old_timeline.pl does) or by setting archive_mode=always on
node2 (I would expect it to be a bit faster).


Best regards, Andrey Borodin.





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-15 14:15  Robert Haas <robertmhaas@gmail.com>
  parent: Andrey Borodin <x4mmm@yandex-team.ru>
  0 siblings, 2 replies; 31+ messages in thread

From: Robert Haas @ 2026-07-15 14:15 UTC (permalink / raw)
  To: Andrey Borodin <x4mmm@yandex-team.ru>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Wed, Jul 15, 2026 at 4:52 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
> I can reproduce it locally by adding an extra WAL switch on node1
> before promoting node2. It can probably be made deterministic either by
> polling pg_stat_archiver before relying on the segment (as
> 025_stuck_on_old_timeline.pl does) or by setting archive_mode=always on
> node2 (I would expect it to be a bit faster).

archive_mode=always seems like the correct fix. Here's v2.

-- 
Robert Haas
EDB: http://www.enterprisedb.com

Attachments:

v2-0001-Prevent-walsummarizer-from-getting-stuck-at-a-tim.patch (application/octet-stream, 16.7K) download From 1bfceb3982e9c1600187d824f9c776494185d91d Mon Sep 17 00:00:00 2001 From: Robert Haas <rhaas@postgresql.org> Date: Wed, 15 Jul 2026 10:06:06 -0400 Subject: [PATCH v2] Prevent walsummarizer from getting stuck at a timeline switch. As previously coded, walsummarizer only wants to read WAL from a file where the TimeLineID in the filename exactly matches the TimeLineID being summarized. But in some cases, when a timeline switch occurs, the WAL file from the old timeline is not archived, because it's never completely filled, so the only way to obtain the contents of that last partial segment is to read from the first segment on the new timeline. Teach WAL summarizer to do that, and add a test case to make sure that it works. Reported-by: Nick Ivanov <nick.ivanov@enterprisedb.com> --- src/backend/postmaster/walsummarizer.c | 173 ++++++++++++++++++++-- src/bin/pg_walsummary/meson.build | 1 + src/bin/pg_walsummary/t/003_tli_switch.pl | 129 ++++++++++++++++ 3 files changed, 289 insertions(+), 14 deletions(-) create mode 100644 src/bin/pg_walsummary/t/003_tli_switch.pl diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c index 4f12eaf2c85..aeee22388e7 100644 --- a/src/backend/postmaster/walsummarizer.c +++ b/src/backend/postmaster/walsummarizer.c @@ -105,6 +105,8 @@ typedef struct bool historic; XLogRecPtr read_upto; bool end_of_wal; + int num_descendant_tlis; + TimeLineID *descendant_tlis; } SummarizerReadLocalXLogPrivate; /* Pointer to shared memory state. */ @@ -156,10 +158,14 @@ int wal_summary_keep_time = 10 * HOURS_PER_DAY * MINS_PER_HOUR; static void WalSummarizerShutdown(int code, Datum arg); static XLogRecPtr GetLatestLSN(TimeLineID *tli); +static XLogRecPtr WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, + TimeLineID **descendant_tlis); static void ProcessWalSummarizerInterrupts(void); static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, XLogRecPtr switch_lsn, - XLogRecPtr maximum_lsn); + XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis); static void SummarizeDbaseRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static void SummarizeSmgrRecord(XLogReaderState *xlogreader, @@ -168,6 +174,9 @@ static void SummarizeXactRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static bool SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward); +static void summarizer_wal_segment_open(XLogReaderState *state, + XLogSegNo nextSegNo, + TimeLineID *tli_p); static int summarizer_read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, @@ -222,16 +231,19 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) * true if 'current_lsn' is known to be the start of a WAL record or WAL * segment, and false if it might be in the middle of a record someplace. * - * 'switch_lsn' and 'switch_tli', if set, are the LSN at which we need to - * switch to a new timeline and the timeline to which we need to switch. - * If not set, we either haven't figured out the answers yet or we're - * already on the latest timeline. + * 'switch_lsn', is the LSN at which we need to switch to a new timeline. + * If not set, we either haven't figured out the answer yet or we're + * already on the latest timeline. 'descendant_tlis' stores an array of + * future timeline IDs to which we know we'll need to switch, and + * 'num_descendant_tlis' is the length of that array. The first element of + * the array is the first timeline to which we will need to switch. */ XLogRecPtr current_lsn; TimeLineID current_tli; bool exact; XLogRecPtr switch_lsn = InvalidXLogRecPtr; - TimeLineID switch_tli = 0; + int num_descendant_tlis = 0; + TimeLineID *descendant_tlis = NULL; Assert(startup_data_len == 0); @@ -379,11 +391,33 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (current_tli != latest_tli && !XLogRecPtrIsValid(switch_lsn)) { List *tles = readTimeLineHistory(latest_tli); + int new_num_descendant_tlis; + TimeLineID *new_descendant_tlis; - switch_lsn = tliSwitchPoint(current_tli, tles, &switch_tli); + /* + * Make sure that the array of descendant TLIs get stored into + * TopMemoryContext. + */ + MemoryContextSwitchTo(TopMemoryContext); + switch_lsn = WalSummarizerSwitchPoint(current_tli, tles, + &new_num_descendant_tlis, + &new_descendant_tlis); + MemoryContextSwitchTo(context); + + /* + * Free any old array of descendant TLIs and install the new + * values. + */ + if (descendant_tlis != NULL) + pfree(descendant_tlis); + num_descendant_tlis = new_num_descendant_tlis; + descendant_tlis = new_descendant_tlis; + + /* Debug message. */ ereport(DEBUG1, errmsg_internal("switch point from TLI %u to TLI %u is at %X/%08X", - current_tli, switch_tli, LSN_FORMAT_ARGS(switch_lsn))); + current_tli, descendant_tlis[0], + LSN_FORMAT_ARGS(switch_lsn))); } /* @@ -394,12 +428,15 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (XLogRecPtrIsValid(switch_lsn) && current_lsn >= switch_lsn) { /* Restart summarization from switch point. */ - current_tli = switch_tli; + Assert(num_descendant_tlis > 0); + current_tli = descendant_tlis[0]; current_lsn = switch_lsn; - /* Next timeline and switch point, if any, not yet known. */ + /* Switch point, if any, and future TLIs, not yet known. */ switch_lsn = InvalidXLogRecPtr; - switch_tli = 0; + num_descendant_tlis = 0; + pfree(descendant_tlis); + descendant_tlis = NULL; /* Update (really, rewind, if needed) state in shared memory. */ LWLockAcquire(WALSummarizerLock, LW_EXCLUSIVE); @@ -415,7 +452,8 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) /* Summarize WAL. */ end_of_summary_lsn = SummarizeWAL(current_tli, current_lsn, exact, - switch_lsn, latest_lsn); + switch_lsn, latest_lsn, + num_descendant_tlis, descendant_tlis); Assert(XLogRecPtrIsValid(end_of_summary_lsn)); Assert(end_of_summary_lsn >= current_lsn); @@ -851,6 +889,62 @@ GetLatestLSN(TimeLineID *tli) } } +/* + * Compute the LSN at which we switched from current_tli to some later timeline. + * 'tles' must be the timeline history of the latest timeline. + * + * As a side effect, we set *num_descendant_tlis to the number of later TLIs that + * appear in the timeline history, and *descendant_tlis to an array of those TLIs, + * starting with immediate successor of current_tli. + */ +static XLogRecPtr +WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, TimeLineID **descendant_tlis) +{ + XLogRecPtr switch_lsn = InvalidXLogRecPtr; + int count = 0; + + /* + * Find the switch point and, at the same time, count the number of TLIs + * in this history that are descendants of that TLI. + */ + foreach_ptr(TimeLineHistoryEntry, tle, tles) + { + if (tle->tli == current_tli) + { + switch_lsn = tle->end; + break; + } + ++count; + } + + /* Sanity checks. */ + if (!XLogRecPtrIsValid(switch_lsn)) + ereport(ERROR, + (errmsg("requested timeline %u is not in this server's history", + current_tli))); + if (count == 0) + elog(ERROR, "cannot compute switch point for current TLI %u", current_tli); + + /* + * Generate an array of TLIs that are part of this history and descendants + * of current_tli. The TLE list starts with the newest timeline and works + * backward toward older timelines; we want the opposite ordering. + */ + *num_descendant_tlis = count; + *descendant_tlis = palloc_array(TimeLineID, count); + for (int i = 0; i < count; ++i) + { + TimeLineHistoryEntry *tle; + + tle = (TimeLineHistoryEntry *) list_nth(tles, count - i - 1); + (*descendant_tlis)[i] = tle->tli; + } + + /* Return value is the switchpoint. */ + return switch_lsn; +} + /* * Interrupt handler for main loop of WAL summarizer process. */ @@ -904,7 +998,8 @@ ProcessWalSummarizerInterrupts(void) */ static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, - XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn) + XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis) { SummarizerReadLocalXLogPrivate *private_data; XLogReaderState *xlogreader; @@ -922,11 +1017,13 @@ SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, private_data->tli = tli; private_data->historic = XLogRecPtrIsValid(switch_lsn); private_data->read_upto = maximum_lsn; + private_data->num_descendant_tlis = num_descendant_tlis; + private_data->descendant_tlis = descendant_tlis; /* Create xlogreader. */ xlogreader = XLogReaderAllocate(wal_segment_size, NULL, XL_ROUTINE(.page_read = &summarizer_read_local_xlog_page, - .segment_open = &wal_segment_open, + .segment_open = &summarizer_wal_segment_open, .segment_close = &wal_segment_close), private_data); if (xlogreader == NULL) @@ -1490,6 +1587,54 @@ SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward) return true; } +/* + * Similar to wal_segment_open, but checks for a file on any descendant timelines + * known to us if no file is found on the requested timeline. + */ +static void +summarizer_wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, + TimeLineID *tli_p) +{ + SummarizerReadLocalXLogPrivate *private_data = state->private_data; + int count = 0; + TimeLineID tli = *tli_p; + char path[MAXPGPATH]; + + for (;;) + { + XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize); + state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY); + if (state->seg.ws_file >= 0) + { + *tli_p = tli; + return; + } + + /* + * If the error is anything other than file-not-found, complain at + * once. + */ + if (errno != ENOENT) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open file \"%s\": %m", + path))); + + /* Try other timelines, if any remain. */ + if (count >= private_data->num_descendant_tlis) + break; + tli = private_data->descendant_tlis[count]; + ++count; + } + + /* Complain about the originally requested filename. */ + XLogFilePath(path, *tli_p, nextSegNo, state->segcxt.ws_segsize); + ereport(ERROR, + (errcode_for_file_access(), + errmsg("requested WAL segment %s has already been removed", + path))); +} + /* * Similar to read_local_xlog_page, but limited to read from one particular * timeline. If the end of WAL is reached, it will wait for more if reading diff --git a/src/bin/pg_walsummary/meson.build b/src/bin/pg_walsummary/meson.build index d012275402b..839b644ef23 100644 --- a/src/bin/pg_walsummary/meson.build +++ b/src/bin/pg_walsummary/meson.build @@ -25,6 +25,7 @@ tests += { 'tests': [ 't/001_basic.pl', 't/002_blocks.pl', + 't/003_tli_switch.pl', ], } } diff --git a/src/bin/pg_walsummary/t/003_tli_switch.pl b/src/bin/pg_walsummary/t/003_tli_switch.pl new file mode 100644 index 00000000000..739ca22a5ab --- /dev/null +++ b/src/bin/pg_walsummary/t/003_tli_switch.pl @@ -0,0 +1,129 @@ +# Copyright (c) 2021-2026, PostgreSQL Global Development Group +# +# In the original version of the WAL summarizer code, we were only willing +# to read WAL for a given TLI from a file with that exact TLI encoded into +# the filename. This could result in WAL summarization running on an archiving +# standby getting stuck. +# +# The reason for the problem is that when a new primary is promoted, the +# partial file that ends the old timeline is renamed, giving it a ".partial" +# suffix, and is not archived. That's not a problem for recovery, because +# the bytes that appear at the start of that segment will be copied into the +# first segment on the new timeline, and recovery will read them from there +# and work just fine. Because the WAL summarizer was unwilling to do the same +# thing, it got stuck. This test aims to validate that this bug has been fixed. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# Set up node1 as primary. +my $node1 = PostgreSQL::Test::Cluster->new('node1'); +$node1->init(allows_streaming => 1); +$node1->append_conf('postgresql.conf', <<EOM); +autovacuum = off +EOM +$node1->start; + +# Set up node2 as a standby for node1. Use archive_mode=always, to make sure it +# archives both before and after promotion. +$node1->backup('backup1'); +my $node2 = PostgreSQL::Test::Cluster->new('node2'); +$node2->init_from_backup($node1, 'backup1', has_streaming => 1); +$node2->enable_archiving(); +$node2->append_conf('postgresql.conf', <<EOM); +archive_mode = always +EOM +$node2->start; + +# Wait for node2 to catch up. +$node1->wait_for_replay_catchup($node2); + +# Set up node3 as a standby for node2. To get the desired behavior, we need a few +# configuration changes here. First, we must enable summarization on the new node, +# since that's what we want to test. We also set log_min_messages = debug1 since +# WAL summarization prints a bunch of diagnostics at that level that may be useful +# in case this test fails. Second, we must clear primary_conninfo, so that it can +# only obtain WAL from the archive. Finally, we lower wal_retrieve_retry_interval +# to avoid long, unnecessary waits while running the test. +$node2->backup('backup2'); +my $node3 = PostgreSQL::Test::Cluster->new('node3'); +$node3->init_from_backup($node2, 'backup2', has_restoring => 1); +$node3->append_conf('postgresql.conf', <<EOM); +summarize_wal = on +log_min_messages = debug1 +primary_conninfo = '' +wal_retrieve_retry_interval = '500ms' +EOM +$node3->start; + +# Create a new, partially-filled WAL segment on node1. +$node1->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CREATE TABLE dummy (); +EOM +$node1->wait_for_replay_catchup($node2); + +# Record the WAL insert LSN on node1, so we can later verify that summarization on +# node3 advances past this point. +my $node1_final_lsn = $node1->safe_psql('postgres', + 'SELECT pg_current_wal_insert_lsn()'); + +# Promote node2. This creates a timeline switch that node3 must follow. +$node2->promote; +$node2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 'f';"); + +# Cause the partial segment to get archived on the *new* timeline. +# +# In more detail: the WAL segment that contains the current insert LSN exists on +# timeline 1, but since all we did is CREATE TABLE dummy (), it wasn't full. We're +# now running on timeline 2, and pg_switch_wal() fills up the rest of the segment. +# So the full segment should get archived on timeline 2, but not on timeline 1. +# We do a CHECKPOINT here to make sure that the summarizer tries to progress. +$node2->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CHECKPOINT; +EOM + +# Wait for WAL summarization on node3 to advance past the pre-promotion LSN. +# If the bug is present, the summarizer gets stuck trying to open the old +# timeline's segment file. +my $result = $node3->poll_query_until('postgres', <<EOM); +SELECT EXISTS (SELECT * FROM pg_available_wal_summaries() WHERE tli = 2) +EOM +ok($result, "WAL summarization on node3 advanced past timeline switch"); + +# Verify the absence of summaries on timeline 2 starting before the final LSN +# from timeline 1. +my $too_early_summaries = $node3->safe_psql('postgres', <<EOM); +SELECT start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn < '$node1_final_lsn' ORDER BY start_lsn +EOM +is($too_early_summaries, '', "no summaries from before LSN $node1_final_lsn"); + +# Verify the presence of summaries on timeline 2 starting at or after the final +# LSN from timeline 1. +my $summaries = $node3->safe_psql('postgres', <<EOM); +SELECT tli, start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn >= '$node1_final_lsn' ORDER BY start_lsn +EOM +my @summary_lines = split(/\n/, $summaries); +ok(@summary_lines > 0, "at least one summary from LSN $node1_final_lsn or later"); + +# We expect the new summaries to be empty, because we have not actually touched +# any block data (and we disabled autovacuum from the start). +for my $line (@summary_lines) +{ + my ($tli, $start_lsn, $end_lsn) = split(/\|/, $line); + my $filename = sprintf "%s/pg_wal/summaries/%08s%08s%08s%08s%08s.summary", + $node3->data_dir, $tli, + split(m@/@, $start_lsn), + split(m@/@, $end_lsn); + my ($stdout, $stderr) = run_command([ 'pg_walsummary', $filename ]); + is($stdout, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no blocks"); + is($stderr, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no error"); +} + +done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-15 17:42  Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  parent: Andrey Borodin <x4mmm@yandex-team.ru>
  1 sibling, 1 reply; 31+ messages in thread

From: Srinath Reddy Sadipiralla @ 2026-07-15 17:42 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

Hi,

i have looked into the patch and it LGTM , will also look into the test.

a nitpick in the 003_tli_switch.pl file the comment says
"....giving it a ".partial" suffix, and is not archived," but AFAIK,
We do archive the .partial files right? CleanupAfterArchiveRecovery
renames and notifies the archiver, or am I reading it wrong?

On Tue, Jul 14, 2026 at 6:11 PM Andrey Borodin <x4mmm@yandex-team.ru> wrote:

>
>
> I think, there's a symmetric bug on the recovery side with the same root
> cause.
> Your patch makes the summarizer fall forward to a descendant timeline,
> which
> looks safe. XLogFileReadAnyTLI() does the opposite: when the switch-point
> segment
> is missing on the target timeline, it falls back to an ancestor and reads
> the
> same segno. But that segment holds divergent data continuing old timeline!
> Recovery applies it silently and then can't reach the intended timeline.
>
> The comment you added to t/003_tli_switch.pl states the assumption that
> breaks
> here:
>
>   # ... recovery will read them from there and work just fine.
>
> That holds only when the new timeline's segment is already there.
> Concretely,
> with just two timelines: TL2 forks from TL1 in segment 67, which is
> archived
> for TL1 but not yet for TL2. Recovery targets TL2 and asks for segment 67;
> TL2's copy isn't in the archive, so XLogFileReadAnyTLI() falls back to TL1
> and
> hands back TL1's segment 67. Past the switch point that is the old
> primary's
> divergent WAL, recovery applies it, and now it can never get onto TL2. The
> beginseg check doesn't help here - it only skips a timeline for segments
> older
> than that timeline's start, so nothing stops the fallback to the ancestor
> TL1
> for the very segment where the two diverge.
>
+1


-- 
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/

^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-15 20:16  Robert Haas <robertmhaas@gmail.com>
  parent: Andrey Borodin <x4mmm@yandex-team.ru>
  1 sibling, 0 replies; 31+ messages in thread

From: Robert Haas @ 2026-07-15 20:16 UTC (permalink / raw)
  To: Andrey Borodin <x4mmm@yandex-team.ru>; +Cc: pgsql-hackers

On Tue, Jul 14, 2026 at 8:41 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
> It seems correct to me: we stop at switch_lsn, so we
> only read the pre-switch bytes both timelines share. But it might be worth a
> test.

I don't think I'm sufficiently motivated to want to write a TAP test
for two timeline switches in the same segment. If you want to try it,
feel free. We can add that in a later commit; it doesn't need to be
part of this patch.

> Second, in the fallback path WALRead reopens the segment on every page,
> because the requested tli never matches seg.ws_tli once
> summarizer_wal_segment_open() has moved to a descendant. These open/close
> might be an exatra overhead?

I can believe this might be the case, and I'll look into fixing it. I
don't think it makes any practical difference because segments
containing timeline switches are rare and only contain so many blocks,
and opening and closing files is not that expensive. But it makes
sense to get this right.

> I think, there's a symmetric bug on the recovery side with the same root cause.
> Your patch makes the summarizer fall forward to a descendant timeline, which
> looks safe. XLogFileReadAnyTLI() does the opposite: when the switch-point segment
> is missing on the target timeline, it falls back to an ancestor and reads the
> same segno. But that segment holds divergent data continuing old timeline!
> Recovery applies it silently and then can't reach the intended timeline.

I think this is only a problem if somebody reads past the switchpoint.
In any case, this thread is not about fixing bugs in
XLogFileReadAnyTLI() or its callers.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-15 20:18  Robert Haas <robertmhaas@gmail.com>
  parent: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
  0 siblings, 2 replies; 31+ messages in thread

From: Robert Haas @ 2026-07-15 20:18 UTC (permalink / raw)
  To: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Wed, Jul 15, 2026 at 1:43 PM Srinath Reddy Sadipiralla
<srinath2133@gmail.com> wrote:
> a nitpick in the 003_tli_switch.pl file the comment says
> "....giving it a ".partial" suffix, and is not archived," but AFAIK,
> We do archive the .partial files right? CleanupAfterArchiveRecovery
> renames and notifies the archiver, or am I reading it wrong?

You're right. I'll reword the comment.

> +1

I think this is all a digression from the problem at hand. I
understand Andrey's probable desire to have me review his patch on
that thread, but I think whatever is going on there is only
tangentially related to this problem.

-- 
Robert Haas
EDB: http://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 05:49  Amit Kapila <amit.kapila16@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 31+ messages in thread

From: Amit Kapila @ 2026-07-16 05:49 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Andrey Borodin <x4mmm@yandex-team.ru>; pgsql-hackers

On Wed, Jul 15, 2026 at 7:46 PM Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Wed, Jul 15, 2026 at 4:52 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
> > I can reproduce it locally by adding an extra WAL switch on node1
> > before promoting node2. It can probably be made deterministic either by
> > polling pg_stat_archiver before relying on the segment (as
> > 025_stuck_on_old_timeline.pl does) or by setting archive_mode=always on
> > node2 (I would expect it to be a bit faster).
>
> archive_mode=always seems like the correct fix. Here's v2.
>

Thanks for the updated patch, it works for me.

-- 
With Regards,
Amit Kapila.





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 06:05  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 31+ messages in thread

From: Andrey Borodin @ 2026-07-16 06:05 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers



> On 16 Jul 2026, at 01:18, Robert Haas <robertmhaas@gmail.com> wrote:
> 
> 
> understand Andrey's probable desire to have me review his patch on
> that thread, but I think whatever is going on there is only
> tangentially related to this problem.

Of course I'd like that fix committed too :) But that's not why I'm raising it here.

+# The reason for the problem is that when a new primary is promoted, the
+# partial file that ends the old timeline is renamed, giving it a ".partial"
+# suffix, and is not archived. That's not a problem for recovery, because
+# the bytes that appear at the start of that segment will be copied into the
+# first segment on the new timeline, and recovery will read them from there
+# and work just fine.

That only holds when the new timeline's segment is already available. If it isn't,
XLogFileReadAnyTLI() falls back to the ancestor's segment and, past the switch point,
hands recovery the old timeline's divergent WAL. It's the mirror, on the recovery
side, of what your patch fixes for the summarizer.

I'm not asking you to fix XLogFileReadAnyTLI() here. I just don't think the new
comment should claim recovery is unaffected.


Best regards, Andrey Borodin.





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* RE: walsummarizer can get stuck when switching timelines
@ 2026-07-16 06:31  Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 31+ messages in thread

From: Zhijie Hou (Fujitsu) @ 2026-07-16 06:31 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers; Andrey Borodin <x4mmm@yandex-team.ru>

On Wednesday, July 15, 2026 10:16 PM Robert Haas <robertmhaas@gmail.com> wrote:
> On Wed, Jul 15, 2026 at 4:52 AM Andrey Borodin <x4mmm@yandex-
> team.ru> wrote:
> > I can reproduce it locally by adding an extra WAL switch on node1
> > before promoting node2. It can probably be made deterministic either
> > by polling pg_stat_archiver before relying on the segment (as
> > 025_stuck_on_old_timeline.pl does) or by setting archive_mode=always
> > on
> > node2 (I would expect it to be a bit faster).
> 
> archive_mode=always seems like the correct fix. Here's v2.

While reading the WAL summarization code, I ran the new 003_tli_switch test and
noticed it takes about 14 seconds to finish on my machine, which prompted me to
debug it a bit. The delay comes from the 10-second wait in the error recovery
path (WAIT_EVENT_WAL_SUMMARIZER_ERROR) in WalSummarizerMain, where it retries
after failing to read an unarchived WAL file.

I was wondering whether it's worth improving this. We could enable summarize_wal
on node3 only after the WALs on the new timeline become readable on node3, which
would eliminate the retry and reduce the test time by about 10 seconds on my
machine. However, if the intention is to exercise the retry logic in
WalSummarizerMain as well, the current test is fine as is. Just sharing this in
case the test time wasn't intentional.

Apart from the test, the fix looks good to me.

Best Regards,
Hou zj


^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 11:46  Thom Brown <thom@linux.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 1 reply; 31+ messages in thread

From: Thom Brown @ 2026-07-16 11:46 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Wed, 15 Jul 2026 at 21:19, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Wed, Jul 15, 2026 at 1:43 PM Srinath Reddy Sadipiralla
> <srinath2133@gmail.com> wrote:
> > a nitpick in the 003_tli_switch.pl file the comment says
> > "....giving it a ".partial" suffix, and is not archived," but AFAIK,
> > We do archive the .partial files right? CleanupAfterArchiveRecovery
> > renames and notifies the archiver, or am I reading it wrong?
>
> You're right. I'll reword the comment.
>
> > +1
>
> I think this is all a digression from the problem at hand. I
> understand Andrey's probable desire to have me review his patch on
> that thread, but I think whatever is going on there is only
> tangentially related to this problem.

+# Cause the partial segment to get archived on the *new* timeline.
+#
+# In more detail: the WAL segment that contains the current insert
LSN exists on
+# timeline 1, but since all we did is CREATE TABLE dummy (), it
wasn't full. We're
+# now running on timeline 2, and pg_switch_wal() fills up the rest of
the segment.
+# So the full segment should get archived on timeline 2, but not on timeline 1.
+# We do a CHECKPOINT here to make sure that the summarizer tries to progress.
+$node2->safe_psql('postgres', <<EOM);
+SELECT pg_switch_wal();
+CHECKPOINT;

Wouldn't we want the checkpoint's redo record to make it into the
archived segment *before* switching wal?

Thom





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 12:19  Robert Haas <robertmhaas@gmail.com>
  parent: Andrey Borodin <x4mmm@yandex-team.ru>
  0 siblings, 1 reply; 31+ messages in thread

From: Robert Haas @ 2026-07-16 12:19 UTC (permalink / raw)
  To: Andrey Borodin <x4mmm@yandex-team.ru>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Thu, Jul 16, 2026 at 2:05 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
> Of course I'd like that fix committed too :) But that's not why I'm raising it here.
>
> +# The reason for the problem is that when a new primary is promoted, the
> +# partial file that ends the old timeline is renamed, giving it a ".partial"
> +# suffix, and is not archived. That's not a problem for recovery, because
> +# the bytes that appear at the start of that segment will be copied into the
> +# first segment on the new timeline, and recovery will read them from there
> +# and work just fine.
>
> That only holds when the new timeline's segment is already available. If it isn't,
> XLogFileReadAnyTLI() falls back to the ancestor's segment and, past the switch point,
> hands recovery the old timeline's divergent WAL. It's the mirror, on the recovery
> side, of what your patch fixes for the summarizer.
>
> I'm not asking you to fix XLogFileReadAnyTLI() here. I just don't think the new
> comment should claim recovery is unaffected.

In the scenario tested by this test case, recovery works fine. Without
the patch, node3 follows the timeline switch from TLI 1 to TLI 2 and
continues recovery thereafter without a problem. Only WAL
summarization gets stuck. Maybe I need to go read your thread to
figure out why you think these are the same problem, but based on what
the test case does, I feel like they are different problems.

-- 
Robert Haas
EDB: http://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 12:39  Robert Haas <robertmhaas@gmail.com>
  parent: Thom Brown <thom@linux.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Robert Haas @ 2026-07-16 12:39 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Thu, Jul 16, 2026 at 7:46 AM Thom Brown <thom@linux.com> wrote:
> +# Cause the partial segment to get archived on the *new* timeline.
> +#
> +# In more detail: the WAL segment that contains the current insert
> LSN exists on
> +# timeline 1, but since all we did is CREATE TABLE dummy (), it
> wasn't full. We're
> +# now running on timeline 2, and pg_switch_wal() fills up the rest of
> the segment.
> +# So the full segment should get archived on timeline 2, but not on timeline 1.
> +# We do a CHECKPOINT here to make sure that the summarizer tries to progress.
> +$node2->safe_psql('postgres', <<EOM);
> +SELECT pg_switch_wal();
> +CHECKPOINT;
>
> Wouldn't we want the checkpoint's redo record to make it into the
> archived segment *before* switching wal?

I don't think so, but maybe you want to explain why you think so.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 12:58  Thom Brown <thom@linux.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Thom Brown @ 2026-07-16 12:58 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Thu, 16 Jul 2026 at 13:39, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Thu, Jul 16, 2026 at 7:46 AM Thom Brown <thom@linux.com> wrote:
> > +# Cause the partial segment to get archived on the *new* timeline.
> > +#
> > +# In more detail: the WAL segment that contains the current insert
> > LSN exists on
> > +# timeline 1, but since all we did is CREATE TABLE dummy (), it
> > wasn't full. We're
> > +# now running on timeline 2, and pg_switch_wal() fills up the rest of
> > the segment.
> > +# So the full segment should get archived on timeline 2, but not on timeline 1.
> > +# We do a CHECKPOINT here to make sure that the summarizer tries to progress.
> > +$node2->safe_psql('postgres', <<EOM);
> > +SELECT pg_switch_wal();
> > +CHECKPOINT;
> >
> > Wouldn't we want the checkpoint's redo record to make it into the
> > archived segment *before* switching wal?
>
> I don't think so, but maybe you want to explain why you think so.

Well if we run pg_switch_wal(), we're effectively closing the current
segment. CHECKPOINT then emits its WAL after the switch. If the
summarizer needs a CHECKPOINT_REDO record in the segment being
archived, it would already be too late. I guess it works if the
checkpoint triggered by promotion always happens before
pg_switch_wal(), but it seems like it could just as well happen
afterwrds. If so, that would make the test depend on timing.

I could be misunderstanding the intended purpose here, though. It just
looked to me like CHECKPOINT; SELECT pg_switch_wal(); would be
deterministic, whereas the current ordering appears to rely on the
promotion checkpoint winning the race.

Or maybe I need to rethink after some caffeine.

Thom






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 13:45  Robert Haas <robertmhaas@gmail.com>
  parent: Thom Brown <thom@linux.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Robert Haas @ 2026-07-16 13:45 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Thu, Jul 16, 2026 at 8:59 AM Thom Brown <thom@linux.com> wrote:
> Well if we run pg_switch_wal(), we're effectively closing the current
> segment. CHECKPOINT then emits its WAL after the switch. If the
> summarizer needs a CHECKPOINT_REDO record in the segment being
> archived, it would already be too late.

OK, I think this is where we're seeing things differently. The
summarizer doesn't need a CHECKPOINT_REDO record in the segment being
archived. Rather, we need a CHECKPOINT_REDO record somewhere after the
WAL that we want summarized. In this case, the WAL we want summarized
is generated by the pg_switch_wal() call.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-16 13:46  Thom Brown <thom@linux.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Thom Brown @ 2026-07-16 13:46 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Thu, 16 Jul 2026 at 14:45, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Thu, Jul 16, 2026 at 8:59 AM Thom Brown <thom@linux.com> wrote:
> > Well if we run pg_switch_wal(), we're effectively closing the current
> > segment. CHECKPOINT then emits its WAL after the switch. If the
> > summarizer needs a CHECKPOINT_REDO record in the segment being
> > archived, it would already be too late.
>
> OK, I think this is where we're seeing things differently. The
> summarizer doesn't need a CHECKPOINT_REDO record in the segment being
> archived. Rather, we need a CHECKPOINT_REDO record somewhere after the
> WAL that we want summarized. In this case, the WAL we want summarized
> is generated by the pg_switch_wal() call.

Ah, gotcha. Sorry for the noise.

Thom






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-17 16:21  Thom Brown <thom@linux.com>
  parent: Thom Brown <thom@linux.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Thom Brown @ 2026-07-17 16:21 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Thu, 16 Jul 2026 at 14:46, Thom Brown <thom@linux.com> wrote:
>
> On Thu, 16 Jul 2026 at 14:45, Robert Haas <robertmhaas@gmail.com> wrote:
> >
> > On Thu, Jul 16, 2026 at 8:59 AM Thom Brown <thom@linux.com> wrote:
> > > Well if we run pg_switch_wal(), we're effectively closing the current
> > > segment. CHECKPOINT then emits its WAL after the switch. If the
> > > summarizer needs a CHECKPOINT_REDO record in the segment being
> > > archived, it would already be too late.
> >
> > OK, I think this is where we're seeing things differently. The
> > summarizer doesn't need a CHECKPOINT_REDO record in the segment being
> > archived. Rather, we need a CHECKPOINT_REDO record somewhere after the
> > WAL that we want summarized. In this case, the WAL we want summarized
> > is generated by the pg_switch_wal() call.
>
> Ah, gotcha. Sorry for the noise.

Another question; I'm seeing this in 003_tli_switch_node3.log:

2026-07-17 16:57:50.525 BST walsummarizer[714073] DEBUG:  timeline 1
became historic, can read up to 0/0301E118
2026-07-17 16:57:50.525 BST walsummarizer[714073] ERROR:  requested
WAL segment pg_wal/000000010000000000000003 has already been removed
2026-07-17 16:58:00.533 BST walsummarizer[714073] DEBUG:  switch point
from TLI 1 to TLI 2 is at 0/0301E118
2026-07-17 16:58:00.534 BST walsummarizer[714073] DEBUG:  summarized
WAL on TLI 1 from 0/02000028 to 0/0301E118
2026-07-17 16:58:00.534 BST walsummarizer[714073] DEBUG:  summarized
WAL on TLI 2 from 0/0301E118 to 0/0301E150

It's erroring out, but shouldn't it check for 000000020000000000000003
before doing so? It wasn't removed, just renamed.

Thom






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-17 19:02  Robert Haas <robertmhaas@gmail.com>
  parent: Thom Brown <thom@linux.com>
  0 siblings, 0 replies; 31+ messages in thread

From: Robert Haas @ 2026-07-17 19:02 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; x4mmm@yandex-team.ru, Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Fri, Jul 17, 2026 at 12:22 PM Thom Brown <thom@linux.com> wrote:
> It's erroring out, but shouldn't it check for 000000020000000000000003
> before doing so? It wasn't removed, just renamed.

Actually, neither is the case. 000000010000000000000003 was not
archived. 000000020000000000000003 is a different file with partially
identical contents. But the fact that the existing error message here
is not quite right is not a problem this patch should be trying to
solve.

-- 
Robert Haas
EDB: http://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-18 18:29  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 0 replies; 31+ messages in thread

From: Andrey Borodin @ 2026-07-18 18:29 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers



> On 16 Jul 2026, at 17:19, Robert Haas <robertmhaas@gmail.com> wrote:
> 
> In the scenario tested by this test case, recovery works fine. Without
> the patch, node3 follows the timeline switch from TLI 1 to TLI 2 and
> continues recovery thereafter without a problem. Only WAL
> summarization gets stuck. Maybe I need to go read your thread to
> figure out why you think these are the same problem, but based on what
> the test case does, I feel like they are different problems.

I toyed a bit with your test and it is safe as long as node1 has is own
archive. So yes, technically there's no problem.

When node3 and node1 has shared archive some write activity triggers
problematic behavior.

PFA demo test to illustrate this. First step is your v1 patch intact.
Step 2 is test change to trigger the problem.

Anyway, this happens only when nodes have common archive.


Best regards, Andrey Borodin.

Attachments: download all (2 files, .tar.gz)

vAB1-0001-Prevent-walsummarizer-from-getting-stuck-at-a-t.patch (application/octet-stream, 16.5K) download From afbbae9b1ddf91b411310eb3a98ac8ab0ba31387 Mon Sep 17 00:00:00 2001 From: Robert Haas <rhaas@postgresql.org> Date: Mon, 13 Jul 2026 16:33:57 -0400 Subject: [PATCH vAB1 1/2] Prevent walsummarizer from getting stuck at a timeline switch. As previously coded, walsummarizer only wants to read WAL from a file where the TimeLineID in the filename exactly matches the TimeLineID being summarized. But in some cases, when a timeline switch occurs, the WAL file from the old timeline is not archived, because it's never completely filled, so the only way to obtain the contents of that last partial segment is to read from the first segment on the new timeline. Teach WAL summarizer to do that, and add a test case to make sure that it works. Reported-by: Nick Ivanov <nick.ivanov@enterprisedb.com> --- src/backend/postmaster/walsummarizer.c | 173 ++++++++++++++++++++-- src/bin/pg_walsummary/meson.build | 1 + src/bin/pg_walsummary/t/003_tli_switch.pl | 125 ++++++++++++++++ 3 files changed, 285 insertions(+), 14 deletions(-) create mode 100644 src/bin/pg_walsummary/t/003_tli_switch.pl diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c index 4f12eaf2c85..aeee22388e7 100644 --- a/src/backend/postmaster/walsummarizer.c +++ b/src/backend/postmaster/walsummarizer.c @@ -105,6 +105,8 @@ typedef struct bool historic; XLogRecPtr read_upto; bool end_of_wal; + int num_descendant_tlis; + TimeLineID *descendant_tlis; } SummarizerReadLocalXLogPrivate; /* Pointer to shared memory state. */ @@ -156,10 +158,14 @@ int wal_summary_keep_time = 10 * HOURS_PER_DAY * MINS_PER_HOUR; static void WalSummarizerShutdown(int code, Datum arg); static XLogRecPtr GetLatestLSN(TimeLineID *tli); +static XLogRecPtr WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, + TimeLineID **descendant_tlis); static void ProcessWalSummarizerInterrupts(void); static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, XLogRecPtr switch_lsn, - XLogRecPtr maximum_lsn); + XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis); static void SummarizeDbaseRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static void SummarizeSmgrRecord(XLogReaderState *xlogreader, @@ -168,6 +174,9 @@ static void SummarizeXactRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static bool SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward); +static void summarizer_wal_segment_open(XLogReaderState *state, + XLogSegNo nextSegNo, + TimeLineID *tli_p); static int summarizer_read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, @@ -222,16 +231,19 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) * true if 'current_lsn' is known to be the start of a WAL record or WAL * segment, and false if it might be in the middle of a record someplace. * - * 'switch_lsn' and 'switch_tli', if set, are the LSN at which we need to - * switch to a new timeline and the timeline to which we need to switch. - * If not set, we either haven't figured out the answers yet or we're - * already on the latest timeline. + * 'switch_lsn', is the LSN at which we need to switch to a new timeline. + * If not set, we either haven't figured out the answer yet or we're + * already on the latest timeline. 'descendant_tlis' stores an array of + * future timeline IDs to which we know we'll need to switch, and + * 'num_descendant_tlis' is the length of that array. The first element of + * the array is the first timeline to which we will need to switch. */ XLogRecPtr current_lsn; TimeLineID current_tli; bool exact; XLogRecPtr switch_lsn = InvalidXLogRecPtr; - TimeLineID switch_tli = 0; + int num_descendant_tlis = 0; + TimeLineID *descendant_tlis = NULL; Assert(startup_data_len == 0); @@ -379,11 +391,33 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (current_tli != latest_tli && !XLogRecPtrIsValid(switch_lsn)) { List *tles = readTimeLineHistory(latest_tli); + int new_num_descendant_tlis; + TimeLineID *new_descendant_tlis; - switch_lsn = tliSwitchPoint(current_tli, tles, &switch_tli); + /* + * Make sure that the array of descendant TLIs get stored into + * TopMemoryContext. + */ + MemoryContextSwitchTo(TopMemoryContext); + switch_lsn = WalSummarizerSwitchPoint(current_tli, tles, + &new_num_descendant_tlis, + &new_descendant_tlis); + MemoryContextSwitchTo(context); + + /* + * Free any old array of descendant TLIs and install the new + * values. + */ + if (descendant_tlis != NULL) + pfree(descendant_tlis); + num_descendant_tlis = new_num_descendant_tlis; + descendant_tlis = new_descendant_tlis; + + /* Debug message. */ ereport(DEBUG1, errmsg_internal("switch point from TLI %u to TLI %u is at %X/%08X", - current_tli, switch_tli, LSN_FORMAT_ARGS(switch_lsn))); + current_tli, descendant_tlis[0], + LSN_FORMAT_ARGS(switch_lsn))); } /* @@ -394,12 +428,15 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (XLogRecPtrIsValid(switch_lsn) && current_lsn >= switch_lsn) { /* Restart summarization from switch point. */ - current_tli = switch_tli; + Assert(num_descendant_tlis > 0); + current_tli = descendant_tlis[0]; current_lsn = switch_lsn; - /* Next timeline and switch point, if any, not yet known. */ + /* Switch point, if any, and future TLIs, not yet known. */ switch_lsn = InvalidXLogRecPtr; - switch_tli = 0; + num_descendant_tlis = 0; + pfree(descendant_tlis); + descendant_tlis = NULL; /* Update (really, rewind, if needed) state in shared memory. */ LWLockAcquire(WALSummarizerLock, LW_EXCLUSIVE); @@ -415,7 +452,8 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) /* Summarize WAL. */ end_of_summary_lsn = SummarizeWAL(current_tli, current_lsn, exact, - switch_lsn, latest_lsn); + switch_lsn, latest_lsn, + num_descendant_tlis, descendant_tlis); Assert(XLogRecPtrIsValid(end_of_summary_lsn)); Assert(end_of_summary_lsn >= current_lsn); @@ -851,6 +889,62 @@ GetLatestLSN(TimeLineID *tli) } } +/* + * Compute the LSN at which we switched from current_tli to some later timeline. + * 'tles' must be the timeline history of the latest timeline. + * + * As a side effect, we set *num_descendant_tlis to the number of later TLIs that + * appear in the timeline history, and *descendant_tlis to an array of those TLIs, + * starting with immediate successor of current_tli. + */ +static XLogRecPtr +WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, TimeLineID **descendant_tlis) +{ + XLogRecPtr switch_lsn = InvalidXLogRecPtr; + int count = 0; + + /* + * Find the switch point and, at the same time, count the number of TLIs + * in this history that are descendants of that TLI. + */ + foreach_ptr(TimeLineHistoryEntry, tle, tles) + { + if (tle->tli == current_tli) + { + switch_lsn = tle->end; + break; + } + ++count; + } + + /* Sanity checks. */ + if (!XLogRecPtrIsValid(switch_lsn)) + ereport(ERROR, + (errmsg("requested timeline %u is not in this server's history", + current_tli))); + if (count == 0) + elog(ERROR, "cannot compute switch point for current TLI %u", current_tli); + + /* + * Generate an array of TLIs that are part of this history and descendants + * of current_tli. The TLE list starts with the newest timeline and works + * backward toward older timelines; we want the opposite ordering. + */ + *num_descendant_tlis = count; + *descendant_tlis = palloc_array(TimeLineID, count); + for (int i = 0; i < count; ++i) + { + TimeLineHistoryEntry *tle; + + tle = (TimeLineHistoryEntry *) list_nth(tles, count - i - 1); + (*descendant_tlis)[i] = tle->tli; + } + + /* Return value is the switchpoint. */ + return switch_lsn; +} + /* * Interrupt handler for main loop of WAL summarizer process. */ @@ -904,7 +998,8 @@ ProcessWalSummarizerInterrupts(void) */ static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, - XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn) + XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis) { SummarizerReadLocalXLogPrivate *private_data; XLogReaderState *xlogreader; @@ -922,11 +1017,13 @@ SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, private_data->tli = tli; private_data->historic = XLogRecPtrIsValid(switch_lsn); private_data->read_upto = maximum_lsn; + private_data->num_descendant_tlis = num_descendant_tlis; + private_data->descendant_tlis = descendant_tlis; /* Create xlogreader. */ xlogreader = XLogReaderAllocate(wal_segment_size, NULL, XL_ROUTINE(.page_read = &summarizer_read_local_xlog_page, - .segment_open = &wal_segment_open, + .segment_open = &summarizer_wal_segment_open, .segment_close = &wal_segment_close), private_data); if (xlogreader == NULL) @@ -1490,6 +1587,54 @@ SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward) return true; } +/* + * Similar to wal_segment_open, but checks for a file on any descendant timelines + * known to us if no file is found on the requested timeline. + */ +static void +summarizer_wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, + TimeLineID *tli_p) +{ + SummarizerReadLocalXLogPrivate *private_data = state->private_data; + int count = 0; + TimeLineID tli = *tli_p; + char path[MAXPGPATH]; + + for (;;) + { + XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize); + state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY); + if (state->seg.ws_file >= 0) + { + *tli_p = tli; + return; + } + + /* + * If the error is anything other than file-not-found, complain at + * once. + */ + if (errno != ENOENT) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open file \"%s\": %m", + path))); + + /* Try other timelines, if any remain. */ + if (count >= private_data->num_descendant_tlis) + break; + tli = private_data->descendant_tlis[count]; + ++count; + } + + /* Complain about the originally requested filename. */ + XLogFilePath(path, *tli_p, nextSegNo, state->segcxt.ws_segsize); + ereport(ERROR, + (errcode_for_file_access(), + errmsg("requested WAL segment %s has already been removed", + path))); +} + /* * Similar to read_local_xlog_page, but limited to read from one particular * timeline. If the end of WAL is reached, it will wait for more if reading diff --git a/src/bin/pg_walsummary/meson.build b/src/bin/pg_walsummary/meson.build index d012275402b..839b644ef23 100644 --- a/src/bin/pg_walsummary/meson.build +++ b/src/bin/pg_walsummary/meson.build @@ -25,6 +25,7 @@ tests += { 'tests': [ 't/001_basic.pl', 't/002_blocks.pl', + 't/003_tli_switch.pl', ], } } diff --git a/src/bin/pg_walsummary/t/003_tli_switch.pl b/src/bin/pg_walsummary/t/003_tli_switch.pl new file mode 100644 index 00000000000..6258cb44643 --- /dev/null +++ b/src/bin/pg_walsummary/t/003_tli_switch.pl @@ -0,0 +1,125 @@ +# Copyright (c) 2021-2026, PostgreSQL Global Development Group +# +# In the original version of the WAL summarizer code, we were only willing +# to read WAL for a given TLI from a file with that exact TLI encoded into +# the filename. This could result in WAL summarization running on an archiving +# standby getting stuck. +# +# The reason for the problem is that when a new primary is promoted, the +# partial file that ends the old timeline is renamed, giving it a ".partial" +# suffix, and is not archived. That's not a problem for recovery, because +# the bytes that appear at the start of that segment will be copied into the +# first segment on the new timeline, and recovery will read them from there +# and work just fine. Because the WAL summarizer was unwilling to do the same +# thing, it got stuck. This test aims to validate that this bug has been fixed. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# Set up node1 as primary. +my $node1 = PostgreSQL::Test::Cluster->new('node1'); +$node1->init(allows_streaming => 1); +$node1->append_conf('postgresql.conf', <<EOM); +autovacuum = off +EOM +$node1->start; + +# Set up node2 as a standby for node1. +$node1->backup('backup1'); +my $node2 = PostgreSQL::Test::Cluster->new('node2'); +$node2->init_from_backup($node1, 'backup1', has_streaming => 1); +$node2->enable_archiving(); +$node2->start; + +# Wait for node2 to catch up. +$node1->wait_for_replay_catchup($node2); + +# Set up node3 as a standby for node2. To get the desired behavior, we need a few +# configuration changes here. First, we must enable summarization on the new node, +# since that's what we want to test. We also set log_min_messages = debug1 since +# WAL summarization prints a bunch of diagnostics at that level that may be useful +# in case this test fails. Second, we must clear primary_conninfo, so that it can +# only obtain WAL from the archive. Finally, we lower wal_retrieve_retry_interval +# to avoid long, unnecessary waits while running the test. +$node2->backup('backup2'); +my $node3 = PostgreSQL::Test::Cluster->new('node3'); +$node3->init_from_backup($node2, 'backup2', has_restoring => 1); +$node3->append_conf('postgresql.conf', <<EOM); +summarize_wal = on +log_min_messages = debug1 +primary_conninfo = '' +wal_retrieve_retry_interval = '500ms' +EOM +$node3->start; + +# Create a new, partially-filled WAL segment on node1. +$node1->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CREATE TABLE dummy (); +EOM +$node1->wait_for_replay_catchup($node2); + +# Record the WAL insert LSN on node1, so we can later verify that summarization on +# node3 advances past this point. +my $node1_final_lsn = $node1->safe_psql('postgres', + 'SELECT pg_current_wal_insert_lsn()'); + +# Promote node2. This creates a timeline switch that node3 must follow. +$node2->promote; +$node2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 'f';"); + +# Cause the partial segment to get archived on the *new* timeline. +# +# In more detail: the WAL segment that contains the current insert LSN exists on +# timeline 1, but since all we did is CREATE TABLE dummy (), it wasn't full. We're +# now running on timeline 2, and pg_switch_wal() fills up the rest of the segment. +# So the full segment should get archived on timeline 2, but not on timeline 1. +# We do a CHECKPOINT here to make sure that the summarizer tries to progress. +$node2->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CHECKPOINT; +EOM + +# Wait for WAL summarization on node3 to advance past the pre-promotion LSN. +# If the bug is present, the summarizer gets stuck trying to open the old +# timeline's segment file. +my $result = $node3->poll_query_until('postgres', <<EOM); +SELECT EXISTS (SELECT * FROM pg_available_wal_summaries() WHERE tli = 2) +EOM +ok($result, "WAL summarization on node3 advanced past timeline switch"); + +# Verify the absence of summaries on timeline 2 starting before the final LSN +# from timeline 1. +my $too_early_summaries = $node3->safe_psql('postgres', <<EOM); +SELECT start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn < '$node1_final_lsn' ORDER BY start_lsn +EOM +is($too_early_summaries, '', "no summaries from before LSN $node1_final_lsn"); + +# Verify the presence of summaries on timeline 2 starting at or after the final +# LSN from timeline 1. +my $summaries = $node3->safe_psql('postgres', <<EOM); +SELECT tli, start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn >= '$node1_final_lsn' ORDER BY start_lsn +EOM +my @summary_lines = split(/\n/, $summaries); +ok(@summary_lines > 0, "at least one summary from LSN $node1_final_lsn or later"); + +# We expect the new summaries to be empty, because we have not actually touched +# any block data (and we disabled autovacuum from the start). +for my $line (@summary_lines) +{ + my ($tli, $start_lsn, $end_lsn) = split(/\|/, $line); + my $filename = sprintf "%s/pg_wal/summaries/%08s%08s%08s%08s%08s.summary", + $node3->data_dir, $tli, + split(m@/@, $start_lsn), + split(m@/@, $end_lsn); + my ($stdout, $stderr) = run_command([ 'pg_walsummary', $filename ]); + is($stdout, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no blocks"); + is($stderr, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no error"); +} + +done_testing(); -- 2.50.1 (Apple Git-155) =
vAB1-0002-DEMO-recovery-follows-the-wrong-timeline-at-a-s.patch (application/octet-stream, 2.3K) download From ed8487c7ed456611f0b578fff6e4df4e07733869 Mon Sep 17 00:00:00 2001 From: Andrey Borodin <amborodin@acm.org> Date: Sat, 18 Jul 2026 00:09:47 +0500 Subject: [PATCH vAB1 2/2] DEMO: recovery follows the wrong timeline at a switch point --- src/bin/pg_walsummary/t/003_tli_switch.pl | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/bin/pg_walsummary/t/003_tli_switch.pl b/src/bin/pg_walsummary/t/003_tli_switch.pl index 6258cb44643..883a2676189 100644 --- a/src/bin/pg_walsummary/t/003_tli_switch.pl +++ b/src/bin/pg_walsummary/t/003_tli_switch.pl @@ -34,6 +34,11 @@ $node2->init_from_backup($node1, 'backup1', has_streaming => 1); $node2->enable_archiving(); $node2->start; +# node1 is never fenced and shares node2's WAL archive. +$node1->append_conf('postgresql.conf', + "archive_mode = on\narchive_command = 'cp \"%p\" \"" . $node2->archive_dir . "/%f\"'"); +$node1->restart; + # Wait for node2 to catch up. $node1->wait_for_replay_catchup($node2); @@ -71,6 +76,25 @@ my $node1_final_lsn = $node1->safe_psql('postgres', $node2->promote; $node2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 'f';"); +# node3 adopts timeline 2, then node1 (still on timeline 1) completes the switch +# segment with divergent WAL; timeline 2's copy is not archived yet, so recovery +# falls back to node1's segment and applies the divergent WAL. +$node3->wait_for_log(qr/new target timeline is 2/); +$node1->safe_psql('postgres', + 'CREATE TABLE divergent_only (); SELECT pg_switch_wal();'); +$node3->poll_query_until('postgres', + "SELECT to_regclass('divergent_only') IS NOT NULL"); +is( $node3->safe_psql( + 'postgres', + "SELECT count(*) FROM pg_class WHERE relname = 'divergent_only'"), + '0', 'node3 must not apply divergent WAL from the old timeline'); + +# We fail above because of the recovery bug. The rest is the original +# summarizer checks, kept verbatim but disabled: once recovery has diverged node3 +# never reaches timeline 2. +if (0) +{ + # Cause the partial segment to get archived on the *new* timeline. # # In more detail: the WAL segment that contains the current insert LSN exists on @@ -122,4 +146,6 @@ for my $line (@summary_lines) is($stderr, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no error"); } +} + done_testing(); -- 2.50.1 (Apple Git-155) =
^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-22 14:51  Robert Haas <robertmhaas@gmail.com>
  parent: Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Robert Haas @ 2026-07-22 14:51 UTC (permalink / raw)
  To: Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers; Andrey Borodin <x4mmm@yandex-team.ru>

On Thu, Jul 16, 2026 at 2:31 AM Zhijie Hou (Fujitsu)
<houzj.fnst@fujitsu.com> wrote:
> I was wondering whether it's worth improving this. We could enable summarize_wal
> on node3 only after the WALs on the new timeline become readable on node3, which
> would eliminate the retry and reduce the test time by about 10 seconds on my
> machine. However, if the intention is to exercise the retry logic in
> WalSummarizerMain as well, the current test is fine as is. Just sharing this in
> case the test time wasn't intentional.

This is a good suggestion, thanks.

Here is v3.

-- 
Robert Haas
EDB: http://www.enterprisedb.com

Attachments:

v3-0001-Prevent-walsummarizer-from-getting-stuck-at-a-tim.patch (application/octet-stream, 17.7K) download From 57439ed173507d6d6f7e7a663bbb976a61347371 Mon Sep 17 00:00:00 2001 From: Robert Haas <rhaas@postgresql.org> Date: Wed, 22 Jul 2026 10:35:51 -0400 Subject: [PATCH v3] Prevent walsummarizer from getting stuck at a timeline switch. As previously coded, walsummarizer only wants to read WAL from a file where the TimeLineID in the filename exactly matches the TimeLineID being summarized. But in some cases, when a timeline switch occurs, the WAL file from the old timeline is not archived, because it's never completely filled, so the only way to obtain the contents of that last partial segment is to read from the first segment on the new timeline. Teach WAL summarizer to do that, and add a test case to make sure that it works. Reported-by: Nick Ivanov <nick.ivanov@enterprisedb.com> Reviewed-by: Andrey Borodin <x4mmm@yandex-team.ru> Tested-by: Amit Kapila <amit.kapila16@gmail.com> Reviewed-by: Srinath Reddy Sadipiralla <srinath2133@gmail.com> Reviewed-by: Zhijie Hou <houzj.fnst@fujitsu.com> Reviewed-by: Thom Brown <thom@linux.com> Discussion: http://postgr.es/m/CA+Tgmobr27GpKDZx3_ezW2+C5_g18i+jSK3sGF_cR-_ESv5N5A@mail.gmail.com --- src/backend/postmaster/walsummarizer.c | 173 ++++++++++++++++++++-- src/bin/pg_walsummary/meson.build | 1 + src/bin/pg_walsummary/t/003_tli_switch.pl | 146 ++++++++++++++++++ 3 files changed, 306 insertions(+), 14 deletions(-) create mode 100644 src/bin/pg_walsummary/t/003_tli_switch.pl diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c index 8b429cb51d7..ff246b07a21 100644 --- a/src/backend/postmaster/walsummarizer.c +++ b/src/backend/postmaster/walsummarizer.c @@ -105,6 +105,8 @@ typedef struct bool historic; XLogRecPtr read_upto; bool end_of_wal; + int num_descendant_tlis; + TimeLineID *descendant_tlis; } SummarizerReadLocalXLogPrivate; /* Pointer to shared memory state. */ @@ -156,10 +158,14 @@ int wal_summary_keep_time = 10 * HOURS_PER_DAY * MINS_PER_HOUR; static void WalSummarizerShutdown(int code, Datum arg); static XLogRecPtr GetLatestLSN(TimeLineID *tli); +static XLogRecPtr WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, + TimeLineID **descendant_tlis); static void ProcessWalSummarizerInterrupts(void); static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, XLogRecPtr switch_lsn, - XLogRecPtr maximum_lsn); + XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis); static void SummarizeDbaseRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static void SummarizeSmgrRecord(XLogReaderState *xlogreader, @@ -168,6 +174,9 @@ static void SummarizeXactRecord(XLogReaderState *xlogreader, BlockRefTable *brtab); static bool SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward); +static void summarizer_wal_segment_open(XLogReaderState *state, + XLogSegNo nextSegNo, + TimeLineID *tli_p); static int summarizer_read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, @@ -222,16 +231,19 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) * true if 'current_lsn' is known to be the start of a WAL record or WAL * segment, and false if it might be in the middle of a record someplace. * - * 'switch_lsn' and 'switch_tli', if set, are the LSN at which we need to - * switch to a new timeline and the timeline to which we need to switch. - * If not set, we either haven't figured out the answers yet or we're - * already on the latest timeline. + * 'switch_lsn', is the LSN at which we need to switch to a new timeline. + * If not set, we either haven't figured out the answer yet or we're + * already on the latest timeline. 'descendant_tlis' stores an array of + * future timeline IDs to which we know we'll need to switch, and + * 'num_descendant_tlis' is the length of that array. The first element of + * the array is the first timeline to which we will need to switch. */ XLogRecPtr current_lsn; TimeLineID current_tli; bool exact; XLogRecPtr switch_lsn = InvalidXLogRecPtr; - TimeLineID switch_tli = 0; + int num_descendant_tlis = 0; + TimeLineID *descendant_tlis = NULL; Assert(startup_data_len == 0); @@ -380,11 +392,33 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (current_tli != latest_tli && !XLogRecPtrIsValid(switch_lsn)) { List *tles = readTimeLineHistory(latest_tli); + int new_num_descendant_tlis; + TimeLineID *new_descendant_tlis; - switch_lsn = tliSwitchPoint(current_tli, tles, &switch_tli); + /* + * Make sure that the array of descendant TLIs get stored into + * TopMemoryContext. + */ + MemoryContextSwitchTo(TopMemoryContext); + switch_lsn = WalSummarizerSwitchPoint(current_tli, tles, + &new_num_descendant_tlis, + &new_descendant_tlis); + MemoryContextSwitchTo(context); + + /* + * Free any old array of descendant TLIs and install the new + * values. + */ + if (descendant_tlis != NULL) + pfree(descendant_tlis); + num_descendant_tlis = new_num_descendant_tlis; + descendant_tlis = new_descendant_tlis; + + /* Debug message. */ ereport(DEBUG1, errmsg_internal("switch point from TLI %u to TLI %u is at %X/%08X", - current_tli, switch_tli, LSN_FORMAT_ARGS(switch_lsn))); + current_tli, descendant_tlis[0], + LSN_FORMAT_ARGS(switch_lsn))); } /* @@ -395,12 +429,15 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) if (XLogRecPtrIsValid(switch_lsn) && current_lsn >= switch_lsn) { /* Restart summarization from switch point. */ - current_tli = switch_tli; + Assert(num_descendant_tlis > 0); + current_tli = descendant_tlis[0]; current_lsn = switch_lsn; - /* Next timeline and switch point, if any, not yet known. */ + /* Switch point, if any, and future TLIs, not yet known. */ switch_lsn = InvalidXLogRecPtr; - switch_tli = 0; + num_descendant_tlis = 0; + pfree(descendant_tlis); + descendant_tlis = NULL; /* Update (really, rewind, if needed) state in shared memory. */ LWLockAcquire(WALSummarizerLock, LW_EXCLUSIVE); @@ -417,7 +454,8 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) maximum_lsn = XLogRecPtrIsValid(switch_lsn) ? switch_lsn : latest_lsn; end_of_summary_lsn = SummarizeWAL(current_tli, current_lsn, exact, - switch_lsn, maximum_lsn); + switch_lsn, maximum_lsn, + num_descendant_tlis, descendant_tlis); Assert(XLogRecPtrIsValid(end_of_summary_lsn)); Assert(end_of_summary_lsn >= current_lsn); @@ -853,6 +891,62 @@ GetLatestLSN(TimeLineID *tli) } } +/* + * Compute the LSN at which we switched from current_tli to some later timeline. + * 'tles' must be the timeline history of the latest timeline. + * + * As a side effect, we set *num_descendant_tlis to the number of later TLIs that + * appear in the timeline history, and *descendant_tlis to an array of those TLIs, + * starting with immediate successor of current_tli. + */ +static XLogRecPtr +WalSummarizerSwitchPoint(TimeLineID current_tli, List *tles, + int *num_descendant_tlis, TimeLineID **descendant_tlis) +{ + XLogRecPtr switch_lsn = InvalidXLogRecPtr; + int count = 0; + + /* + * Find the switch point and, at the same time, count the number of TLIs + * in this history that are descendants of that TLI. + */ + foreach_ptr(TimeLineHistoryEntry, tle, tles) + { + if (tle->tli == current_tli) + { + switch_lsn = tle->end; + break; + } + ++count; + } + + /* Sanity checks. */ + if (!XLogRecPtrIsValid(switch_lsn)) + ereport(ERROR, + (errmsg("requested timeline %u is not in this server's history", + current_tli))); + if (count == 0) + elog(ERROR, "cannot compute switch point for current TLI %u", current_tli); + + /* + * Generate an array of TLIs that are part of this history and descendants + * of current_tli. The TLE list starts with the newest timeline and works + * backward toward older timelines; we want the opposite ordering. + */ + *num_descendant_tlis = count; + *descendant_tlis = palloc_array(TimeLineID, count); + for (int i = 0; i < count; ++i) + { + TimeLineHistoryEntry *tle; + + tle = (TimeLineHistoryEntry *) list_nth(tles, count - i - 1); + (*descendant_tlis)[i] = tle->tli; + } + + /* Return value is the switchpoint. */ + return switch_lsn; +} + /* * Interrupt handler for main loop of WAL summarizer process. */ @@ -906,7 +1000,8 @@ ProcessWalSummarizerInterrupts(void) */ static XLogRecPtr SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, - XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn) + XLogRecPtr switch_lsn, XLogRecPtr maximum_lsn, + int num_descendant_tlis, TimeLineID *descendant_tlis) { SummarizerReadLocalXLogPrivate *private_data; XLogReaderState *xlogreader; @@ -924,11 +1019,13 @@ SummarizeWAL(TimeLineID tli, XLogRecPtr start_lsn, bool exact, private_data->tli = tli; private_data->historic = XLogRecPtrIsValid(switch_lsn); private_data->read_upto = maximum_lsn; + private_data->num_descendant_tlis = num_descendant_tlis; + private_data->descendant_tlis = descendant_tlis; /* Create xlogreader. */ xlogreader = XLogReaderAllocate(wal_segment_size, NULL, XL_ROUTINE(.page_read = &summarizer_read_local_xlog_page, - .segment_open = &wal_segment_open, + .segment_open = &summarizer_wal_segment_open, .segment_close = &wal_segment_close), private_data); if (xlogreader == NULL) @@ -1492,6 +1589,54 @@ SummarizeXlogRecord(XLogReaderState *xlogreader, bool *new_fast_forward) return true; } +/* + * Similar to wal_segment_open, but checks for a file on any descendant timelines + * known to us if no file is found on the requested timeline. + */ +static void +summarizer_wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, + TimeLineID *tli_p) +{ + SummarizerReadLocalXLogPrivate *private_data = state->private_data; + int count = 0; + TimeLineID tli = *tli_p; + char path[MAXPGPATH]; + + for (;;) + { + XLogFilePath(path, tli, nextSegNo, state->segcxt.ws_segsize); + state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY); + if (state->seg.ws_file >= 0) + { + *tli_p = tli; + return; + } + + /* + * If the error is anything other than file-not-found, complain at + * once. + */ + if (errno != ENOENT) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open file \"%s\": %m", + path))); + + /* Try other timelines, if any remain. */ + if (count >= private_data->num_descendant_tlis) + break; + tli = private_data->descendant_tlis[count]; + ++count; + } + + /* Complain about the originally requested filename. */ + XLogFilePath(path, *tli_p, nextSegNo, state->segcxt.ws_segsize); + ereport(ERROR, + (errcode_for_file_access(), + errmsg("requested WAL segment %s has already been removed", + path))); +} + /* * Similar to read_local_xlog_page, but limited to read from one particular * timeline. If the end of WAL is reached, it will wait for more if reading diff --git a/src/bin/pg_walsummary/meson.build b/src/bin/pg_walsummary/meson.build index d012275402b..839b644ef23 100644 --- a/src/bin/pg_walsummary/meson.build +++ b/src/bin/pg_walsummary/meson.build @@ -25,6 +25,7 @@ tests += { 'tests': [ 't/001_basic.pl', 't/002_blocks.pl', + 't/003_tli_switch.pl', ], } } diff --git a/src/bin/pg_walsummary/t/003_tli_switch.pl b/src/bin/pg_walsummary/t/003_tli_switch.pl new file mode 100644 index 00000000000..810d27d908e --- /dev/null +++ b/src/bin/pg_walsummary/t/003_tli_switch.pl @@ -0,0 +1,146 @@ +# Copyright (c) 2021-2026, PostgreSQL Global Development Group +# +# In the original version of the WAL summarizer code, we were only willing +# to read WAL for a given TLI from a file with that exact TLI encoded into +# the filename. This could result in WAL summarization running on an archiving +# standby getting stuck. +# +# The reason for the problem is that when a new primary is promoted, the +# partial file that ends the old timeline is renamed, giving it a ".partial" +# suffix, meaning that it will be ignored by both recovery and by the WAL +# summarizer. The bytes that appear at the start of that segment will be copied +# into the first segment on the new timeline, and recovery was able to read +# them from there and work as expected. However, the WAL summarizer was +# unwilling to do the same thing, so it got stuck. This test aims to validate +# that this bug has been fixed. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# Set up node1 as primary. +my $node1 = PostgreSQL::Test::Cluster->new('node1'); +$node1->init(allows_streaming => 1); +$node1->append_conf('postgresql.conf', <<EOM); +autovacuum = off +EOM +$node1->start; + +# Set up node2 as a standby for node1. Use archive_mode=always, to make sure it +# archives both before and after promotion. +$node1->backup('backup1'); +my $node2 = PostgreSQL::Test::Cluster->new('node2'); +$node2->init_from_backup($node1, 'backup1', has_streaming => 1); +$node2->enable_archiving(); +$node2->append_conf('postgresql.conf', <<EOM); +archive_mode = always +EOM +$node2->start; + +# Wait for node2 to catch up. +$node1->wait_for_replay_catchup($node2); + +# Set up node3 as a standby for node2. We want it to fetch WAL only from the +# archive, so we clear primary_conninfo. We don't want long delays during the +# test, so we reduce wal_retrieve_retry_interval. We also don't want it to try +# to archive anything to node2's archive, but at the same time, we don't want +# it to remove WAL before we enable WAL summarization. To accomplish that, we +# set archive_command to the empty string. +$node2->backup('backup2'); +my $node3 = PostgreSQL::Test::Cluster->new('node3'); +$node3->init_from_backup($node2, 'backup2', has_restoring => 1); +$node3->append_conf('postgresql.conf', <<EOM); +primary_conninfo = '' +wal_retrieve_retry_interval = '500ms' +archive_command = '' +EOM +$node3->start; + +# Create a new, partially-filled WAL segment on node1. +$node1->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CREATE TABLE dummy (); +EOM +$node1->wait_for_replay_catchup($node2); + +# Record the WAL insert LSN on node1, so we can later verify that summarization +# on node3 advances past this point. +my $node1_final_lsn = $node1->safe_psql('postgres', + 'SELECT pg_current_wal_insert_lsn()'); + +# Promote node2. This creates a timeline switch that node3 must follow. +$node2->promote; +$node2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 'f';"); + +# Cause the partial segment to get archived on the *new* timeline. +# +# In more detail: the WAL segment that contains the current insert LSN exists +# on timeline 1, but since all we did is CREATE TABLE dummy (), it wasn't full. +# We're now running on timeline 2, and pg_switch_wal() fills up the rest of the +# segment. So the full segment should get archived on timeline 2, but not on +# timeline 1. We do a CHECKPOINT here to make sure that the summarizer tries +# to progress. +$node2->safe_psql('postgres', <<EOM); +SELECT pg_switch_wal(); +CHECKPOINT; +EOM + +# Wait until replay has reached TLI 2 on node3, and then start the WAL +# summarizer. If node3 is started with the summarizer already enabled, then +# it may try to fetch the partial segment from timeline 1 before it learns +# about timeline 2. If that happens, it will error out, wait 10 seconds, and +# retry, slowing down the test. This avoids that. +# +# We set log_min_messages=debug1 at the same time we enable WAL summarization +# so that we get useful debug messages if there's any problem. +$node3->poll_query_until('postgres', + "SELECT replay_end_tli = 2 FROM pg_stat_get_recovery()") + or die "TLI 2 not reached on node3"; +$node3->append_conf('postgresql.conf', <<EOM); +summarize_wal = on +log_min_messages = debug1 +EOM +$node3->reload; + +# Wait for WAL summarization on node3 to advance past the pre-promotion LSN. +# If the bug is present, the summarizer gets stuck trying to open the old +# timeline's segment file. +my $result = $node3->poll_query_until('postgres', <<EOM); +SELECT EXISTS (SELECT * FROM pg_available_wal_summaries() WHERE tli = 2) +EOM +ok($result, "WAL summarization on node3 advanced past timeline switch"); + +# Verify the absence of summaries on timeline 2 starting before the final LSN +# from timeline 1. +my $too_early_summaries = $node3->safe_psql('postgres', <<EOM); +SELECT start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn < '$node1_final_lsn' ORDER BY start_lsn +EOM +is($too_early_summaries, '', "no summaries from before LSN $node1_final_lsn"); + +# Verify the presence of summaries on timeline 2 starting at or after the final +# LSN from timeline 1. +my $summaries = $node3->safe_psql('postgres', <<EOM); +SELECT tli, start_lsn, end_lsn FROM pg_available_wal_summaries() +WHERE tli = 2 AND start_lsn >= '$node1_final_lsn' ORDER BY start_lsn +EOM +my @summary_lines = split(/\n/, $summaries); +ok(@summary_lines > 0, "at least one summary from LSN $node1_final_lsn or later"); + +# We expect the new summaries to be empty, because we have not actually touched +# any block data (and we disabled autovacuum from the start). +for my $line (@summary_lines) +{ + my ($tli, $start_lsn, $end_lsn) = split(/\|/, $line); + my $filename = sprintf "%s/pg_wal/summaries/%08s%08s%08s%08s%08s.summary", + $node3->data_dir, $tli, + split(m@/@, $start_lsn), + split(m@/@, $end_lsn); + my ($stdout, $stderr) = run_command([ 'pg_walsummary', $filename ]); + is($stdout, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no blocks"); + is($stderr, '', "pg_walsummary TLI $tli $start_lsn-$end_lsn: no error"); +} + +done_testing(); -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-07-31 16:55  Robert Haas <robertmhaas@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Robert Haas @ 2026-07-31 16:55 UTC (permalink / raw)
  To: Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers; Andrey Borodin <x4mmm@yandex-team.ru>

On Wed, Jul 22, 2026 at 10:51 AM Robert Haas <robertmhaas@gmail.com> wrote:
> This is a good suggestion, thanks.
>
> Here is v3.

It took me way longer than I was hoping to find the time to get this
committed and back-patched, but I have now done so. The test case
required some adjustments for v17 and v18.

Yours truly from the depths of a very deep hole,

-- 
Robert Haas
EDB: http://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-08-02 16:00  Alexander Lakhin <exclusion@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Alexander Lakhin @ 2026-08-02 16:00 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers; Andrey Borodin <x4mmm@yandex-team.ru>

Hello Robert,

31.07.2026 19:55, Robert Haas wrote:
> It took me way longer than I was hoping to find the time to get this
> committed and back-patched, but I have now done so. The test case
> required some adjustments for v17 and v18.

Buildfarm animal sidewinder managed to fail the new test 003_tli_switch.pl,
[1]:
### Promoting node "node2"
# Running: pg_ctl --pgdata 
/home/pgbf/buildroot/REL_19_STABLE/pgsql.build/src/bin/pg_walsummary/tmp_check/t_003_tli_switch_node2_data/pgdata --log 
/home/pgbf/buildroot/REL_19_STABLE/pgsql.build/src/bin/pg_walsummary/tmp_check/log/003_tli_switch_node2.log promote
waiting for server to promote.... done
server promoted
### Reloading node "node3"
# Running: pg_ctl --pgdata 
/home/pgbf/buildroot/REL_19_STABLE/pgsql.build/src/bin/pg_walsummary/tmp_check/t_003_tli_switch_node3_data/pgdata reload
server signaled
[23:03:08.443](215.681s) # poll_query_until timed out executing this query:
# SELECT EXISTS (SELECT * FROM pg_available_wal_summaries() WHERE tli = 2)
#
# expecting this output:
# t
# last actual query output:
# f
# with stderr:
[23:03:08.444](0.001s) not ok 1 - WAL summarization on node3 advanced past timeline switch
[23:03:08.445](0.001s)
[23:03:08.445](0.000s) #   Failed test 'WAL summarization on node3 advanced past timeline switch'
#   at t/003_tli_switch.pl line 113.

003_tli_switch_node3.log contains:
2026-08-01 22:59:41.862 CEST [25416:2] DEBUG:  switch point from TLI 1 to TLI 2 is at 0/0301DBE8
2026-08-01 22:59:41.864 CEST [25416:3] DEBUG:  summarized WAL on TLI 1 from 0/02000028 to 0/0301DBE8
2026-08-01 22:59:41.865 CEST [4231:1] [unknown] LOG:  connection received: host=[local]
2026-08-01 22:59:41.866 CEST [4231:2] [unknown] LOG:  connection authenticated: user="pgbf" method=trust 
(/home/pgbf/buildroot/REL_19_STABLE/pgsql.build/src/bin/pg_walsummary/tmp_check/t_003_tli_switch_node3_data/pgdata/pg_hba.conf:117)
2026-08-01 22:59:41.866 CEST [4231:3] [unknown] LOG:  connection authorized: user=pgbf database=postgres 
application_name=003_tli_switch.pl
cp: 
/home/pgbf/buildroot/REL_19_STABLE/pgsql.build/src/bin/pg_walsummary/tmp_check/t_003_tli_switch_node2_data/archives/00000003.history: 
No such file or directory
2026-08-01 22:59:41.867 CEST [22705:14] LOG:  waiting for WAL to become available at 0/04000018
2026-08-01 22:59:41.867 CEST [4231:4] 003_tli_switch.pl LOG: statement: SELECT EXISTS (SELECT * FROM 
pg_available_wal_summaries() WHERE tli = 2)
...
2026-08-01 23:03:08.336 CEST [222:4] 003_tli_switch.pl LOG: statement: SELECT EXISTS (SELECT * FROM 
pg_available_wal_summaries() WHERE tli = 2)
2026-08-01 23:03:08.338 CEST [222:5] 003_tli_switch.pl LOG: disconnection: session time: 0:00:00.006 user=pgbf 
database=postgres host=[local]
cp: 
/home/pgbf/buildroot/REL_19_STABLE/pgsql.build/src/bin/pg_walsummary/tmp_check/t_003_tli_switch_node2_data/archives/000000020000000000000004: 
No such file or directory
cp: 
/home/pgbf/buildroot/REL_19_STABLE/pgsql.build/src/bin/pg_walsummary/tmp_check/t_003_tli_switch_node2_data/archives/00000003.history: 
No such file or directory
2026-08-01 23:03:08.407 CEST [22705:419] LOG:  waiting for WAL to become available at 0/04000018

003_tli_switch_node2.log:
2026-08-01 22:59:41.062 CEST [11464:4] 003_tli_switch.pl LOG: statement: SELECT pg_switch_wal();
2026-08-01 22:59:41.129 CEST [18094:4] LOG:  database system is ready to accept connections
2026-08-01 22:59:41.204 CEST [14948:1] LOG:  checkpoint starting: force
2026-08-01 22:59:41.205 CEST [11464:5] 003_tli_switch.pl LOG: statement: CHECKPOINT;
2026-08-01 22:59:41.426 CEST [14948:2] LOG:  checkpoint complete: force: wrote 21 buffers (16.4%), wrote 3 SLRU buffers; 
0 WAL file(s) added, 0 removed, 0 recycled; write=0.043 s, sync=0.001 s, total=0.302 s; sync files=0, longest=0.000 s, 
average=0.000 s; distance=32768 kB, estimate=32768 kB; lsn=0/04000088, redo lsn=0/04000028
2026-08-01 22:59:41.426 CEST [14948:3] LOG:  checkpoint starting: fast force wait
2026-08-01 22:59:41.434 CEST [14948:4] LOG:  checkpoint complete: fast force wait: wrote 0 buffers (0.0%), wrote 0 SLRU 
buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.001 s, sync=0.001 s, total=0.009 s; sync files=0, 
longest=0.000 s, average=0.000 s; distance=0 kB, estimate=29491 kB; lsn=0/04000168, redo lsn=0/04000108
2026-08-01 22:59:41.471 CEST [11464:6] 003_tli_switch.pl LOG: disconnection: session time: 0:00:00.411 user=pgbf 
database=postgres host=[local]
(both redo_lsn belong to segment 4)

vs the previous successful run [2]:
003_tli_switch_node2.log
2026-08-01 00:55:39.071 CEST [965:4] 003_tli_switch.pl LOG: statement: SELECT pg_switch_wal();
2026-08-01 00:55:39.241 CEST [965:5] 003_tli_switch.pl LOG: statement: CHECKPOINT;
2026-08-01 00:55:39.727 CEST [15172:2] LOG:  checkpoint complete: force: wrote 21 buffers (16.4%), wrote 3 SLRU buffers; 
0 WAL file(s) added, 0 removed, 0 recycled; write=0.318 s, sync=0.001 s, total=0.813 s; sync files=0, longest=0.000 s, 
average=0.000 s; distance=16502 kB, estimate=16502 kB; lsn=0/04000060, redo lsn=0/0301DC20
2026-08-01 00:55:39.727 CEST [15172:3] LOG:  checkpoint starting: fast force wait
2026-08-01 00:55:39.747 CEST [15172:4] LOG:  checkpoint complete: fast force wait: wrote 0 buffers (0.0%), wrote 0 SLRU 
buffers; 0 WAL file(s) added, 0 removed, 1 recycled; write=0.001 s, sync=0.001 s, total=0.020 s; sync files=0, 
longest=0.000 s, average=0.000 s; distance=16265 kB, estimate=16479 kB; lsn=0/04000140, redo lsn=0/040000E0
(the first redo_lsn belongs to segment 3)

So it looks like the test might fail when the checkpoint record slips into
segment 4. I've reproduced the failure with:
inline patch 1: src/backend/access/transam/xlog.c (+1/-0 lines) download inline-1.patch--- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -7448,2 +7448,3 @@ CreateCheckPoint(int flags)         INJECTION_POINT_LOAD("create-checkpoint-run"); +pg_usleep(1000000);
PROVE_TESTS="t/003*" make -s check -C src/bin/pg_walsummary/ # +++ tap check in src/bin/pg_walsummary +++ t/003_tli_switch.pl .. # poll_query_until timed out executing this query: # SELECT EXISTS (SELECT * FROM pg_available_wal_summaries() WHERE tli = 2) # # expecting this output: # t # last actual query output: # f # with stderr: t/003_tli_switch.pl .. 1/? #   Failed test 'WAL summarization on node3 advanced past timeline switch' #   at t/003_tli_switch.pl line 113. Could you please have a look? [1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=sidewinder&dt=2026-08-01%2020%3A35%3A00 [2] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=sidewinder&dt=2026-07-31%2022%3A35%3A00 Best regards, Alexander ^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-08-03 09:16  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Alexander Lakhin <exclusion@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Andrey Borodin @ 2026-08-03 09:16 UTC (permalink / raw)
  To: Alexander Lakhin <exclusion@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers



> On 2 Aug 2026, at 21:00, Alexander Lakhin <exclusion@gmail.com> wrote:
> 
> So it looks like the test might fail when the checkpoint record slips into
> segment 4.


I think swapping two SQL statements would be enough:

 $node2->safe_psql('postgres', <<EOM);
-SELECT pg_switch_wal();
 CHECKPOINT;
+SELECT pg_switch_wal();
 EOM

The CHECKPOINT is what gives the summarizer a redo point to close the
timeline-2 summary at, and node3 only ever reads completed segments from
the archive, so it has to be before pg_switch_wal().

CI shows no problems with this change to me.


Best regards, Andrey Borodin.






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-08-10 18:20  Robert Haas <robertmhaas@gmail.com>
  parent: Andrey Borodin <x4mmm@yandex-team.ru>
  0 siblings, 1 reply; 31+ messages in thread

From: Robert Haas @ 2026-08-10 18:20 UTC (permalink / raw)
  To: Andrey Borodin <x4mmm@yandex-team.ru>; +Cc: Alexander Lakhin <exclusion@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

On Mon, Aug 3, 2026 at 5:16 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:
> I think swapping two SQL statements would be enough:
>
>  $node2->safe_psql('postgres', <<EOM);
> -SELECT pg_switch_wal();
>  CHECKPOINT;
> +SELECT pg_switch_wal();
>  EOM

Thanks to both of you for the analysis, and apologies for the slow
response. Here's a patch. I think the tricky part is justifying the
change, which I at least find counterintuitive (else I would have done
it right to begin with!). The attached patch attempts to explain via a
lengthy comment.

-- 
Robert Haas
EDB: http://www.enterprisedb.com

Attachments:

v1-0001-003_tli_switch.pl-Adjust-command-order-to-avoid-p.patch (application/octet-stream, 2.2K) download From c5a1e6079706bd11757e7025e15a2397eb63585f Mon Sep 17 00:00:00 2001 From: Robert Haas <rhaas@postgresql.org> Date: Mon, 10 Aug 2026 14:17:15 -0400 Subject: [PATCH v1] 003_tli_switch.pl: Adjust command order to avoid possible hang. Reported-by: Alexander Lakhin <exclusion@gmail.com> Analyzed-by: Alexander Lakhin <exclusion@gmail.com> Analyzed-by: Andrey Borodin <x4mmm@yandex-team.ru> --- src/bin/pg_walsummary/t/003_tli_switch.pl | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/bin/pg_walsummary/t/003_tli_switch.pl b/src/bin/pg_walsummary/t/003_tli_switch.pl index 810d27d908e..cc3eaedb74d 100644 --- a/src/bin/pg_walsummary/t/003_tli_switch.pl +++ b/src/bin/pg_walsummary/t/003_tli_switch.pl @@ -80,11 +80,22 @@ $node2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 'f';"); # on timeline 1, but since all we did is CREATE TABLE dummy (), it wasn't full. # We're now running on timeline 2, and pg_switch_wal() fills up the rest of the # segment. So the full segment should get archived on timeline 2, but not on -# timeline 1. We do a CHECKPOINT here to make sure that the summarizer tries -# to progress. +# timeline 1. +# +# However, we need to make sure that we fill up the current WAL segment *after* +# node2 completes the asynchronous checkpoint triggered by promotion. If we do, +# the segment containing the XLOG_CHECKPOINT_REDO record from the promotion +# checkpoint is guaranteed to be archived, enabling node3 to generate a summary +# file on timeline 2. If we don't, there won't be anything to ensure that the +# segment containing the XLOG_CHECKPOINT_REDO record ever fills up, +# so it will never be archived, node3 won't see it, and the test will hang. +# The easiest way to make sure that the right thing happens is to run another +# CHECKPOINT command before switching WAL segments. That will wait until the +# preceding checkpoint finishes, if it is still in progress, and then run +# another one, which won't hurt anything. $node2->safe_psql('postgres', <<EOM); -SELECT pg_switch_wal(); CHECKPOINT; +SELECT pg_switch_wal(); EOM # Wait until replay has reached TLI 2 on node3, and then start the WAL -- 2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-08-17 11:00  Alexander Lakhin <exclusion@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Alexander Lakhin @ 2026-08-17 11:00 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; Andrey Borodin <x4mmm@yandex-team.ru>; +Cc: Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

Hello Robert and Andrey,

10.08.2026 21:20, Robert Haas wrote:
> Thanks to both of you for the analysis, and apologies for the slow
> response. Here's a patch. I think the tricky part is justifying the
> change, which I at least find counterintuitive (else I would have done
> it right to begin with!). The attached patch attempts to explain via a
> lengthy comment.

Thank you for paying attention to that test defect!

Meanwhile, other buildfarm animal, morepork, was lucky enough to reveal
one more issue, thanks to its timings: [1], [2].
[01:07:53.816](18.983s) ok 1 - WAL summarization on node3 advanced past timeline switch
[01:07:53.830](0.014s) not ok 2 - no summaries from before LSN 0/0301DC20
[01:07:53.831](0.000s)
[01:07:53.831](0.000s) #   Failed test 'no summaries from before LSN 0/0301DC20'
#   at t/003_tli_switch.pl line 121.
[01:07:53.831](0.000s) #          got: '0/0301DBE8|0/0301DC20'
#     expected: ''
[01:07:53.843](0.012s) not ok 3 - at least one summary from LSN 0/0301DC20 or later
[01:07:53.843](0.000s)
[01:07:53.843](0.000s) #   Failed test 'at least one summary from LSN 0/0301DC20 or later'
#   at t/003_tli_switch.pl line 130.

003_tli_switch_node1.log
2026-08-15 01:07:37.126 CEST [68231:1] LOG:  starting PostgreSQL 19beta3 on x86_64-unknown-openbsd6.9, compiled by 
OpenBSD clang version 10.0.1 , 64-bit
...
2026-08-15 01:07:51.657 CEST [9984:4] 003_tli_switch.pl LOG: statement: SELECT pg_switch_wal();
2026-08-15 01:07:51.658 CEST [9984:5] 003_tli_switch.pl LOG: statement: CREATE TABLE dummy ();
..
2026-08-15 01:07:52.200 CEST [4172:4] 003_tli_switch.pl LOG: statement: SELECT pg_current_wal_flush_lsn()
...
2026-08-15 01:07:52.226 CEST [72425:4] 003_tli_switch.pl LOG: statement: SELECT pg_current_wal_insert_lsn()

That is, ~15 seconds passed from the server start to the pg_current_wal_insert_lsn()
call. So I guess, the test failed due to bgwriter's LogStandbySnapshot. I
could reproduce such a failure locally with:
inline patch 1: src/backend/postmaster/bgwriter.c (+2/-2 lines) download inline-1.patch--- a/src/backend/postmaster/bgwriter.c +++ b/src/backend/postmaster/bgwriter.c @@ -70,3 +70,3 @@ int            BgWriterDelay = 200;   */ -#define LOG_SNAPSHOT_INTERVAL_MS 15000 +#define LOG_SNAPSHOT_INTERVAL_MS 1 @@ -308,3 +308,3 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len)                         WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, -                       BgWriterDelay /* ms */ , WAIT_EVENT_BGWRITER_MAIN); +                       1 /* ms */ , WAIT_EVENT_BGWRITER_MAIN);
make -s check -C src/bin/pg_walsummary # +++ tap check in src/bin/pg_walsummary +++ t/001_basic.pl ....... ok t/002_blocks.pl ...... ok t/003_tli_switch.pl .. 1/? #   Failed test 'no summaries from before LSN 0/0401DD28' #   at t/003_tli_switch.pl line 121. #          got: '0/0401DCF0|0/0401DD28' #     expected: '' #   Failed test 'at least one summary from LSN 0/0401DD28 or later' #   at t/003_tli_switch.pl line 130. # Looks like you failed 2 tests of 3. t/003_tli_switch.pl .. Dubious, test returned 2 (wstat 512, 0x200) Failed 2/3 subtests Test Summary Report ------------------- t/003_tli_switch.pl (Wstat: 512 (exited 2) Tests: 3 Failed: 2)   Failed tests:  2-3   Non-zero exit status: 2 Files=3, Tests=22,  3 wallclock secs ( 0.01 usr  0.00 sys +  0.21 cusr  0.38 csys =  0.60 CPU) Result: FAIL (Basic check-world passes with this change for me.) Could you please look at this anomaly too? [1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=morepork&dt=2026-08-12%2018%3A51%3A34 [2] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=morepork&dt=2026-08-14%2022%3A32%3A27 Best regards, Alexander ^ permalink raw reply [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-08-20 18:43  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Alexander Lakhin <exclusion@gmail.com>
  0 siblings, 1 reply; 31+ messages in thread

From: Andrey Borodin @ 2026-08-20 18:43 UTC (permalink / raw)
  To: Alexander Lakhin <exclusion@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

Hi Alexander,

On Mon, Aug 17, 2026 at 11:00 AM Alexander Lakhin wrote:
> So I guess, the test failed due to bgwriter's LogStandbySnapshot.

I think you are right. The test records node1_final_lsn after waiting
for node2 to catch up. Any WAL generated on node1 between those two
operations can therefore move node1_final_lsn past the point from which
node2 is later promoted.

Perhaps we should instead obtain the LSN together with the operation
whose WAL we want node2 to replay, and only then wait for catchup:

my $node1_final_lsn = $node1->safe_psql('postgres', <<EOM);
CREATE TABLE dummy ();
SELECT pg_current_wal_insert_lsn();
EOM
$node1->wait_for_replay_catchup($node2);

This way node1_final_lsn identifies the position immediately after the
test's own pre-promotion WAL, and wait_for_replay_catchup() guarantees
that node2 has replayed at least that far. Any WAL generated on node1
afterwards can no longer move the reference point past node2's fork
point.

WDYT?

Thank you!

Best regards, Andrey Borodin.







^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-08-21 16:00  Alexander Lakhin <exclusion@gmail.com>
  parent: Andrey Borodin <x4mmm@yandex-team.ru>
  0 siblings, 1 reply; 31+ messages in thread

From: Alexander Lakhin @ 2026-08-21 16:00 UTC (permalink / raw)
  To: Andrey Borodin <x4mmm@yandex-team.ru>; +Cc: Robert Haas <robertmhaas@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

Hi Andrey,

20.08.2026 21:43, Andrey Borodin wrote:
> I think you are right. The test records node1_final_lsn after waiting
> for node2 to catch up. Any WAL generated on node1 between those two
> operations can therefore move node1_final_lsn past the point from which
> node2 is later promoted.
>
> Perhaps we should instead obtain the LSN together with the operation
> whose WAL we want node2 to replay, and only then wait for catchup:
>
> my $node1_final_lsn = $node1->safe_psql('postgres', <<EOM);
> CREATE TABLE dummy ();
> SELECT pg_current_wal_insert_lsn();
> EOM
> $node1->wait_for_replay_catchup($node2);
>
> This way node1_final_lsn identifies the position immediately after the
> test's own pre-promotion WAL, and wait_for_replay_catchup() guarantees
> that node2 has replayed at least that far. Any WAL generated on node1
> afterwards can no longer move the reference point past node2's fork
> point.
>
> WDYT?
>

I wonder if $node1_final_lsn should be pg_current_wal_flush_lsn instead of
pg_current_wal_insert_lsn. I've tried flush_lsn and it seems to fix the
issue, but I'm not sure if it's correct test-wise.

Best regards,
Alexander






^ permalink  raw  reply  [nested|flat] 31+ messages in thread

* Re: walsummarizer can get stuck when switching timelines
@ 2026-08-23 16:02  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: Alexander Lakhin <exclusion@gmail.com>
  0 siblings, 0 replies; 31+ messages in thread

From: Andrey Borodin @ 2026-08-23 16:02 UTC (permalink / raw)
  To: Alexander Lakhin <exclusion@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>; Amit Kapila <amit.kapila16@gmail.com>; pgsql-hackers

Hi Alexander,

> I wonder if $node1_final_lsn should be pg_current_wal_flush_lsn
> instead of pg_current_wal_insert_lsn. I've tried flush_lsn and it
> seems to fix the issue, but I'm not sure if it's correct test-wise.

I think either is correct here. CREATE TABLE has already committed
before the SELECT is executed.

AFAIU important part for avoiding the race is to record the LSN before
wait_for_replay_catchup(), rather than afterwards. The wait then
guarantees that node2 has replayed at least the recorded position, while
WAL generated later on node1 cannot move that position past node2's
eventual fork point.

I'd keep pg_current_wal_insert_lsn(), it matches what
wait_for_replay_catchup() uses.


Best regards, Andrey Borodin.







^ permalink  raw  reply  [nested|flat] 31+ messages in thread


end of thread, other threads:[~2026-08-23 16:02 UTC | newest]

Thread overview: 31+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-07-13 20:39 walsummarizer can get stuck when switching timelines Robert Haas <robertmhaas@gmail.com>
2026-07-14 12:40 ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-07-15 17:42   ` Srinath Reddy Sadipiralla <srinath2133@gmail.com>
2026-07-15 20:18     ` Robert Haas <robertmhaas@gmail.com>
2026-07-16 06:05       ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-07-16 12:19         ` Robert Haas <robertmhaas@gmail.com>
2026-07-18 18:29           ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-07-16 11:46       ` Thom Brown <thom@linux.com>
2026-07-16 12:39         ` Robert Haas <robertmhaas@gmail.com>
2026-07-16 12:58           ` Thom Brown <thom@linux.com>
2026-07-16 13:45             ` Robert Haas <robertmhaas@gmail.com>
2026-07-16 13:46               ` Thom Brown <thom@linux.com>
2026-07-17 16:21                 ` Thom Brown <thom@linux.com>
2026-07-17 19:02                   ` Robert Haas <robertmhaas@gmail.com>
2026-07-15 20:16   ` Robert Haas <robertmhaas@gmail.com>
2026-07-14 12:49 ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-14 13:05   ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-07-15 06:28     ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-15 08:52       ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-07-15 14:15         ` Robert Haas <robertmhaas@gmail.com>
2026-07-16 05:49           ` Amit Kapila <amit.kapila16@gmail.com>
2026-07-16 06:31           ` Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>
2026-07-22 14:51             ` Robert Haas <robertmhaas@gmail.com>
2026-07-31 16:55               ` Robert Haas <robertmhaas@gmail.com>
2026-08-02 16:00                 ` Alexander Lakhin <exclusion@gmail.com>
2026-08-03 09:16                   ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-08-10 18:20                     ` Robert Haas <robertmhaas@gmail.com>
2026-08-17 11:00                       ` Alexander Lakhin <exclusion@gmail.com>
2026-08-20 18:43                         ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-08-21 16:00                           ` Alexander Lakhin <exclusion@gmail.com>
2026-08-23 16:02                             ` Andrey Borodin <x4mmm@yandex-team.ru>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox