LCOV - code coverage report
Current view: top level - src/backend/replication/logical - sequencesync.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 89.9 % 248 223
Test Date: 2026-07-17 01:15:41 Functions: 100.0 % 9 9
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 64.4 % 146 94

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  * sequencesync.c
       3                 :             :  *    PostgreSQL logical replication: sequence synchronization
       4                 :             :  *
       5                 :             :  * Copyright (c) 2025-2026, PostgreSQL Global Development Group
       6                 :             :  *
       7                 :             :  * IDENTIFICATION
       8                 :             :  *    src/backend/replication/logical/sequencesync.c
       9                 :             :  *
      10                 :             :  * NOTES
      11                 :             :  *    This file contains code for sequence synchronization for
      12                 :             :  *    logical replication.
      13                 :             :  *
      14                 :             :  * Sequences requiring synchronization are tracked in the pg_subscription_rel
      15                 :             :  * catalog.
      16                 :             :  *
      17                 :             :  * Sequences to be synchronized will be added with state INIT when either of
      18                 :             :  * the following commands is executed:
      19                 :             :  * CREATE SUBSCRIPTION
      20                 :             :  * ALTER SUBSCRIPTION ... REFRESH PUBLICATION
      21                 :             :  *
      22                 :             :  * Executing the following command resets all sequences in the subscription to
      23                 :             :  * state INIT, triggering re-synchronization:
      24                 :             :  * ALTER SUBSCRIPTION ... REFRESH SEQUENCES
      25                 :             :  *
      26                 :             :  * The apply worker periodically scans pg_subscription_rel for sequences in
      27                 :             :  * INIT state. When such sequences are found, it spawns a sequencesync worker
      28                 :             :  * to handle synchronization.
      29                 :             :  *
      30                 :             :  * A single sequencesync worker is responsible for synchronizing all sequences.
      31                 :             :  * It begins by retrieving the list of sequences that are flagged for
      32                 :             :  * synchronization, i.e., those in the INIT state. These sequences are then
      33                 :             :  * processed in batches, allowing multiple entries to be synchronized within a
      34                 :             :  * single transaction. The worker fetches the current sequence values and page
      35                 :             :  * LSNs from the remote publisher, updates the corresponding sequences on the
      36                 :             :  * local subscriber, and finally marks each sequence as READY upon successful
      37                 :             :  * synchronization.
      38                 :             :  *
      39                 :             :  * Sequence state transitions follow this pattern:
      40                 :             :  *   INIT -> READY
      41                 :             :  *
      42                 :             :  * To avoid creating too many transactions, up to MAX_SEQUENCES_SYNC_PER_BATCH
      43                 :             :  * sequences are synchronized per transaction. The locks on the sequence
      44                 :             :  * relation will be periodically released at each transaction commit.
      45                 :             :  *
      46                 :             :  * XXX: We didn't choose launcher process to maintain the launch of sequencesync
      47                 :             :  * worker as it didn't have database connection to access the sequences from the
      48                 :             :  * pg_subscription_rel system catalog that need to be synchronized.
      49                 :             :  *-------------------------------------------------------------------------
      50                 :             :  */
      51                 :             : 
      52                 :             : #include "postgres.h"
      53                 :             : 
      54                 :             : #include "access/genam.h"
      55                 :             : #include "access/table.h"
      56                 :             : #include "catalog/pg_sequence.h"
      57                 :             : #include "catalog/pg_subscription_rel.h"
      58                 :             : #include "commands/sequence.h"
      59                 :             : #include "pgstat.h"
      60                 :             : #include "postmaster/interrupt.h"
      61                 :             : #include "replication/logicalworker.h"
      62                 :             : #include "replication/worker_internal.h"
      63                 :             : #include "storage/lwlock.h"
      64                 :             : #include "utils/acl.h"
      65                 :             : #include "utils/builtins.h"
      66                 :             : #include "utils/fmgroids.h"
      67                 :             : #include "utils/guc.h"
      68                 :             : #include "utils/inval.h"
      69                 :             : #include "utils/lsyscache.h"
      70                 :             : #include "utils/memutils.h"
      71                 :             : #include "utils/pg_lsn.h"
      72                 :             : #include "utils/syscache.h"
      73                 :             : #include "utils/usercontext.h"
      74                 :             : 
      75                 :             : #define REMOTE_SEQ_COL_COUNT 11
      76                 :             : 
      77                 :             : typedef enum CopySeqResult
      78                 :             : {
      79                 :             :     COPYSEQ_SUCCESS,
      80                 :             :     COPYSEQ_MISMATCH,
      81                 :             :     COPYSEQ_SUBSCRIBER_INSUFFICIENT_PERM,
      82                 :             :     COPYSEQ_PUBLISHER_INSUFFICIENT_PERM,
      83                 :             :     COPYSEQ_SKIPPED
      84                 :             : } CopySeqResult;
      85                 :             : 
      86                 :             : static List *seqinfos = NIL;
      87                 :             : 
      88                 :             : /*
      89                 :             :  * Apply worker determines if sequence synchronization is needed.
      90                 :             :  *
      91                 :             :  * Start a sequencesync worker if one is not already running. The active
      92                 :             :  * sequencesync worker will handle all pending sequence synchronization. If any
      93                 :             :  * sequences remain unsynchronized after it exits, a new worker can be started
      94                 :             :  * in the next iteration.
      95                 :             :  */
      96                 :             : void
      97                 :        9877 : ProcessSequencesForSync(void)
      98                 :             : {
      99                 :             :     LogicalRepWorker *sequencesync_worker;
     100                 :             :     int         nsyncworkers;
     101                 :             :     bool        has_pending_sequences;
     102                 :             :     bool        started_tx;
     103                 :             : 
     104                 :        9877 :     FetchRelationStates(NULL, &has_pending_sequences, &started_tx);
     105                 :             : 
     106         [ +  + ]:        9877 :     if (started_tx)
     107                 :             :     {
     108                 :         190 :         CommitTransactionCommand();
     109                 :         190 :         pgstat_report_stat(true);
     110                 :             :     }
     111                 :             : 
     112         [ +  + ]:        9877 :     if (!has_pending_sequences)
     113                 :        9851 :         return;
     114                 :             : 
     115                 :          44 :     LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
     116                 :             : 
     117                 :             :     /* Check if there is a sequencesync worker already running? */
     118                 :          44 :     sequencesync_worker = logicalrep_worker_find(WORKERTYPE_SEQUENCESYNC,
     119                 :          44 :                                                  MyLogicalRepWorker->subid,
     120                 :             :                                                  InvalidOid, true);
     121         [ +  + ]:          44 :     if (sequencesync_worker)
     122                 :             :     {
     123                 :          18 :         LWLockRelease(LogicalRepWorkerLock);
     124                 :          18 :         return;
     125                 :             :     }
     126                 :             : 
     127                 :             :     /*
     128                 :             :      * Count running sync workers for this subscription, while we have the
     129                 :             :      * lock.
     130                 :             :      */
     131                 :          26 :     nsyncworkers = logicalrep_sync_worker_count(MyLogicalRepWorker->subid);
     132                 :          26 :     LWLockRelease(LogicalRepWorkerLock);
     133                 :             : 
     134                 :             :     /*
     135                 :             :      * It is okay to read/update last_seqsync_start_time here in apply worker
     136                 :             :      * as we have already ensured that sync worker doesn't exist.
     137                 :             :      */
     138                 :          26 :     launch_sync_worker(WORKERTYPE_SEQUENCESYNC, nsyncworkers, InvalidOid,
     139                 :          26 :                        &MyLogicalRepWorker->last_seqsync_start_time);
     140                 :             : }
     141                 :             : 
     142                 :             : /*
     143                 :             :  * get_sequences_string
     144                 :             :  *
     145                 :             :  * Build a comma-separated string of schema-qualified sequence names
     146                 :             :  * for the given list of sequence indexes.
     147                 :             :  */
     148                 :             : static void
     149                 :           7 : get_sequences_string(List *seqindexes, StringInfo buf)
     150                 :             : {
     151                 :           7 :     resetStringInfo(buf);
     152   [ +  -  +  +  :          21 :     foreach_int(seqidx, seqindexes)
                   +  + ]
     153                 :             :     {
     154                 :             :         LogicalRepSequenceInfo *seqinfo =
     155                 :           7 :             (LogicalRepSequenceInfo *) list_nth(seqinfos, seqidx);
     156                 :             : 
     157         [ -  + ]:           7 :         if (buf->len > 0)
     158                 :           0 :             appendStringInfoString(buf, ", ");
     159                 :             : 
     160                 :           7 :         appendStringInfo(buf, "\"%s.%s\"", seqinfo->nspname, seqinfo->seqname);
     161                 :             :     }
     162                 :           7 : }
     163                 :             : 
     164                 :             : /*
     165                 :             :  * report_sequence_errors
     166                 :             :  *
     167                 :             :  * Report discrepancies found during sequence synchronization between
     168                 :             :  * the publisher and subscriber. Emits warnings for:
     169                 :             :  * a) mismatched definitions or concurrent rename
     170                 :             :  * b) insufficient privileges on the subscriber
     171                 :             :  * c) insufficient privileges on the publisher
     172                 :             :  * d) missing sequences on the publisher
     173                 :             :  * Then raises an ERROR to indicate synchronization failure.
     174                 :             :  */
     175                 :             : static void
     176                 :          14 : report_sequence_errors(List *mismatched_seqs_idx,
     177                 :             :                        List *sub_insuffperm_seqs_idx,
     178                 :             :                        List *pub_insuffperm_seqs_idx,
     179                 :             :                        List *missing_seqs_idx)
     180                 :             : {
     181                 :             :     StringInfoData seqstr;
     182                 :             : 
     183                 :             :     /* Quick exit if there are no errors to report */
     184   [ +  +  +  -  :          14 :     if (!mismatched_seqs_idx && !sub_insuffperm_seqs_idx &&
                   +  + ]
     185         [ +  + ]:          10 :         !pub_insuffperm_seqs_idx && !missing_seqs_idx)
     186                 :           7 :         return;
     187                 :             : 
     188                 :           7 :     initStringInfo(&seqstr);
     189                 :             : 
     190         [ +  + ]:           7 :     if (mismatched_seqs_idx)
     191                 :             :     {
     192                 :           3 :         get_sequences_string(mismatched_seqs_idx, &seqstr);
     193         [ +  - ]:           3 :         ereport(WARNING,
     194                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     195                 :             :                 errmsg_plural("mismatched or renamed sequence on subscriber (%s)",
     196                 :             :                               "mismatched or renamed sequences on subscriber (%s)",
     197                 :             :                               list_length(mismatched_seqs_idx),
     198                 :             :                               seqstr.data));
     199                 :             :     }
     200                 :             : 
     201         [ -  + ]:           7 :     if (sub_insuffperm_seqs_idx)
     202                 :             :     {
     203                 :           0 :         get_sequences_string(sub_insuffperm_seqs_idx, &seqstr);
     204                 :             : 
     205                 :             :         /*
     206                 :             :          * With run_as_owner enabled, sequence synchronization runs as the
     207                 :             :          * subscription owner, so a missing UPDATE privilege should be granted
     208                 :             :          * to that role. Otherwise, the worker switches to the sequence owner
     209                 :             :          * before checking privileges, so no useful GRANT hint can be
     210                 :             :          * provided.
     211                 :             :          */
     212   [ #  #  #  # ]:           0 :         ereport(WARNING,
     213                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     214                 :             :                 errmsg_plural("insufficient privileges on subscriber sequence (%s)",
     215                 :             :                               "insufficient privileges on subscriber sequences (%s)",
     216                 :             :                               list_length(sub_insuffperm_seqs_idx),
     217                 :             :                               seqstr.data),
     218                 :             :                 MySubscription->runasowner ?
     219                 :             :                 errhint_plural("Grant UPDATE on the sequence to the subscription "
     220                 :             :                                "owner on the subscriber.",
     221                 :             :                                "Grant UPDATE on the sequences to the subscription "
     222                 :             :                                "owner on the subscriber.",
     223                 :             :                                list_length(sub_insuffperm_seqs_idx)) : 0);
     224                 :             :     }
     225                 :             : 
     226         [ +  + ]:           7 :     if (pub_insuffperm_seqs_idx)
     227                 :             :     {
     228                 :           1 :         get_sequences_string(pub_insuffperm_seqs_idx, &seqstr);
     229         [ +  - ]:           1 :         ereport(WARNING,
     230                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     231                 :             :                 errmsg_plural("insufficient privileges on publisher sequence (%s)",
     232                 :             :                               "insufficient privileges on publisher sequences (%s)",
     233                 :             :                               list_length(pub_insuffperm_seqs_idx),
     234                 :             :                               seqstr.data),
     235                 :             :                 errhint_plural("Grant SELECT on the sequence to the role used for "
     236                 :             :                                "the replication connection on the publisher.",
     237                 :             :                                "Grant SELECT on the sequences to the role used for "
     238                 :             :                                "the replication connection on the publisher.",
     239                 :             :                                list_length(pub_insuffperm_seqs_idx)));
     240                 :             :     }
     241                 :             : 
     242         [ +  + ]:           7 :     if (missing_seqs_idx)
     243                 :             :     {
     244                 :           3 :         get_sequences_string(missing_seqs_idx, &seqstr);
     245         [ +  - ]:           3 :         ereport(WARNING,
     246                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     247                 :             :                 errmsg_plural("missing sequence on publisher (%s)",
     248                 :             :                               "missing sequences on publisher (%s)",
     249                 :             :                               list_length(missing_seqs_idx),
     250                 :             :                               seqstr.data));
     251                 :             :     }
     252                 :             : 
     253         [ +  - ]:           7 :     ereport(ERROR,
     254                 :             :             errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     255                 :             :             errmsg("logical replication sequence synchronization failed for subscription \"%s\"",
     256                 :             :                    MySubscription->name));
     257                 :             : }
     258                 :             : 
     259                 :             : /*
     260                 :             :  * get_and_validate_seq_info
     261                 :             :  *
     262                 :             :  * Extracts remote sequence information from the tuple slot received from the
     263                 :             :  * publisher, and validates it against the corresponding local sequence
     264                 :             :  * definition.
     265                 :             :  */
     266                 :             : static CopySeqResult
     267                 :          27 : get_and_validate_seq_info(TupleTableSlot *slot, Relation *sequence_rel,
     268                 :             :                           LogicalRepSequenceInfo **seqinfo, int *seqidx)
     269                 :             : {
     270                 :             :     bool        isnull;
     271                 :          27 :     int         col = 0;
     272                 :             :     Datum       datum;
     273                 :             :     bool        remote_has_select_priv;
     274                 :             :     Oid         remote_typid;
     275                 :             :     int64       remote_start;
     276                 :             :     int64       remote_increment;
     277                 :             :     int64       remote_min;
     278                 :             :     int64       remote_max;
     279                 :             :     bool        remote_cycle;
     280                 :          27 :     CopySeqResult result = COPYSEQ_SUCCESS;
     281                 :             :     HeapTuple   tup;
     282                 :             :     Form_pg_sequence local_seq;
     283                 :             :     LogicalRepSequenceInfo *seqinfo_local;
     284                 :             : 
     285                 :          27 :     *seqidx = DatumGetInt32(slot_getattr(slot, ++col, &isnull));
     286                 :             :     Assert(!isnull);
     287                 :             : 
     288                 :             :     /* Identify the corresponding local sequence for the given index. */
     289                 :          27 :     *seqinfo = seqinfo_local =
     290                 :          27 :         (LogicalRepSequenceInfo *) list_nth(seqinfos, *seqidx);
     291                 :             : 
     292                 :             :     /*
     293                 :             :      * has_sequence_privilege() itself returns NULL, rather than false, when
     294                 :             :      * the sequence has been dropped concurrently after it was identified in
     295                 :             :      * the catalog snapshot (see has_sequence_privilege_id()). Treat that as a
     296                 :             :      * missing sequence on the publisher.
     297                 :             :      */
     298                 :          27 :     datum = slot_getattr(slot, ++col, &isnull);
     299         [ +  + ]:          27 :     if (isnull)
     300                 :           1 :         return COPYSEQ_SKIPPED;
     301                 :             : 
     302                 :          26 :     remote_has_select_priv = DatumGetBool(datum);
     303                 :             : 
     304                 :             :     /*
     305                 :             :      * The remote sequence state can be NULL if the publisher lacks the
     306                 :             :      * required privileges or if the sequence was dropped concurrently after
     307                 :             :      * it was identified in the catalog snapshot (see pg_get_sequence_data()).
     308                 :             :      */
     309                 :          26 :     datum = slot_getattr(slot, ++col, &isnull);
     310         [ +  + ]:          26 :     if (isnull)
     311         [ -  + ]:           1 :         return remote_has_select_priv ? COPYSEQ_SKIPPED :
     312                 :             :             COPYSEQ_PUBLISHER_INSUFFICIENT_PERM;
     313                 :             : 
     314                 :          25 :     seqinfo_local->last_value = DatumGetInt64(datum);
     315                 :             : 
     316                 :          25 :     seqinfo_local->is_called = DatumGetBool(slot_getattr(slot, ++col, &isnull));
     317                 :             :     Assert(!isnull);
     318                 :             : 
     319                 :          25 :     seqinfo_local->page_lsn = DatumGetLSN(slot_getattr(slot, ++col, &isnull));
     320                 :             :     Assert(!isnull);
     321                 :             : 
     322                 :          25 :     remote_typid = DatumGetObjectId(slot_getattr(slot, ++col, &isnull));
     323                 :             :     Assert(!isnull);
     324                 :             : 
     325                 :          25 :     remote_start = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
     326                 :             :     Assert(!isnull);
     327                 :             : 
     328                 :          25 :     remote_increment = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
     329                 :             :     Assert(!isnull);
     330                 :             : 
     331                 :          25 :     remote_min = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
     332                 :             :     Assert(!isnull);
     333                 :             : 
     334                 :          25 :     remote_max = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
     335                 :             :     Assert(!isnull);
     336                 :             : 
     337                 :          25 :     remote_cycle = DatumGetBool(slot_getattr(slot, ++col, &isnull));
     338                 :             :     Assert(!isnull);
     339                 :             : 
     340                 :             :     /* Sanity check */
     341                 :             :     Assert(col == REMOTE_SEQ_COL_COUNT);
     342                 :             : 
     343                 :          25 :     seqinfo_local->found_on_pub = true;
     344                 :             : 
     345                 :          25 :     *sequence_rel = try_table_open(seqinfo_local->localrelid, RowExclusiveLock);
     346                 :             : 
     347                 :             :     /* Sequence was concurrently dropped? */
     348         [ -  + ]:          25 :     if (!*sequence_rel)
     349                 :           0 :         return COPYSEQ_SKIPPED;
     350                 :             : 
     351                 :          25 :     tup = SearchSysCache1(SEQRELID, ObjectIdGetDatum(seqinfo_local->localrelid));
     352                 :             : 
     353                 :             :     /* Sequence was concurrently dropped? */
     354         [ -  + ]:          25 :     if (!HeapTupleIsValid(tup))
     355         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for sequence %u",
     356                 :             :              seqinfo_local->localrelid);
     357                 :             : 
     358                 :          25 :     local_seq = (Form_pg_sequence) GETSTRUCT(tup);
     359                 :             : 
     360                 :             :     /* Sequence parameters for remote/local are the same? */
     361         [ +  - ]:          25 :     if (local_seq->seqtypid != remote_typid ||
     362         [ +  + ]:          25 :         local_seq->seqstart != remote_start ||
     363         [ +  + ]:          24 :         local_seq->seqincrement != remote_increment ||
     364         [ +  - ]:          22 :         local_seq->seqmin != remote_min ||
     365         [ +  - ]:          22 :         local_seq->seqmax != remote_max ||
     366         [ -  + ]:          22 :         local_seq->seqcycle != remote_cycle)
     367                 :           3 :         result = COPYSEQ_MISMATCH;
     368                 :             : 
     369                 :             :     /* Sequence was concurrently renamed? */
     370         [ +  - ]:          25 :     if (strcmp(seqinfo_local->nspname,
     371                 :          25 :                get_namespace_name(RelationGetNamespace(*sequence_rel))) ||
     372         [ -  + ]:          25 :         strcmp(seqinfo_local->seqname, RelationGetRelationName(*sequence_rel)))
     373                 :           0 :         result = COPYSEQ_MISMATCH;
     374                 :             : 
     375                 :          25 :     ReleaseSysCache(tup);
     376                 :          25 :     return result;
     377                 :             : }
     378                 :             : 
     379                 :             : /*
     380                 :             :  * Apply remote sequence state to local sequence and mark it as
     381                 :             :  * synchronized (READY).
     382                 :             :  */
     383                 :             : static CopySeqResult
     384                 :          22 : copy_sequence(LogicalRepSequenceInfo *seqinfo, Oid seqowner)
     385                 :             : {
     386                 :             :     UserContext ucxt;
     387                 :             :     AclResult   aclresult;
     388                 :          22 :     bool        run_as_owner = MySubscription->runasowner;
     389                 :          22 :     Oid         seqoid = seqinfo->localrelid;
     390                 :             : 
     391                 :             :     /*
     392                 :             :      * If the user did not opt to run as the owner of the subscription
     393                 :             :      * ('run_as_owner'), then copy the sequence as the owner of the sequence.
     394                 :             :      */
     395         [ +  - ]:          22 :     if (!run_as_owner)
     396                 :          22 :         SwitchToUntrustedUser(seqowner, &ucxt);
     397                 :             : 
     398                 :          22 :     aclresult = pg_class_aclcheck(seqoid, GetUserId(), ACL_UPDATE);
     399                 :             : 
     400         [ -  + ]:          22 :     if (aclresult != ACLCHECK_OK)
     401                 :             :     {
     402         [ #  # ]:           0 :         if (!run_as_owner)
     403                 :           0 :             RestoreUserContext(&ucxt);
     404                 :             : 
     405                 :           0 :         return COPYSEQ_SUBSCRIBER_INSUFFICIENT_PERM;
     406                 :             :     }
     407                 :             : 
     408                 :             :     /*
     409                 :             :      * The log counter (log_cnt) tracks how many sequence values are still
     410                 :             :      * unused locally. It is only relevant to the local node and managed
     411                 :             :      * internally by nextval() when allocating new ranges. Since log_cnt does
     412                 :             :      * not affect the visible sequence state (like last_value or is_called)
     413                 :             :      * and is only used for local caching, it need not be copied to the
     414                 :             :      * subscriber during synchronization.
     415                 :             :      */
     416                 :          22 :     SetSequence(seqoid, seqinfo->last_value, seqinfo->is_called);
     417                 :             : 
     418         [ +  - ]:          22 :     if (!run_as_owner)
     419                 :          22 :         RestoreUserContext(&ucxt);
     420                 :             : 
     421                 :             :     /*
     422                 :             :      * Record the remote sequence's LSN in pg_subscription_rel and mark the
     423                 :             :      * sequence as READY.
     424                 :             :      */
     425                 :          22 :     UpdateSubscriptionRelState(MySubscription->oid, seqoid, SUBREL_STATE_READY,
     426                 :             :                                seqinfo->page_lsn, false);
     427                 :             : 
     428                 :          22 :     return COPYSEQ_SUCCESS;
     429                 :             : }
     430                 :             : 
     431                 :             : /*
     432                 :             :  * Copy existing data of sequences from the publisher.
     433                 :             :  */
     434                 :             : static void
     435                 :          14 : copy_sequences(WalReceiverConn *conn)
     436                 :             : {
     437                 :          14 :     int         cur_batch_base_index = 0;
     438                 :          14 :     int         n_seqinfos = list_length(seqinfos);
     439                 :          14 :     List       *mismatched_seqs_idx = NIL;
     440                 :          14 :     List       *missing_seqs_idx = NIL;
     441                 :          14 :     List       *sub_insuffperm_seqs_idx = NIL;
     442                 :          14 :     List       *pub_insuffperm_seqs_idx = NIL;
     443                 :             :     StringInfoData seqstr;
     444                 :             :     StringInfoData cmd;
     445                 :             :     MemoryContext oldctx;
     446                 :             : 
     447                 :          14 :     initStringInfo(&seqstr);
     448                 :          14 :     initStringInfo(&cmd);
     449                 :             : 
     450                 :             : #define MAX_SEQUENCES_SYNC_PER_BATCH 100
     451                 :             : 
     452         [ -  + ]:          14 :     elog(DEBUG1,
     453                 :             :          "logical replication sequence synchronization for subscription \"%s\" - total unsynchronized: %d",
     454                 :             :          MySubscription->name, n_seqinfos);
     455                 :             : 
     456         [ +  + ]:          28 :     while (cur_batch_base_index < n_seqinfos)
     457                 :             :     {
     458                 :          14 :         Oid         seqRow[REMOTE_SEQ_COL_COUNT] = {INT8OID, BOOLOID, INT8OID,
     459                 :             :         BOOLOID, LSNOID, OIDOID, INT8OID, INT8OID, INT8OID, INT8OID, BOOLOID};
     460                 :          14 :         int         batch_size = 0;
     461                 :          14 :         int         batch_succeeded_count = 0;
     462                 :          14 :         int         batch_mismatched_count = 0;
     463                 :          14 :         int         batch_skipped_count = 0;
     464                 :          14 :         int         batch_sub_insuffperm_count = 0;
     465                 :          14 :         int         batch_pub_insuffperm_count = 0;
     466                 :             :         int         batch_missing_count;
     467                 :             : 
     468                 :             :         WalRcvExecResult *res;
     469                 :             :         TupleTableSlot *slot;
     470                 :             : 
     471                 :          14 :         StartTransactionCommand();
     472                 :             : 
     473         [ +  + ]:          43 :         for (int idx = cur_batch_base_index; idx < n_seqinfos; idx++)
     474                 :             :         {
     475                 :             :             char       *nspname_literal;
     476                 :             :             char       *seqname_literal;
     477                 :             : 
     478                 :             :             LogicalRepSequenceInfo *seqinfo =
     479                 :          29 :                 (LogicalRepSequenceInfo *) list_nth(seqinfos, idx);
     480                 :             : 
     481         [ +  + ]:          29 :             if (seqstr.len > 0)
     482                 :          15 :                 appendStringInfoString(&seqstr, ", ");
     483                 :             : 
     484                 :          29 :             nspname_literal = quote_literal_cstr(seqinfo->nspname);
     485                 :          29 :             seqname_literal = quote_literal_cstr(seqinfo->seqname);
     486                 :             : 
     487                 :          29 :             appendStringInfo(&seqstr, "(%s, %s, %d)",
     488                 :             :                              nspname_literal, seqname_literal, idx);
     489                 :             : 
     490         [ -  + ]:          29 :             if (++batch_size == MAX_SEQUENCES_SYNC_PER_BATCH)
     491                 :           0 :                 break;
     492                 :             :         }
     493                 :             : 
     494                 :             :         /*
     495                 :             :          * We deliberately avoid acquiring a local lock on the sequence before
     496                 :             :          * querying the publisher to prevent potential distributed deadlocks
     497                 :             :          * in bi-directional replication setups.
     498                 :             :          *
     499                 :             :          * Example scenario:
     500                 :             :          *
     501                 :             :          * - On each node, a background worker acquires a lock on a sequence
     502                 :             :          * as part of a sync operation.
     503                 :             :          *
     504                 :             :          * - Concurrently, a user transaction attempts to alter the same
     505                 :             :          * sequence, waiting on the background worker's lock.
     506                 :             :          *
     507                 :             :          * - Meanwhile, a query from the other node tries to access metadata
     508                 :             :          * that depends on the completion of the alter operation.
     509                 :             :          *
     510                 :             :          * - This creates a circular wait across nodes:
     511                 :             :          *
     512                 :             :          * Node-1: Query -> waits on Alter -> waits on Sync Worker
     513                 :             :          *
     514                 :             :          * Node-2: Query -> waits on Alter -> waits on Sync Worker
     515                 :             :          *
     516                 :             :          * Since each node only sees part of the wait graph, the deadlock may
     517                 :             :          * go undetected, leading to indefinite blocking.
     518                 :             :          *
     519                 :             :          * Note: Each entry in VALUES includes an index 'seqidx' that
     520                 :             :          * represents the sequence's position in the local 'seqinfos' list.
     521                 :             :          * This index is propagated to the query results and later used to
     522                 :             :          * directly map the fetched publisher sequence rows back to their
     523                 :             :          * corresponding local entries without relying on result order or name
     524                 :             :          * matching.
     525                 :             :          */
     526                 :          14 :         appendStringInfo(&cmd,
     527                 :             :                          "SELECT s.seqidx, has_sequence_privilege(c.oid, 'SELECT'),\n"
     528                 :             :                          "       ps.*, seq.seqtypid,\n"
     529                 :             :                          "       seq.seqstart, seq.seqincrement, seq.seqmin,\n"
     530                 :             :                          "       seq.seqmax, seq.seqcycle\n"
     531                 :             :                          "FROM ( VALUES %s ) AS s (schname, seqname, seqidx)\n"
     532                 :             :                          "JOIN pg_namespace n ON n.nspname = s.schname\n"
     533                 :             :                          "JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = s.seqname\n"
     534                 :             :                          "JOIN pg_sequence seq ON seq.seqrelid = c.oid\n"
     535                 :             :                          "JOIN LATERAL pg_get_sequence_data(seq.seqrelid) AS ps ON true\n",
     536                 :             :                          seqstr.data);
     537                 :             : 
     538                 :          14 :         res = walrcv_exec(conn, cmd.data, lengthof(seqRow), seqRow);
     539         [ -  + ]:          14 :         if (res->status != WALRCV_OK_TUPLES)
     540         [ #  # ]:           0 :             ereport(ERROR,
     541                 :             :                     errcode(ERRCODE_CONNECTION_FAILURE),
     542                 :             :                     errmsg("could not fetch sequence information from the publisher: %s",
     543                 :             :                            res->err));
     544                 :             : 
     545                 :          14 :         slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
     546         [ +  + ]:          41 :         while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
     547                 :             :         {
     548                 :             :             CopySeqResult sync_status;
     549                 :             :             LogicalRepSequenceInfo *seqinfo;
     550                 :          27 :             Relation    sequence_rel = NULL;
     551                 :             :             int         seqidx;
     552                 :             : 
     553         [ -  + ]:          27 :             CHECK_FOR_INTERRUPTS();
     554                 :             : 
     555         [ -  + ]:          27 :             if (ConfigReloadPending)
     556                 :             :             {
     557                 :           0 :                 ConfigReloadPending = false;
     558                 :           0 :                 ProcessConfigFile(PGC_SIGHUP);
     559                 :             :             }
     560                 :             : 
     561                 :          27 :             sync_status = get_and_validate_seq_info(slot, &sequence_rel,
     562                 :             :                                                     &seqinfo, &seqidx);
     563         [ +  + ]:          27 :             if (sync_status == COPYSEQ_SUCCESS)
     564                 :          22 :                 sync_status = copy_sequence(seqinfo,
     565                 :          22 :                                             sequence_rel->rd_rel->relowner);
     566                 :             : 
     567   [ +  +  -  +  :          27 :             switch (sync_status)
                   +  - ]
     568                 :             :             {
     569                 :          22 :                 case COPYSEQ_SUCCESS:
     570         [ -  + ]:          22 :                     elog(DEBUG1,
     571                 :             :                          "logical replication synchronization for subscription \"%s\", sequence \"%s.%s\" has finished",
     572                 :             :                          MySubscription->name, seqinfo->nspname,
     573                 :             :                          seqinfo->seqname);
     574                 :          22 :                     batch_succeeded_count++;
     575                 :          22 :                     break;
     576                 :           3 :                 case COPYSEQ_MISMATCH:
     577                 :             : 
     578                 :             :                     /*
     579                 :             :                      * Remember mismatched sequences in a long-lived memory
     580                 :             :                      * context since these will be used after the transaction
     581                 :             :                      * is committed.
     582                 :             :                      */
     583                 :           3 :                     oldctx = MemoryContextSwitchTo(ApplyContext);
     584                 :           3 :                     mismatched_seqs_idx = lappend_int(mismatched_seqs_idx,
     585                 :             :                                                       seqidx);
     586                 :           3 :                     MemoryContextSwitchTo(oldctx);
     587                 :           3 :                     batch_mismatched_count++;
     588                 :           3 :                     break;
     589                 :           0 :                 case COPYSEQ_SUBSCRIBER_INSUFFICIENT_PERM:
     590                 :             : 
     591                 :             :                     /*
     592                 :             :                      * Remember sequences with insufficient privileges in a
     593                 :             :                      * long-lived memory context since these will be used
     594                 :             :                      * after the transaction is committed.
     595                 :             :                      */
     596                 :           0 :                     oldctx = MemoryContextSwitchTo(ApplyContext);
     597                 :           0 :                     sub_insuffperm_seqs_idx = lappend_int(sub_insuffperm_seqs_idx,
     598                 :             :                                                           seqidx);
     599                 :           0 :                     MemoryContextSwitchTo(oldctx);
     600                 :           0 :                     batch_sub_insuffperm_count++;
     601                 :           0 :                     break;
     602                 :           1 :                 case COPYSEQ_PUBLISHER_INSUFFICIENT_PERM:
     603                 :             : 
     604                 :             :                     /*
     605                 :             :                      * Remember sequences for which the publisher lacks the
     606                 :             :                      * privileges required by pg_get_sequence_data().
     607                 :             :                      */
     608                 :           1 :                     oldctx = MemoryContextSwitchTo(ApplyContext);
     609                 :           1 :                     pub_insuffperm_seqs_idx = lappend_int(pub_insuffperm_seqs_idx,
     610                 :             :                                                           seqidx);
     611                 :           1 :                     MemoryContextSwitchTo(oldctx);
     612                 :           1 :                     batch_pub_insuffperm_count++;
     613                 :           1 :                     break;
     614                 :           1 :                 case COPYSEQ_SKIPPED:
     615                 :             : 
     616                 :             :                     /*
     617                 :             :                      * Concurrent removal of a sequence on the subscriber is
     618                 :             :                      * treated as success, since the only viable action is to
     619                 :             :                      * skip the corresponding sequence data. Missing sequences
     620                 :             :                      * on the publisher are treated as ERROR.
     621                 :             :                      */
     622         [ -  + ]:           1 :                     if (seqinfo->found_on_pub)
     623                 :             :                     {
     624         [ #  # ]:           0 :                         ereport(LOG,
     625                 :             :                                 errmsg("skip synchronization of sequence \"%s.%s\" because it has been dropped concurrently",
     626                 :             :                                        seqinfo->nspname,
     627                 :             :                                        seqinfo->seqname));
     628                 :           0 :                         batch_skipped_count++;
     629                 :             :                     }
     630                 :           1 :                     break;
     631                 :             :             }
     632                 :             : 
     633         [ +  + ]:          27 :             if (sequence_rel)
     634                 :          25 :                 table_close(sequence_rel, NoLock);
     635                 :             :         }
     636                 :             : 
     637                 :          14 :         ExecDropSingleTupleTableSlot(slot);
     638                 :          14 :         walrcv_clear_result(res);
     639                 :          14 :         resetStringInfo(&seqstr);
     640                 :          14 :         resetStringInfo(&cmd);
     641                 :             : 
     642                 :          14 :         batch_missing_count = batch_size - (batch_succeeded_count +
     643                 :          14 :                                             batch_mismatched_count +
     644                 :          14 :                                             batch_sub_insuffperm_count +
     645                 :          14 :                                             batch_pub_insuffperm_count +
     646                 :             :                                             batch_skipped_count);
     647                 :             : 
     648         [ -  + ]:          14 :         elog(DEBUG1,
     649                 :             :              "logical replication sequence synchronization for subscription \"%s\" - batch #%d = %d attempted, %d succeeded, %d mismatched, %d subscriber insufficient permission, %d publisher insufficient permission, %d missing from publisher, %d skipped",
     650                 :             :              MySubscription->name,
     651                 :             :              (cur_batch_base_index / MAX_SEQUENCES_SYNC_PER_BATCH) + 1,
     652                 :             :              batch_size, batch_succeeded_count, batch_mismatched_count,
     653                 :             :              batch_sub_insuffperm_count, batch_pub_insuffperm_count, batch_missing_count, batch_skipped_count);
     654                 :             : 
     655                 :             :         /* Commit this batch, and prepare for next batch */
     656                 :          14 :         CommitTransactionCommand();
     657                 :             : 
     658         [ +  + ]:          14 :         if (batch_missing_count)
     659                 :             :         {
     660         [ +  + ]:          13 :             for (int idx = cur_batch_base_index; idx < cur_batch_base_index + batch_size; idx++)
     661                 :             :             {
     662                 :             :                 LogicalRepSequenceInfo *seqinfo =
     663                 :          10 :                     (LogicalRepSequenceInfo *) list_nth(seqinfos, idx);
     664                 :             : 
     665                 :             :                 /* If the sequence was not found on publisher, record it */
     666         [ +  + ]:          10 :                 if (!seqinfo->found_on_pub)
     667                 :           3 :                     missing_seqs_idx = lappend_int(missing_seqs_idx, idx);
     668                 :             :             }
     669                 :             :         }
     670                 :             : 
     671                 :             :         /*
     672                 :             :          * cur_batch_base_index is not incremented sequentially because some
     673                 :             :          * sequences may be missing, and the number of fetched rows may not
     674                 :             :          * match the batch size.
     675                 :             :          */
     676                 :          14 :         cur_batch_base_index += batch_size;
     677                 :             :     }
     678                 :             : 
     679                 :             :     /* Report mismatches, permission issues, or missing sequences */
     680                 :          14 :     report_sequence_errors(mismatched_seqs_idx, sub_insuffperm_seqs_idx,
     681                 :             :                            pub_insuffperm_seqs_idx, missing_seqs_idx);
     682                 :           7 : }
     683                 :             : 
     684                 :             : /*
     685                 :             :  * Identifies sequences that require synchronization and initiates the
     686                 :             :  * synchronization process.
     687                 :             :  */
     688                 :             : static void
     689                 :          14 : LogicalRepSyncSequences(void)
     690                 :             : {
     691                 :             :     char       *err;
     692                 :             :     bool        must_use_password;
     693                 :             :     Relation    rel;
     694                 :             :     HeapTuple   tup;
     695                 :             :     ScanKeyData skey[2];
     696                 :             :     SysScanDesc scan;
     697                 :          14 :     Oid         subid = MyLogicalRepWorker->subid;
     698                 :             :     StringInfoData app_name;
     699                 :             : 
     700                 :          14 :     StartTransactionCommand();
     701                 :             : 
     702                 :          14 :     rel = table_open(SubscriptionRelRelationId, AccessShareLock);
     703                 :             : 
     704                 :          14 :     ScanKeyInit(&skey[0],
     705                 :             :                 Anum_pg_subscription_rel_srsubid,
     706                 :             :                 BTEqualStrategyNumber, F_OIDEQ,
     707                 :             :                 ObjectIdGetDatum(subid));
     708                 :             : 
     709                 :          14 :     ScanKeyInit(&skey[1],
     710                 :             :                 Anum_pg_subscription_rel_srsubstate,
     711                 :             :                 BTEqualStrategyNumber, F_CHAREQ,
     712                 :             :                 CharGetDatum(SUBREL_STATE_INIT));
     713                 :             : 
     714                 :          14 :     scan = systable_beginscan(rel, InvalidOid, false,
     715                 :             :                               NULL, 2, skey);
     716         [ +  + ]:          44 :     while (HeapTupleIsValid(tup = systable_getnext(scan)))
     717                 :             :     {
     718                 :             :         Form_pg_subscription_rel subrel;
     719                 :             :         LogicalRepSequenceInfo *seq;
     720                 :             :         Relation    sequence_rel;
     721                 :             :         MemoryContext oldctx;
     722                 :             : 
     723         [ -  + ]:          30 :         CHECK_FOR_INTERRUPTS();
     724                 :             : 
     725                 :          30 :         subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
     726                 :             : 
     727                 :          30 :         sequence_rel = try_table_open(subrel->srrelid, RowExclusiveLock);
     728                 :             : 
     729                 :             :         /* Skip if sequence was dropped concurrently */
     730         [ -  + ]:          30 :         if (!sequence_rel)
     731                 :           0 :             continue;
     732                 :             : 
     733                 :             :         /* Skip if the relation is not a sequence */
     734         [ +  + ]:          30 :         if (sequence_rel->rd_rel->relkind != RELKIND_SEQUENCE)
     735                 :             :         {
     736                 :           1 :             table_close(sequence_rel, NoLock);
     737                 :           1 :             continue;
     738                 :             :         }
     739                 :             : 
     740                 :             :         /*
     741                 :             :          * Worker needs to process sequences across transaction boundary, so
     742                 :             :          * allocate them under long-lived context.
     743                 :             :          */
     744                 :          29 :         oldctx = MemoryContextSwitchTo(ApplyContext);
     745                 :             : 
     746                 :          29 :         seq = palloc0_object(LogicalRepSequenceInfo);
     747                 :          29 :         seq->localrelid = subrel->srrelid;
     748                 :          29 :         seq->nspname = get_namespace_name(RelationGetNamespace(sequence_rel));
     749                 :          29 :         seq->seqname = pstrdup(RelationGetRelationName(sequence_rel));
     750                 :          29 :         seqinfos = lappend(seqinfos, seq);
     751                 :             : 
     752                 :          29 :         MemoryContextSwitchTo(oldctx);
     753                 :             : 
     754                 :          29 :         table_close(sequence_rel, NoLock);
     755                 :             :     }
     756                 :             : 
     757                 :             :     /* Cleanup */
     758                 :          14 :     systable_endscan(scan);
     759                 :          14 :     table_close(rel, AccessShareLock);
     760                 :             : 
     761                 :          14 :     CommitTransactionCommand();
     762                 :             : 
     763                 :             :     /*
     764                 :             :      * Exit early if no catalog entries found, likely due to concurrent drops.
     765                 :             :      */
     766         [ -  + ]:          14 :     if (!seqinfos)
     767                 :           0 :         return;
     768                 :             : 
     769                 :             :     /* Is the use of a password mandatory? */
     770         [ +  - ]:          28 :     must_use_password = MySubscription->passwordrequired &&
     771         [ -  + ]:          14 :         !MySubscription->ownersuperuser;
     772                 :             : 
     773                 :          14 :     initStringInfo(&app_name);
     774                 :          14 :     appendStringInfo(&app_name, "pg_%u_sequence_sync_" UINT64_FORMAT,
     775                 :          14 :                      MySubscription->oid, GetSystemIdentifier());
     776                 :             : 
     777                 :             :     /*
     778                 :             :      * Establish the connection to the publisher for sequence synchronization.
     779                 :             :      */
     780                 :          14 :     LogRepWorkerWalRcvConn =
     781                 :          14 :         walrcv_connect(MySubscription->conninfo, true, true,
     782                 :             :                        must_use_password,
     783                 :             :                        app_name.data, &err);
     784         [ -  + ]:          14 :     if (LogRepWorkerWalRcvConn == NULL)
     785         [ #  # ]:           0 :         ereport(ERROR,
     786                 :             :                 errcode(ERRCODE_CONNECTION_FAILURE),
     787                 :             :                 errmsg("sequencesync worker for subscription \"%s\" could not connect to the publisher: %s",
     788                 :             :                        MySubscription->name, err));
     789                 :             : 
     790                 :          14 :     pfree(app_name.data);
     791                 :             : 
     792                 :          14 :     copy_sequences(LogRepWorkerWalRcvConn);
     793                 :             : }
     794                 :             : 
     795                 :             : /*
     796                 :             :  * Execute the initial sync with error handling. Disable the subscription,
     797                 :             :  * if required.
     798                 :             :  *
     799                 :             :  * Note that we don't handle FATAL errors which are probably because of system
     800                 :             :  * resource error and are not repeatable.
     801                 :             :  */
     802                 :             : static void
     803                 :          14 : start_sequence_sync(void)
     804                 :             : {
     805                 :             :     Assert(am_sequencesync_worker());
     806                 :             : 
     807         [ +  + ]:          14 :     PG_TRY();
     808                 :             :     {
     809                 :             :         /* Call initial sync. */
     810                 :          14 :         LogicalRepSyncSequences();
     811                 :             :     }
     812                 :           7 :     PG_CATCH();
     813                 :             :     {
     814         [ -  + ]:           7 :         if (MySubscription->disableonerr)
     815                 :           0 :             DisableSubscriptionAndExit();
     816                 :             :         else
     817                 :             :         {
     818                 :             :             /*
     819                 :             :              * Report the worker failed during sequence synchronization. Abort
     820                 :             :              * the current transaction so that the stats message is sent in an
     821                 :             :              * idle state.
     822                 :             :              */
     823                 :           7 :             AbortOutOfAnyTransaction();
     824                 :           7 :             pgstat_report_subscription_error(MySubscription->oid);
     825                 :             : 
     826                 :           7 :             PG_RE_THROW();
     827                 :             :         }
     828                 :             :     }
     829         [ -  + ]:           7 :     PG_END_TRY();
     830                 :           7 : }
     831                 :             : 
     832                 :             : /* Logical Replication sequencesync worker entry point */
     833                 :             : void
     834                 :          14 : SequenceSyncWorkerMain(Datum main_arg)
     835                 :             : {
     836                 :          14 :     int         worker_slot = DatumGetInt32(main_arg);
     837                 :             : 
     838                 :          14 :     SetupApplyOrSyncWorker(worker_slot);
     839                 :             : 
     840                 :          14 :     start_sequence_sync();
     841                 :             : 
     842                 :           7 :     FinishSyncWorker();
     843                 :             : }
        

Generated by: LCOV version 2.0-1