Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/*-------------------------------------------------------------------------
 * logicalctl.c
 *      Functionality to control logical decoding status online.
 *
 * This module enables dynamic control of logical decoding availability.
 * Logical decoding becomes active under two conditions: when the wal_level
 * parameter is set to 'logical', or when at least one valid logical replication
 * slot exists with wal_level set to 'replica'. The system disables logical
 * decoding when neither condition is met. Therefore, the dynamic control
 * of logical decoding availability is required only when wal_level is set
 * to 'replica'. Logical decoding is always enabled when wal_level='logical'
 * and always disabled when wal_level='minimal'.
 *
 * The core concept of dynamically enabling and disabling logical decoding
 * is to separately control two aspects: writing information required for
 * logical decoding to WAL records, and using logical decoding itself. During
 * activation, we first enable logical WAL writing while keeping logical
 * decoding disabled. This change is reflected in the read-only
 * effective_wal_level GUC parameter. Once we ensure that all processes have
 * updated to the latest effective_wal_level value, we then enable logical
 * decoding. Deactivation follows a similar careful, multi-step process
 * in reverse order.
 *
 * While activation occurs synchronously right after creating the first
 * logical slot, deactivation happens asynchronously through the checkpointer
 * process. This design avoids a race condition at the end of recovery; see
 * the comments in UpdateLogicalDecodingStatusEndOfRecovery() for details.
 * Asynchronous deactivation also avoids excessive toggling of the logical
 * decoding status in workloads that repeatedly create and drop a single
 * logical slot. On the other hand, this lazy approach can delay changes
 * to effective_wal_level and the disabling logical decoding, especially
 * when the checkpointer is busy with other tasks. We chose this lazy approach
 * in all deactivation paths to keep the implementation simple, even though
 * laziness is strictly required only for end-of-recovery cases. Future work
 * might address this limitation either by using a dedicated worker instead
 * of the checkpointer, or by implementing synchronous waiting during slot
 * drops if workloads are significantly affected by the lazy deactivation
 * of logical decoding.
 *
 * Standby servers use the primary server's effective_wal_level and logical
 * decoding status. Unlike normal activation and deactivation, these
 * are updated simultaneously without status change coordination, solely by
 * replaying XLOG_LOGICAL_DECODING_STATUS_CHANGE records. The local wal_level
 * setting has no effect during this time. Upon promotion, we update the
 * logical decoding status based on local conditions: the wal_level value and
 * the presence of logical slots.
 *
 * In the future, we could extend support to include automatic transitions
 * of effective_wal_level between 'minimal' and 'logical' WAL levels. However,
 * this enhancement would require additional coordination mechanisms and
 * careful implementation of operations such as terminating walsenders and
 * archiver processes while carefully considering the sequence of operations
 * to ensure system stability during these transitions.
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * IDENTIFICATION
 *    src/backend/replication/logical/logicalctl.c
 *
 *-------------------------------------------------------------------------
 */
 
#include "postgres.h"
 
#include "access/xloginsert.h"
#include "access/xlogrecovery.h"
#include "catalog/pg_control.h"
#include "miscadmin.h"
#include "replication/slot.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/procsignal.h"
#include "storage/subsystems.h"
#include "utils/injection_point.h"
 
/*
 * Struct for controlling the logical decoding status.
 *
 * This struct is protected by LogicalDecodingControlLock.
 */
typedef struct LogicalDecodingCtlData
{
    /*
     * This is the authoritative value used by all processes to determine
     * whether to write additional information required by logical decoding to
     * WAL. Since this information could be checked frequently, each process
     * caches this value in XLogLogicalInfo for better performance.
     */
    bool        xlog_logical_info;
 
    /* True if logical decoding is available in the system */
    bool        logical_decoding_enabled;
 
    /* True if logical decoding might need to be disabled */
    bool        pending_disable;
 
    /*
     * End LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record that
     * enabled logical decoding, or InvalidXLogRecPtr if none has been
     * replayed since the server started. Checking it with
     * logical_decoding_enabled tells from which point on WAL was written with
     * logical decoding enabled; see StandbyLogicalDecodingEnabledSince().
     *
     * WAL records that disable logical decoding are deliberately not tracked
     * here. logical_decoding_enabled is false while decoding is off, which is
     * all the check needs.
     *
     * This is maintained only during recovery and is not persisted, so it
     * says nothing about a status change replayed in an earlier server run.
     */
    XLogRecPtr  last_replayed_enable_lsn;
} LogicalDecodingCtlData;
 
