sync_standbys_defined and pg_stat_replication

Started by Jeremy Schneiderabout 1 year ago5 messageshackers

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1Jeremy Schneider
schneider@ardentperf.com

For failover to work correctly, if someone changes the GUC
synchronous_standby_names to enable sync replication, then we need to
understand the exact moment when backends will begin to block in order
to correctly determine when we can failover without data loss.

There's an older mailing list thread that discusses one aspect of this

/messages/by-id/CABrsG8j3kPD+kbbsx_isEpFvAgaOBNGyGpsqSjQ6L8vwVUaZAQ@mail.gmail.com

I've also gone through the code for SyncRepWaitForLSN() and worked
backwards to where the checkpointer sets sync_standbys_defined. But I
have a question which I couldn't answer so far.

It looks like sync_standbys_defined is only updated by the checkpointer
process. Is there a short period of time where the pg_stat_replication
view would show sync_state=sync and state=streaming, but the
checkpointer has not yet updated sync_standbys_defined?

I'm wondering if this is a race condition where COMMITs are not being
blocked for replication but external tools which rely on
pg_stat_replication would think it's safe to failover with zero data
loss?

-Jeremy

#2Jeremy Schneider
schneider@ardentperf.com
In reply to: Jeremy Schneider (#1)
Re: sync_standbys_defined and pg_stat_replication

On Mon, 6 Oct 2025 22:59:33 -0700
Jeremy Schneider <schneider@ardentperf.com> wrote:

For failover to work correctly, if someone changes the GUC
synchronous_standby_names to enable sync replication, then we need to
understand the exact moment when backends will begin to block in order
to correctly determine when we can failover without data loss.

There's an older mailing list thread that discusses one aspect of this

/messages/by-id/CABrsG8j3kPD+kbbsx_isEpFvAgaOBNGyGpsqSjQ6L8vwVUaZAQ@mail.gmail.com

I've also gone through the code for SyncRepWaitForLSN() and worked
backwards to where the checkpointer sets sync_standbys_defined. But I
have a question which I couldn't answer so far.

It looks like sync_standbys_defined is only updated by the
checkpointer process. Is there a short period of time where the
pg_stat_replication view would show sync_state=sync and
state=streaming, but the checkpointer has not yet updated
sync_standbys_defined?

I'm wondering if this is a race condition where COMMITs are not being
blocked for replication but external tools which rely on
pg_stat_replication would think it's safe to failover with zero data
loss?

FYI - some more details on the background of my question are here

https://github.com/cloudnative-pg/cloudnative-pg/issues/8790

I'm running Jepsen tests of a new CNPG feature (quorum failover) and
Jepsen picked up data loss when I ran it in conjuction with CNPG's
"preferred" dataDurability setting and I'm theorizing it may be related
to this delay with SyncRepWaitForLSN() starting to block COMMITs. The
"preferred durability" configuration is the equivalent to "Max
Availability" mode with Oracle Data Guard Broker; if anyone is curious I
have a table comparing Oracle modes to patroni/cnpg configs in this
blog:

https://ardentperf.com/2025/10/05/testing-cloudnativepg-preferred-data-durability/

-Jeremy

#3Ants Aasma
ants.aasma@cybertec.at
In reply to: Jeremy Schneider (#1)
Re: sync_standbys_defined and pg_stat_replication

On Tue, 7 Oct 2025 at 08:59, Jeremy Schneider <schneider@ardentperf.com> wrote:

For failover to work correctly, if someone changes the GUC
synchronous_standby_names to enable sync replication, then we need to
understand the exact moment when backends will begin to block in order
to correctly determine when we can failover without data loss.

There is an early out in SyncRepWaitForLSN() when
WalSndCtl->sync_standbys_status has SYNC_STANDBY_DEFINED unset. That
flag gets set by the checkpointer in
SyncRepUpdateSyncStandbysDefined() via CheckpointWriteDelay() among
other places. But only when it's not executing a fast checkpoint or
it's not behind on checkpoints.

In other words, synchronous_standby_names will not become effective
until checkpointer has some downtime. While this is a small problem on
its own, there is no way to check if this has happened or not.

For the config update getting delayed the fix seems simple - just do
the config update unconditionally. Patch attached.

For the other problem, my thinking is to provide a new function that
allows a user to check if synchronous replication is active.

Ideally this function would give other information also needed by
cluster managers. Specifically when a replica is removed from
synchronous standby names we would need still need to consider that
replica as a potential synchronous replica until a quorum matching the
current synchronous_standby_names setting overtakes the last LSN
confirmed by a replica matching the removed name.

To illustrate the situation where this is needed, consider s_s_n =
'ANY 1 (A B)'. While this setting is active we have to check latest
replicated LSN from both A and B to know which one to promote. Lets
say transaction X is replicated to A and confirmed, but not yet to B.
Now A is removed so s_s_n becomes 'ANY 1 (B)'. Based on this setting
it is always safe to promote B, but until B receives the LSN that was
on primary when synchronous_standby_names was changed, it might not
have all the data. This one is possible to work around by checking the
relevant values from pg_stat_replication, but it would be nice to have
a neater interface.

My proposal is something like this:

postgres=# SELECT * FROM pg_sync_replication_status();
is_active | synchronous_standby_names | has_quorum
-----------+---------------------------+------------
t | ANY 1 (A B) | f
(1 row)

Thoughts?

Regards,
Ants Aasma

Attachments:

t52397_3
v1-0001-Update-checkpointer-config-even-during-fast-check.patchtext/x-patch; charset=US-ASCII; name=v1-0001-Update-checkpointer-config-even-during-fast-check.patchDownload+8-9
#4Jeremy Schneider
schneider@ardentperf.com
In reply to: Ants Aasma (#3)
Re: sync_standbys_defined and pg_stat_replication

On Wed, 8 Oct 2025 20:38:53 +0300
Ants Aasma <ants.aasma@cybertec.at> wrote:

For the other problem, my thinking is to provide a new function that
allows a user to check if synchronous replication is active.

Ideally this function would give other information also needed by
cluster managers. Specifically when a replica is removed from
synchronous standby names we would need still need to consider that
replica as a potential synchronous replica until a quorum matching the
current synchronous_standby_names setting overtakes the last LSN
confirmed by a replica matching the removed name.

...

My proposal is something like this:

postgres=# SELECT * FROM pg_sync_replication_status();
is_active | synchronous_standby_names | has_quorum
-----------+---------------------------+------------
t | ANY 1 (A B) | f
(1 row)

Would it make sense to also add a fourth column in this proposed new
function with the effective LSN from the last time
synchronous_standby_names was changed?

I'm also thinking about changes to the synchronous_commit setting; if we
wanted the highest level of correctness, should we also capture the LSN
of that change and reflect it in this view? I haven't thought this
through fully yet.

Should external tools use procs corresponding with synchronous_commit
setting for promotion decisions? (pg_last_wal_receive_lsn vs
pg_last_wal_replay_lsn) This also relates to Andrey Borodin's other
thread about adding direct access to the write LSN on replicas for
promotion decisions.

/messages/by-id/0B44E464-BA62-4056-9465-3320DD2D0302@yandex-team.ru

-Jeremy

#5Aleksandr Korchak
korchakan@gmail.com
In reply to: Ants Aasma (#3)
Re: sync_standbys_defined and pg_stat_replication

On Wed, 8 Oct 2025 at 20:38, Ants Aasma <ants.aasma@cybertec.at> wrote:

For the config update getting delayed the fix seems simple - just do
the config update unconditionally. Patch attached.

Hi,

We're moving to two-node clusters (primary + one synchronous standby)
and need to know the moment commits start waiting for the standby
after synchronous_standby_names is set, which is what Jeremy asked at
the start of this thread (see also [1]https://github.com/cloudnative-pg/cloudnative-pg/issues/8790). Today that moment can be
delayed by the whole duration of a fast or behind-schedule checkpoint.

I reviewed and tested v1 on master, REL_19_STABLE and REL_18_STABLE.
It removes the delay, but it also processes the reload during shutdown
and end-of-recovery checkpoints, where UpdateFullPageWrites() must not
run:

- a reload that changes full_page_writes during a shutdown checkpoint
writes XLOG_FPW_CHANGE between the REDO point and the checkpoint
record, the shutdown ends in "PANIC: concurrent write-ahead log
activity while database system is shutting down", and the next start
runs crash recovery;
- the same reload during the end-of-recovery checkpoint changes
full_page_writes while RecoveryInProgress() is still true, so
XLOG_FPW_CHANGE is never written, and a standby replaying this WAL
never advances lastFpwDisableRecPtr.

v2 is attached:

0001 v1 plus one condition: the reload is not processed during the
checkpoints that CreateCheckPoint() treats as shutdown
checkpoints,

!(flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY))

There the reload is processed after the checkpoint, as today.
Checking ShutdownXLOGPending instead is not enough: it is false
during the end-of-recovery checkpoint.
0002 injection point "checkpoint-write-delay" at the end of
CheckpointWriteDelay() and TAP test
recovery/062_checkpoint_config_reload.pl. It fails without 0001
(times out waiting for the checkpointer to apply the change) and
passes with it.

The nocfbot-REL_19-* and nocfbot-REL_18-* files are the same series
for those branches; REL_18 uses CHECKPOINT_IMMEDIATE and
ImmediateCheckpointRequested(). The deferral itself is much older than
18, but I only tested 18 and later.

While testing I also found a pre-existing PANIC in 18 and later when a
reload arrives after the shutdown checkpoint. It doesn't depend on
this patch and is reported separately:
/messages/by-id/CAEBMo=D+fQ6vAw_TOpTQyL4h_+jHo1CMEDEuMzapN79-PsnKEw@mail.gmail.com

Results
-------

master 4280abf88409, REL_19_STABLE 67ad2443f78e and REL_18_STABLE
75829f043992, cassert builds, one primary and one streaming standby
(down in these scenarios). To keep a checkpoint ~50 s in BufferSync():
66,679 dirty buffers in 2GB of shared_buffers, debug_io_direct = data,
and the data directory on a device throttled to 20 MB/s. "Effect" is
the time from pg_reload_conf() until sessions see the change.

without fix with v2 (*)
master REL_19 REL_18 master REL_19 REL_18
1a enable s_s_n during 51.2 s 57.6 s 58.6 s 31 ms 25 ms 47 ms
CHECKPOINT
commits acknowledged 424 477 487 0 0 0
without the standby
1b disable s_s_n 49.5 s 51.9 s 57.3 s 14 ms 15 ms 43 ms
during CHECKPOINT
1c enable s_s_n during 31.3 s - - 7 ms - -
a WAL checkpoint
behind schedule
commits acknowledged 247 - - 0 - -
TAP test 062 fail fail fail pass pass pass

(*) On REL_19 and REL_18 measured with the separately reported fix
applied as well; it is not on this path.

Without the fix (master, 1a) the change is applied 1 ms after
"checkpoint complete":

15:17.473 pm LOG: parameter "synchronous_standby_names" changed
to "*"
16:08.593 ckpt LOG: checkpoint complete: fast force wait: ...
write=56.168 s, sync=0.004 s, total=56.216 s
16:08.594 ckpt DEBUG: checkpointer updated shared memory
configuration values

With v2, 14 ms after pg_reload_conf() and 57 s before the checkpoint
completes:

30:00.358 pm LOG: parameter "synchronous_standby_names" changed
to "*"
30:00.360 ckpt DEBUG: checkpointer updated shared memory
configuration values
30:57.502 ckpt LOG: checkpoint complete: fast force wait: ...

v1 at shutdown (pg_ctl stop -m smart, then a reload that sets
full_page_writes = off during the shutdown checkpoint), pg_waldump:

0/29E3F588 FPW_CHANGE false
0/29E3F5A8 CHECKPOINT_SHUTDOWN redo 0/29E3F588; ... fpw true; ...

followed by the PANIC above. v1 at the end of crash recovery, same
reload during the end-of-recovery checkpoint:

0/29E391A8 CHECKPOINT_SHUTDOWN redo 0/29E391A8; ... fpw true; ...
0/29E392C8 CHECKPOINT_REDO wal_level replica; checksums on
0/29E39328 CHECKPOINT_ONLINE redo 0/29E392C8; ... fpw false; ...

With v2, as on unpatched master, the shutdown checkpoint completes
normally, and after crash recovery FPW_CHANGE false is written right
after the end-of-recovery checkpoint.

Known limitation
----------------

CheckpointWriteDelay() is not called from ProcessSyncRequests(), so
the change still waits while the checkpoint fsyncs. Without
debug_io_direct, where the checkpoint had write=0.5 s and sync=26 s,
master, v1 and v2 all applied synchronous_standby_names 21.5 s after
the reload, together with "checkpoint complete", and acknowledged
172-178 commits without the standby. v2 shrinks the window to the
fsync phase but doesn't close it. I'd leave that to a separate patch.

Regression tests, with this series and the separately reported fix
applied: on master, full meson test passed (391 ok, 0 fail); on
REL_19_STABLE and REL_18_STABLE, meson test --suite recovery passed
(59 and 54 ok). Those runs were on the commits listed above; since
then the series was only rebased (the test moved from 061 to 062), and
it applies with git am to today's heads of all three branches.

Server logs, gdb traces, pg_waldump output and the scripts for every
scenario are available if anyone wants them.

[1]: https://github.com/cloudnative-pg/cloudnative-pg/issues/8790

--
Aleksandr Korchak

Attachments:

t52397_5
nocfbot-REL_19-v2-0002-Add-test-for-config-reload-during-a-fast-checkpoi.patchapplication/octet-stream; name=nocfbot-REL_19-v2-0002-Add-test-for-config-reload-during-a-fast-checkpoi.patchDownload+102-1
v2-0001-Update-checkpointer-config-even-during-fast-check.patchapplication/octet-stream; name=v2-0001-Update-checkpointer-config-even-during-fast-check.patchDownload+18-9
nocfbot-REL_19-v2-0001-Update-checkpointer-config-even-during-fast-check.patchapplication/octet-stream; name=nocfbot-REL_19-v2-0001-Update-checkpointer-config-even-during-fast-check.patchDownload+18-9
nocfbot-REL_18-v2-0001-Update-checkpointer-config-even-during-immediate-.patchapplication/octet-stream; name=nocfbot-REL_18-v2-0001-Update-checkpointer-config-even-during-immediate-.patchDownload+18-9
nocfbot-REL_18-v2-0002-Add-test-for-config-reload-during-an-immediate-ch.patchapplication/octet-stream; name=nocfbot-REL_18-v2-0002-Add-test-for-config-reload-during-an-immediate-ch.patchDownload+102-1
v2-0002-Add-test-for-config-reload-during-a-fast-checkpoi.patchapplication/octet-stream; name=v2-0002-Add-test-for-config-reload-during-a-fast-checkpoi.patchDownload+102-1