Re: Possible race condition in pg_basebackup

Поиск
Список
Период
Сортировка
Искать

Re: Possible race condition in pg_basebackup

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Вложения:
Hi Alvaro,

On Fri, Aug 21, 2026 at 6:35 PM Alvaro Herrera wrote:
> If you're using a version that contains these fixes, then we may have
> some slightly different bug ...

Yes, this is a different bug.  I added a deterministic injection-point test
on current master, which already contains 006dd4b2e.  It stops
BASE_BACKUP after selecting the startpoint but before sending it to the
client, recycles that WAL, and then observes pg_basebackup fail when its WAL
streamer starts.  As a reproducer, the test succeeds only when pg_basebackup
fails with the expected missing-WAL error.

006dd4b2e protects an already created slot while it reserves WAL.  In this
case no slot exists yet, so it cannot protect the earlier backup startpoint.

PFA the test patch.


Best regards, Andrey Borodin.

Re: Possible race condition in pg_basebackup

От:
Nick Ivanov <nick.ivanov@enterprisedb.com>
Дата:
Вложения:
Hello, 

On Fri, Aug 21, 2026 at 12:28 PM Andrey Borodin <x4mmm@yandex-team.ru> wrote:


 I think this needs a design
discussion rather than just moving client-side calls around.

Perhaps BASE_BACKUP should retain WAL from the exact REDO location of the
checkpoint it selected until the WAL streamer has taken over.  This also
handles backups from a standby, where the selected restartpoint may be
older than the current replay location.  The server knows the exact LSN
and can release such a backup-owned retention horizon on backup completion
or abort, without transferring a temporary slot between the two client
connections.

The attached patch is intended to fix the WAL recycle race condition discussed in this thread. It's more to kick off the design discussion, as suggested by Andrey earlier, than to provide the final answer. It follows the replication slots example of maintaining a list of in-progress backups in a shared memory structure and allowing the checkpointer, via KeepLogSeg, to determine which segments it should not recycle/remove.

The memory structure is much simpler than ReplicationSlot; we don't need to store any complex state information, and each backup is supposed to have its unique start XLogRecPtr, which we can use to distinguish between them. We still introduce a BackupInProgress struct for possible future extension, instead of using bare XLogRecPtr.

We need to define a new GUC, max_concurrent_backups, to control the size of the BackupInProgress array.

When the backup starts, it requests a checkpoint and records its start point in BackupCtlData; when it ends or is aborted, the corresponding entry is removed. KeepLogSeg checks the oldest XLogRecPtr needed by backups when deciding what segments need to be removed by a checkpoint. 

I retrofitted Andrey Borodin's reproducer test by flipping its success/failure criterion, and it seems to confirm the fix works. It doesn't seem to break anything else either.

I left out documentation updates until later; since it's my very first Postgres patch, its fate is uncertain. I'll be grateful for any feedback.

I did use Claude to vet the design and proofread the resulting code, but the actual code is all mine.


Cheers

--
Nick Ivanov 

Re: Possible race condition in pg_basebackup

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Вложения:
Hi Nick,

On 11 Sep 2026, Nick Ivanov wrote:
> I agree, and I'm attaching a separate patch for that.

Thanks!  This looks like the right scope for a backpatch.

I adapted your v2 test for the client-side fix, checking that the slot
already reserves WAL before the server sends the startpoint.  It covers
both --create-slot and the default temporary slot, and requires the
backup to succeed after the concurrent checkpoint.  Without the fix,
both cases fail with the expected missing-WAL error.

Small wording detail. Another checkpoint is enough to trigger the race.
It need not come from another basebackup.  I adjusted and wrapped the
commit message accordingly.  Apart from wrapping a comment, the client
code is unchanged.

WDYT?


Best regards, Andrey Borodin.

Re: Possible race condition in pg_basebackup

От:
Shashishekar Hullahally Anantharamu <shashi.h.ananth@gmail.com>
Дата:
The following review has been posted through the commitfest application:
make installcheck-world:  not tested
Implements feature:       tested, passed
Spec compliant:           not tested
Documentation:            not tested

Hi Andrey and Nick,