static LogicalDecodingCtlData *LogicalDecodingCtl = NULL;
 
static void LogicalDecodingCtlShmemRequest(void *arg);
static void LogicalDecodingCtlShmemInit(void *arg);
 
const ShmemCallbacks LogicalDecodingCtlShmemCallbacks = {
    .request_fn = LogicalDecodingCtlShmemRequest,
    .init_fn = LogicalDecodingCtlShmemInit,
};
 
/*
 * A process-local cache of LogicalDecodingCtl->xlog_logical_info. This is
 * initialized at process startup, and updated when processing the process
 * barrier signal in ProcessBarrierUpdateXLogLogicalInfo(). If the process
 * is in an XID-assigned transaction, the cache update is delayed until the
 * transaction ends. See the comments for XLogLogicalInfoUpdatePending for details.
 */
bool        XLogLogicalInfo = false;
 
/*
 * When receiving the PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO signal, if
 * an XID is assigned to the current transaction, the process sets this flag and
 * delays the XLogLogicalInfo update until the transaction ends. This ensures
 * that the XLogLogicalInfo value (typically accessed via XLogLogicalInfoActive)
 * remains consistent throughout the transaction.
 */
static bool XLogLogicalInfoUpdatePending = false;
 
static void update_xlog_logical_info(void);
static void abort_logical_decoding_activation(int code, Datum arg);
static void write_logical_decoding_status_update_record(bool status);
 
static void
LogicalDecodingCtlShmemRequest(void *arg)
{
    ShmemRequestStruct(.name = "Logical decoding control",
                       .size = sizeof(LogicalDecodingCtlData),
                       .ptr = (void **) &LogicalDecodingCtl,
        );
}
 
static void
LogicalDecodingCtlShmemInit(void *arg)
{
    LogicalDecodingCtl->xlog_logical_info = false;
    LogicalDecodingCtl->logical_decoding_enabled = false;
    LogicalDecodingCtl->pending_disable = false;
    LogicalDecodingCtl->last_replayed_enable_lsn = InvalidXLogRecPtr;
}
 
/*
 * Initialize the logical decoding status in shmem at server startup. This
 * must be called ONCE during postmaster or standalone-backend startup.
 */
void
StartupLogicalDecodingStatus(bool last_status)
{
    /* Logical decoding is always disabled when 'minimal' WAL level */
    if (wal_level == WAL_LEVEL_MINIMAL)
        return;
 
    /*
     * Set the initial logical decoding status based on the last status. If
     * logical decoding was enabled before the last shutdown, it remains
     * enabled as we might have set wal_level='logical' or have at least one
     * logical slot.
     */
    LogicalDecodingCtl->xlog_logical_info = last_status;
    LogicalDecodingCtl->logical_decoding_enabled = last_status;
}
 
/*
 * Update the XLogLogicalInfo cache.
 */
static inline void
update_xlog_logical_info(void)
{
    XLogLogicalInfo = IsXLogLogicalInfoEnabled();
}
 
/*
 * Initialize XLogLogicalInfo backend-private cache. This routine is called
 * during process initialization.
 */
void
InitializeProcessXLogLogicalInfo(void)
{
    update_xlog_logical_info();
}
 
/*
 * This routine is called when we are told to update XLogLogicalInfo
 * by a ProcSignalBarrier.
 */
bool
ProcessBarrierUpdateXLogLogicalInfo(void)
{
    if (GetTopTransactionIdIfAny() != InvalidTransactionId)
    {
        /* Delay updating XLogLogicalInfo until the transaction end */
        XLogLogicalInfoUpdatePending = true;
    }
    else
        update_xlog_logical_info();
 
    return true;
}
 
/*
 * Check the shared memory state and return true if logical decoding is
 * enabled on the system.
 */
bool
IsLogicalDecodingEnabled(void)
{
    bool        enabled;
 
    LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
    enabled = LogicalDecodingCtl->logical_decoding_enabled;
    LWLockRelease(LogicalDecodingControlLock);
 
    return enabled;
}
 
/*
 * Return true if logical decoding has been enabled continuously from the given
 * LSN up to the current replay position, that is, if the WAL in that range
 * was written with logical decoding enabled.
 *
 * The given LSN must have been replayed already; nothing can be said about
 * WAL this server has not replayed yet. The caller is responsible for checking
 * that.
 */
