Coverage Report

Created: 2026-12-01 07:00

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