I reviewed the v3 two-patch series against PostgreSQL commit 94670ba6d56.

Both patches applied cleanly, and git diff --check reported no errors. I configured the build with assertions, debug support, TAP tests, and injection points enabled. The build completed successfully without warnings or errors.

The implementation moves creation of the WAL-streaming connection and replication slot before the BASE_BACKUP request. It then passes the same connection to StartLogStreamer(). This closes the interval in which the backup startpoint could previously become unprotected before the requested slot was created.

I also reviewed the new 057_basebackup_slot_race.pl test. It deterministically pauses BASE_BACKUP before the startpoint is returned, forces WAL generation and a checkpoint, and verifies that the startpoint segment remains available. The test covers both permanent and temporary replication slots and verifies successful backup completion and slot cleanup.

Test results:

057_basebackup_slot_race.pl: PASS, 10 tests
Complete src/bin/pg_basebackup test suite: PASS, 5 files and 351 tests
Full make check: PASS

The first component-suite and full-check attempts encountered macOS temporary-install Mach-O paths referring to /usr/local/pgsql/lib/libpq.5.dylib. After correcting those paths only in the disposable temporary installation, the affected tests and complete suites passed. This was a local build-environment issue and did not require any source changes.

I did not find any functional or test-coverage issues with the v3 series. The patch appears ready for committer review.

Regards,
Shashishekar Hullahally Anantharamu

The new status of this patch is: Ready for Committer

Re: Possible race condition in pg_basebackup

От:
Nick Ivanov <nick.ivanov@enterprisedb.com>
Дата:
Hello Andrey,

On 15/09/2026 19:29, Andrey Borodin wrote:
> Hi Nick,
>
> Thanks!  This looks like the right scope for a backpatch.
>
> I adapted your v2 test for the client-side fix, checking that the slot
> already reserves WAL before the server sends the startpoint.  It covers
> both --create-slot and the default temporary slot, and requires the
> backup to succeed after the concurrent checkpoint.  Without the fix,
> both cases fail with the expected missing-WAL error.

Thank you for updating the test, much appreciated. I should have done 
that myself, to be honest.


> Small wording detail. Another checkpoint is enough to trigger the race.
> It need not come from another basebackup.  I adjusted and wrapped the
> commit message accordingly.  Apart from wrapping a comment, the client
> code is unchanged.
>
> WDYT?


The changes make good sense, thanks for that too.

I will now proceed to validate the patch against older versions. One 
question in that regard: the TAP test carries the number 57 in the 
recovery suite in the master branch. Earlier stable versions likely have 
fewer tests, and if we add the new test there with #57 there will be a 
gap in the sequence. What is the accepted practice in such cases: 
renumber the newly added test in earlier versions to avoid the gap, or 
keep the number consistent with HEAD?

Cheers


Nick



Re: Possible race condition in pg_basebackup

От:
Nick Ivanov <nick.ivanov@enterprisedb.com>
Дата:
Hello Shashishekar,

Thank you very much for your review and tests, much appreciated.

Nick

On 18/09/2026 04:02, Shashishekar Hullahally Anantharamu wrote:
> The following review has been posted through the commitfest application:
> make installcheck-world:  not tested
> Implements feature:       tested, passed
> Spec compliant:           not tested
> Documentation:            not tested
>
> Hi Andrey and Nick,
>
> I reviewed the v3 two-patch series against PostgreSQL commit 94670ba6d56.
>
> Both patches applied cleanly, and git diff --check reported no errors. I configured the build with assertions, debug support, TAP tests, and injection points enabled. The build completed successfully without warnings or errors.
>
> The implementation moves creation of the WAL-streaming connection and replication slot before the BASE_BACKUP request. It then passes the same connection to StartLogStreamer(). This closes the interval in which the backup startpoint could previously become unprotected before the requested slot was created.
>
> I also reviewed the new 057_basebackup_slot_race.pl test. It deterministically pauses BASE_BACKUP before the startpoint is returned, forces WAL generation and a checkpoint, and verifies that the startpoint segment remains available. The test covers both permanent and temporary replication slots and verifies successful backup completion and slot cleanup.
>
> Test results:
>
> 057_basebackup_slot_race.pl: PASS, 10 tests
> Complete src/bin/pg_basebackup test suite: PASS, 5 files and 351 tests
> Full make check: PASS
>
> The first component-suite and full-check attempts encountered macOS temporary-install Mach-O paths referring to /usr/local/pgsql/lib/libpq.5.dylib. After correcting those paths only in the disposable temporary installation, the affected tests and complete suites passed. This was a local build-environment issue and did not require any source changes.
>
> I did not find any functional or test-coverage issues with the v3 series. The patch appears ready for committer review.
>
> Regards,
> Shashishekar Hullahally Anantharamu
>
> The new status of this patch is: Ready for Committer