bool
StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn)
{
    bool        result;
 
    Assert(RecoveryInProgress());
    Assert(lsn <= GetXLogReplayRecPtr(NULL));
 
    LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
    result = LogicalDecodingCtl->logical_decoding_enabled &&
        lsn >= LogicalDecodingCtl->last_replayed_enable_lsn;
    LWLockRelease(LogicalDecodingControlLock);
 
    return result;
}
 
/*
 * Returns true if logical WAL logging is enabled based on the shared memory
 * status.
 */
bool
IsXLogLogicalInfoEnabled(void)
{
    bool        xlog_logical_info;
 
    LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
    xlog_logical_info = LogicalDecodingCtl->xlog_logical_info;
    LWLockRelease(LogicalDecodingControlLock);
 
    return xlog_logical_info;
}
 
/*
 * Apply a pending XLogLogicalInfo update at end of the top-level transaction.
 *
 * This is called from CommitTransaction(), PrepareTransaction(), and
 * CleanupTransaction(), which are the only places where the top-level XID is
 * reset, so the next transaction always starts with the latest value.
 */
void
AtEOXact_LogicalCtl(void)
{
    /* Update the local cache if there is a pending update */
    if (XLogLogicalInfoUpdatePending)
    {
        update_xlog_logical_info();
        XLogLogicalInfoUpdatePending = false;
    }
}
 
/*
 * Writes an XLOG_LOGICAL_DECODING_STATUS_CHANGE WAL record with the given
 * status.
 */
static void
write_logical_decoding_status_update_record(bool status)
{
    XLogRecPtr  recptr;
 
    XLogBeginInsert();
    XLogRegisterData(&status, sizeof(bool));
    recptr = XLogInsert(RM_XLOG_ID, XLOG_LOGICAL_DECODING_STATUS_CHANGE);
    XLogFlush(recptr);
}
 
/*
 * A PG_ENSURE_ERROR_CLEANUP callback for activating logical decoding.
 *
 * Rather than directly reverting xlog_logical_info here, we request
 * that the checkpointer handle it via the normal disable path. This
 * avoids race conditions when multiple backends attempt concurrent
 * activation: the checkpointer will reset xlog_logical_info when
 * no valid logical slots exist.
 */
static void
abort_logical_decoding_activation(int code, Datum arg)
{
    elog(DEBUG1, "aborting logical decoding activation process");
    RequestDisableLogicalDecoding();
}
 
/*
 * Enable logical decoding if disabled.
 *
 * If this function is called during recovery, it just checks that logical
 * decoding is still enabled, since the logical decoding status cannot be
 * changed during this time. The logical decoding status depends on the
 * status on the primary.
 *
 * Note that there is no interlock between logical decoding activation
 * and slot creation. To ensure enabling logical decoding, the caller
 * needs to call this function after creating a logical slot before
 * initializing the logical decoding context.
 */
void
EnsureLogicalDecodingEnabled(void)
{
    Assert(MyReplicationSlot);
    Assert(wal_level >= WAL_LEVEL_REPLICA);
 
    /* Logical decoding is always enabled */
    if (wal_level >= WAL_LEVEL_LOGICAL)
        return;
 
    if (RecoveryInProgress())
    {
        /*
         * The caller has already checked that logical decoding is enabled via
         * CheckLogicalDecodingRequirements(), but the status could have been
         * disabled concurrently before we created our slot: either by
         * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by
         * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We
         * cannot enable logical decoding during recovery, so raise an error.
         *
         * Our slot has already been created, so its in_use flag is set and
         * the slot scans performed by a deactivation can see it. It
         * guarantees that this check doesn't miss a concurrent deactivation:
         * UpdateLogicalDecodingStatusEndOfRecovery() won't disable logical
         * decoding since CheckLogicalSlotExists() finds our valid slot, and
         * replaying a status change record after this check invalidates our
         * slot, so this slot creation fails afterwards anyway (by a recovery
         * conflict or the requirement re-check in
         * CreateInitDecodingContext()). Hence, this check only needs to catch
         * deactivations that completed before our slot's in_use flag was set.
         */
        if (!IsLogicalDecodingEnabled())
            ereport(ERROR,
                    (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                     errmsg("logical decoding on standby requires \"effective_wal_level\" >= \"logical\" on the primary"),
                     errdetail("Logical decoding was concurrently disabled during the logical replication slot creation.")));
 
        return;
    }
 
    /*
     * Ensure to abort the activation process in cases where there in an
     * interruption during the wait.
     */
    PG_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0);
    {
        EnableLogicalDecoding(InvalidXLogRecPtr);
    }
    PG_END_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0);
}
 
/*
 * A workhorse function to enable logical decoding.
 *
 * lsn is the end LSN of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record
 * being replayed, and is InvalidXLogRecPtr when not called from redo.
 */
void
EnableLogicalDecoding(XLogRecPtr lsn)
{
    bool        in_recovery;
 
    LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
 
    /*
     * Remember where logical decoding was enabled. This has to happen before
     * the early return below, because replay can reach here with the status
     * already on. For example, CreateCheckPoint() fixes the redo point before
     * it records logicalDecodingEnabled, so a checkpoint can claim logical
     * decoding is enabled while the record that enabled it still follows the
     * redo point.
     */
    Assert(RecoveryInProgress() == XLogRecPtrIsValid(lsn));
    if (XLogRecPtrIsValid(lsn))
        LogicalDecodingCtl->last_replayed_enable_lsn = lsn;
 
    /* Return if it is already enabled */
    if (LogicalDecodingCtl->logical_decoding_enabled)
    {
        LogicalDecodingCtl->pending_disable = false;
        LWLockRelease(LogicalDecodingControlLock);
        return;
    }
 
    /*
     * Set logical info WAL logging in shmem. All process starts after this
     * point will include the information required by logical decoding to WAL
     * records.
     */
    LogicalDecodingCtl->xlog_logical_info = true;
 
    LWLockRelease(LogicalDecodingControlLock);
 
    /*
     * Tell all running processes to reflect the xlog_logical_info update, and
     * wait. This ensures that all running processes have enabled logical
     * information WAL logging.
     */
    WaitForProcSignalBarrier(
                             EmitProcSignalBarrier(PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO));
 
    INJECTION_POINT("logical-decoding-activation", NULL);
 
    in_recovery = RecoveryInProgress();
 
    /*
     * There could be some transactions that might have started with the old
     * status, but we don't need to wait for these transactions to complete as
     * long as they have valid XIDs. These transactions will appear in the
     * xl_running_xacts record and therefore the snapshot builder will not try
     * to decode the transaction during the logical decoding initialization.
     *
     * There is a theoretical case where a transaction decides whether to
     * include logical-info to WAL records before getting an XID. In this
     * case, the transaction won't appear in xl_running_xacts.
     *
     * For operations that do not require an XID assignment, the process
     * starts including logical-info immediately upon receiving the signal
     * (barrier). If such an operation checks the effective_wal_level multiple
     * times within a single execution, the resulting WAL records might be
     * inconsistent (i.e., logical-info is included in some records but not in
     * others). However, this is harmless because logical decoding generally
     * ignores WAL records that are not associated with an assigned XID.
     *
     * One might think we need to wait for all running transactions, including
     * those without XIDs and read-only transactions, to finish before
     * enabling logical decoding. However, such a requirement would force the
     * slot creation to wait for a potentially very long time due to
     * long-running read queries, which is practically unacceptable.
     */
 
    LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
 
    /*
     * Re-check whether logical decoding got enabled while we waited for the
     * barrier above.
     */
    if (LogicalDecodingCtl->logical_decoding_enabled)
    {
        LogicalDecodingCtl->pending_disable = false;
        LWLockRelease(LogicalDecodingControlLock);
        return;
    }
 
    START_CRIT_SECTION();
 
    /*
     * We enable logical decoding first, followed by writing the WAL record.
     * This sequence ensures logical decoding becomes available on the primary
     * first.
     */
    LogicalDecodingCtl->logical_decoding_enabled = true;
 
    if (!in_recovery)
        write_logical_decoding_status_update_record(true);
 
    LogicalDecodingCtl->pending_disable = false;
 
    END_CRIT_SECTION();
 
    LWLockRelease(LogicalDecodingControlLock);
 
    /*
     * We log the activation message after releasing the slot lock. This is
     * safe because the activation is performed while holding a logical slot,
     * meaning, a concurrent deactivation cannot interleave its log message
     * ahead of ours.
     */
    if (!in_recovery)
        ereport(LOG,
                errmsg("logical decoding is enabled upon creating a new logical replication slot"));
}
 