Re: Possible race condition in pg_basebackup

От:
Shashishekar Hullahally Anantharamu <shashi.h.ananth@gmail.com>
Дата:
Hi Nick,

You are welcome!, Glad that my tests and reviews were helpful.

Regards
Shashi A

On Sat, Sep 19, 2026 at 8:50 AM Nick Ivanov <nick.ivanov@enterprisedb.com> wrote:
Hello Shashishekar,

Thank you very much for your review and tests, much appreciated.

Nick

On 18/09/2026 04:02, Shashishekar Hullahally Anantharamu wrote:
> The following review has been posted through the commitfest application:
> make installcheck-world:  not tested
> Implements feature:       tested, passed
> Spec compliant:           not tested
> Documentation:            not tested
>
> Hi Andrey and Nick,
>
> I reviewed the v3 two-patch series against PostgreSQL commit 94670ba6d56.
>
> Both patches applied cleanly, and git diff --check reported no errors. I configured the build with assertions, debug support, TAP tests, and injection points enabled. The build completed successfully without warnings or errors.
>
> The implementation moves creation of the WAL-streaming connection and replication slot before the BASE_BACKUP request. It then passes the same connection to StartLogStreamer(). This closes the interval in which the backup startpoint could previously become unprotected before the requested slot was created.
>
> I also reviewed the new 057_basebackup_slot_race.pl test. It deterministically pauses BASE_BACKUP before the startpoint is returned, forces WAL generation and a checkpoint, and verifies that the startpoint segment remains available. The test covers both permanent and temporary replication slots and verifies successful backup completion and slot cleanup.
>
> Test results:
>
> 057_basebackup_slot_race.pl: PASS, 10 tests
> Complete src/bin/pg_basebackup test suite: PASS, 5 files and 351 tests
> Full make check: PASS
>
> The first component-suite and full-check attempts encountered macOS temporary-install Mach-O paths referring to /usr/local/pgsql/lib/libpq.5.dylib. After correcting those paths only in the disposable temporary installation, the affected tests and complete suites passed. This was a local build-environment issue and did not require any source changes.
>
> I did not find any functional or test-coverage issues with the v3 series. The patch appears ready for committer review.
>
> Regards,
> Shashishekar Hullahally Anantharamu
>
> The new status of this patch is: Ready for Committer

Re: Possible race condition in pg_basebackup

От:
Raja Sai pranav <rajasaipranav0@gmail.com>
Дата:
The following review has been posted through the commitfest application:
make installcheck-world:  not tested
Implements feature:       tested, passed
Spec compliant:           not tested
Documentation:            not tested

Hi Nick, Andrey,
I tested v3 on master (45fc51f, 2026-10-17), built with --enable-cassert --enable-debug --enable-tap-tests --enable-injection-points on Linux (aarch64).