/*
 * Initiate a request for disabling logical decoding.
 *
 * Note that this function does not verify whether logical slots exist. The
 * checkpointer will verify if logical decoding should actually be disabled.
 *
 * This may be called during recovery, for example when a standby invalidates
 * its last valid logical slot. That is safe because the queued request is only
 * acted upon outside recovery. See the RecoveryInProgress() check in
 * DisableLogicalDecodingIfNecessary().
 */
void
RequestDisableLogicalDecoding(void)
{
    if (wal_level != WAL_LEVEL_REPLICA)
        return;
 
    /*
     * It's possible that we might not actually need to disable logical
     * decoding if someone creates a new logical slot concurrently. We set the
     * flag anyway and the checkpointer will check it and disable logical
     * decoding if necessary.
     */
    LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
    LogicalDecodingCtl->pending_disable = true;
    LWLockRelease(LogicalDecodingControlLock);
 
    WakeupCheckpointer();
 
    elog(DEBUG1, "requested disabling logical decoding");
}
 
/*
 * Disable logical decoding if necessary.
 *
 * This function disables logical decoding upon a request initiated by
 * RequestDisableLogicalDecoding(). Otherwise, it performs no action.
 */
void
DisableLogicalDecodingIfNecessary(void)
{
    bool        pending_disable;
 
    if (wal_level != WAL_LEVEL_REPLICA)
        return;
 
    /*
     * Sanity check as we cannot disable logical decoding while holding a
     * logical slot.
     */
    Assert(!MyReplicationSlot);
 
    /*
     * During recovery the logical decoding status follows the primary via WAL
     * replay, so we must not disable it here. A pending_disable request
     * queued during recovery, for example by a local slot invalidation, is
     * intentionally left for the end-of-recovery transition or the
     * post-promotion checkpointer to act on. See
     * UpdateLogicalDecodingStatusEndOfRecovery().
     */
    if (RecoveryInProgress())
        return;
 
    LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
    pending_disable = LogicalDecodingCtl->pending_disable;
    LWLockRelease(LogicalDecodingControlLock);
 
    /* Quick return if no pending disable request */
    if (!pending_disable)
        return;
 
    DisableLogicalDecoding();
}
 
/*
 * A workhorse function to disable logical decoding.
 */
void
DisableLogicalDecoding(void)
{
    bool        in_recovery = RecoveryInProgress();
    bool        was_enabled;
 
    LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
 
    /*
     * Check if we can disable logical decoding.
     *
     * Nothing to do if both flags are already off, or if valid slots exist
     * (skip the slot check during recovery because the existing slots will be
     * invalidated after disabling logical decoding.)
     */
    if ((!LogicalDecodingCtl->logical_decoding_enabled &&
         !LogicalDecodingCtl->xlog_logical_info) ||
        (!in_recovery && CheckLogicalSlotExists()))
    {
        LogicalDecodingCtl->pending_disable = false;
        LWLockRelease(LogicalDecodingControlLock);
        return;
    }
 
    /*
     * Remember if logical decoding was enabled. An interrupted activation can
     * leave xlog_logical_info=true while logical_decoding_enabled remains
     * false.
     */
    was_enabled = LogicalDecodingCtl->logical_decoding_enabled;
 
    START_CRIT_SECTION();
 
    /*
     * We need to disable logical decoding first and then disable logical
     * information WAL logging in order to ensure that no logical decoding
     * processes WAL records with insufficient information.
     */
    LogicalDecodingCtl->logical_decoding_enabled = false;
 
    /* Write the WAL to disable logical decoding on standbys too */
    if (!in_recovery && was_enabled)
        write_logical_decoding_status_update_record(false);
 
    /* Now disable logical information WAL logging */
    LogicalDecodingCtl->xlog_logical_info = false;
    LogicalDecodingCtl->pending_disable = false;
 
    END_CRIT_SECTION();
 
    /*
     * Logging under the lock guarantees our "is disabled" message appears in
     * the server log before its eventual "is enabled", making server log
     * diagnostics easy.
     */
    if (!in_recovery && was_enabled)
        ereport(LOG,
                errmsg("logical decoding is disabled because there are no valid logical replication slots"));
 
    LWLockRelease(LogicalDecodingControlLock);
 
    /*
     * Tell all running processes to reflect the xlog_logical_info update.
     * Unlike when enabling logical decoding, we don't need to wait for all
     * processes to complete it in this case. We already disabled logical
     * decoding and it's always safe to write logical information to WAL
     * records, even when not strictly required. Therefore, we don't need to
     * wait for all running transactions to finish either.
     */
    EmitProcSignalBarrier(PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO);
}
 