v3 no longer applies (cfbot shows "Needs rebase"): 0001 conflicts in src/test/recovery/meson.build, and 057 is now taken by 057_snapshot_commit_race.pl (058-060 exist as well). 0002 applies cleanly. For testing I renamed the test to 061_basebackup_slot_race.pl.

 - No compiler warnings.
 - The new test passes with 0001+0002. With 0001 only (the injection point and the test, no fix) it fails in both modes with "requested WAL segment ... has already been removed", as described upthread.
 - src/bin/pg_basebackup's TAP tests pass with the patch.
 - Without injection points, the reported scenario: three pg_basebackup -X stream --create-slot -c fast started together, 1 MB WAL segments, wal_keep_size = 0, max_wal_size = 32MB, and a session writing WAL continuously (pg_logical_emit_message, 1 MB each). Over 100 rounds (300 backups), 62 failed without 0002, all with "requested WAL segment ... has already been removed", and none failed with it. All 538 backups that completed pass pg_verifybackup.
 One behaviour change I noticed: with --create-slot, the permanent slot is now created before BASE_BACKUP, and pg_basebackup doesn't drop it if the backup can't start. Before the patch, a backup the server refused never created the slot. To check:

 initdb, summarize_wal = on, pg_basebackup a full backup, then summarize_wal = off, then
 pg_basebackup -X stream --create-slot -S leftover --incremental=/backup_manifest
 -> could not initiate base backup: ERROR:  incremental backups cannot be taken unless WAL summarization is enabled
 On master no slot is left. With the patch, "leftover" remains with restart_lsn 0/02000028 and keeps holding back WAL until someone drops it. Since the slot is now created first, any other error from BASE_BACKUP should leave it behind the same way (I only tried this one). Temporary slots are not affected, since they go away with the connection.

Would it make sense to drop the slot when BASE_BACKUP fails, if this run created it? A failure later in the backup already leaves the slot behind today, so that part isn't new, but a refused start probably shouldn't leave a permanent slot behind.

I haven't tried the back branches yet.

Regards,
Sai Pranav

The new status of this patch is: Waiting on Author

Re: Possible race condition in pg_basebackup

От:
Raja Sai pranav <rajasaipranav0@gmail.com>
Дата:
Hi Nick, Andrey,

Following up on my review with the back branches (REL_15_STABLE to REL_19_STABLE, as of 2026-10-19), since the patch is marked Backpatch-through: 15.

0002 doesn't apply as is on any of them:
- in StartLogStreamer() the context line `if (!pg_parse_lsn(startpos, ...))` is `sscanf(startpos, "%X/%X", ...)` there (`"%X/%08X"` on 19), so the `param->bgconn = walconn;` hunk has to be placed by hand
- on 15, 16 and 17 CreateReplicationSlot() has no failover argument, so the new call takes 8 arguments

With only those changes it builds without warnings, src/bin/pg_basebackup's TAP tests pass, and the race (three pg_basebackup --create-slot started together, 1 MB segments, wal_keep_size = 0, a session writing WAL) gives 0 failures of 300 backups on each branch, against 150-165 of 300 without it.

0001 on 17-19 needs `#include "utils/injection_point.h"` in basebackup.c (master has it, the branches don't); on 17, INJECTION_POINT() takes one argument and Cluster.pm has no check_extension(). The free test number also differs per branch (057 on 17, 058 on 18 and 19). With that, the test passes with 0002 and fails in both modes without it on 17, 18 and 19.

The leftover slot from my previous mail isn't tied to incremental backups: with `pg_basebackup -X stream --create-slot -S leftover --manifest-checksums=bogus` the server rejects BASE_BACKUP (`unrecognized checksum algorithm: "bogus"`), and with the patch the slot stays, on every branch from 15 to 19; without it there is none.

Regards,
 Pranav

Re: Possible race condition in pg_basebackup

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
Hi all,

On 17 Oct 2026, Raja Sai Pranav wrote:
> Would it make sense to drop the slot when BASE_BACKUP fails, if this
> run created it?

For a backpatch, I'd preserve the old behavior on a refused start: drop
the permanent slot if this run successfully created it and BASE_BACKUP
is rejected before returning the startpoint. The ownership flag should
only be set after successful creation, so a failed --create-slot cannot
cause an existing slot to be dropped. I'd keep later backup failures
unchanged.

Our test drops the permanent slot itself after success, so it does not
cover this. The bogus-checksum case should check both the specific error
and absence of the new slot. An existing slot should survive both a
rejected backup and a failed --create-slot. Cleanup failure should not
replace the original backup error.

Nick, could we put the early-error cleanup and its tests in a separate
patch in the same backpatch series? That would keep the early-slot
change focused.

Thank you!


Best regards, Andrey Borodin.



FAQ