/*
 * Update the logical decoding status at end of recovery, synchronizing
 * process-local WAL logging state when necessary. This function must
 * be called before accepting writes.
 */
void
UpdateLogicalDecodingStatusEndOfRecovery(void)
{
    bool        new_status = false;
 
    Assert(RecoveryInProgress());
 
    LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
 
    /*
     * With 'minimal' WAL level, no logical replication slot can exist (see
     * RestoreSlotFromDisk()), so the new status is always false. However,
     * logical decoding could have been enabled during recovery by replaying
     * an XLOG_LOGICAL_DECODING_STATUS_CHANGE record from WAL generated with a
     * higher wal_level, e.g. if the server crashed right after the last
     * logical slot was dropped and then restarted with wal_level='minimal'.
     * The code below disables logical decoding in that case.
     */
    if (wal_level == WAL_LEVEL_LOGICAL || CheckLogicalSlotExists())
        new_status = true;
 
    /*
     * When recovery ends, we need to either enable or disable logical
     * decoding based on the wal_level setting and the presence of logical
     * slots. We need to note that concurrent slot creation and deletion could
     * happen but WAL writes are still not permitted until recovery fully
     * completes. Here's how we handle concurrent toggling of logical
     * decoding:
     *
     * For 'enable' case, if there's a concurrent disable request before
     * recovery fully completes, the checkpointer will handle it after
     * recovery is done. This means there might be a brief period after
     * recovery where logical decoding remains enabled even with no logical
     * replication slots present. This temporary state is not new - it can
     * already occur due to the checkpointer's asynchronous deactivation
     * process.
     *
     * For 'disable' case, a backend concurrently creating a logical slot on a
     * standby could have passed its CheckLogicalDecodingRequirements() check
     * when creating its slot only after our slot check above. Such a backend
     * rechecks the status after creating the slot in
     * EnsureLogicalDecodingEnabled() and raises an error if logical decoding
     * has been disabled meanwhile, so it cannot end up with a logical slot
     * while logical decoding remains disabled. (If recovery has already ended
     * by the time of the recheck, the backend instead enables logical
     * decoding by itself, which is fine after promotion.)
     */
    if (new_status != LogicalDecodingCtl->logical_decoding_enabled)
    {
        /*
         * Update both the logical decoding status and logical WAL logging
         * status. Unlike toggling these status during non-recovery, we don't
         * need to worry about the operation order as WAL writes are still not
         * permitted.
         */
        LogicalDecodingCtl->xlog_logical_info = new_status;
        LogicalDecodingCtl->logical_decoding_enabled = new_status;
 
        elog(DEBUG1,
             "update logical decoding status to %d at the end of recovery",
             new_status);
 
        /*
         * Now that we updated the logical decoding status, clear the pending
         * disable flag. It's possible that a concurrent process drops the
         * last logical slot and initiates the pending disable again. The
         * checkpointer process will check it.
         */
        LogicalDecodingCtl->pending_disable = false;
 
        LWLockRelease(LogicalDecodingControlLock);
 
        write_logical_decoding_status_update_record(new_status);
    }
    else
        LWLockRelease(LogicalDecodingControlLock);
 
    /*
     * With wal_level = logical, XLogLogicalInfoActive() is always true, so no
     * barrier is needed.
     *
     * Otherwise, notify all processes to refresh XLogLogicalInfo. Wait only
     * if new_status is true, even if the shared status is unchanged, since
     * recovery may have left stale caches. Writes are not yet allowed, so we
     * need not wait for running transactions to finish.
     *
     * If new_status is false, stale caches only cause extra logical
     * information in WAL, which is safe (see DisableLogicalDecoding()).
     */
    if (IsUnderPostmaster && wal_level != WAL_LEVEL_LOGICAL)
    {
        uint64      generation;
 
        generation = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO);
        if (new_status)
            WaitForProcSignalBarrier(generation);
    }
 
    INJECTION_POINT("startup-logical-decoding-status-change-end-of-recovery", NULL);
}