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 : 11956 : ProcessSequencesForSync(void)
98 : : {
99 : : LogicalRepWorker *sequencesync_worker;
100 : : int nsyncworkers;
101 : : bool has_pending_sequences;
102 : : bool started_tx;
103 : :
104 : 11956 : FetchRelationStates(NULL, &has_pending_sequences, &started_tx);
105 : :
106 [ + + ]: 11956 : if (started_tx)
107 : : {
108 : 185 : CommitTransactionCommand();
109 : 185 : pgstat_report_stat(true);
110 : : }
111 : :
112 [ + + ]: 11956 : if (!has_pending_sequences)
113 : 11922 : return;
114 : :
115 : 55 : LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
116 : :
117 : : /* Check if there is a sequencesync worker already running? */
118 : 55 : sequencesync_worker = logicalrep_worker_find(WORKERTYPE_SEQUENCESYNC,
119 : 55 : MyLogicalRepWorker->subid,
120 : : InvalidOid, true);
121 [ + + ]: 55 : if (sequencesync_worker)
122 : : {
123 : 21 : LWLockRelease(LogicalRepWorkerLock);
124 : 21 : return;
125 : : }
126 : :
127 : : /*
128 : : * Count running sync workers for this subscription, while we have the
129 : : * lock.
130 : : */
131 : 34 : nsyncworkers = logicalrep_sync_worker_count(MyLogicalRepWorker->subid);
132 : 34 : 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 : 34 : launch_sync_worker(WORKERTYPE_SEQUENCESYNC, nsyncworkers, InvalidOid,
139 : 34 : &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 : 30 : get_and_validate_seq_info(TupleTableSlot *slot, Relation *sequence_rel,
268 : : LogicalRepSequenceInfo **seqinfo, int *seqidx)
269 : : {
270 : : bool isnull;
271 : 30 : 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 : 30 : CopySeqResult result = COPYSEQ_SUCCESS;
281 : : HeapTuple tup;
282 : : Form_pg_sequence local_seq;
283 : : LogicalRepSequenceInfo *seqinfo_local;
284 : :
285 : 30 : *seqidx = DatumGetInt32(slot_getattr(slot, ++col, &isnull));
286 : : Assert(!isnull);
287 : :
288 : : /* Identify the corresponding local sequence for the given index. */
289 : 30 : *seqinfo = seqinfo_local =
290 : 30 : (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 : 30 : datum = slot_getattr(slot, ++col, &isnull);
299 [ + + ]: 30 : if (isnull)
300 : 1 : return COPYSEQ_SKIPPED;
301 : :
302 : 29 : 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 : 29 : datum = slot_getattr(slot, ++col, &isnull);
310 [ + + ]: 29 : if (isnull)
311 : : {
312 : : /*
313 : : * The sequence was dropped concurrently after it was identified in
314 : : * the catalog snapshot. Treat it as skipped (and, since it no longer
315 : : * exists on the publisher, ultimately missing).
316 : : */
317 [ - + ]: 1 : if (remote_has_select_priv)
318 : 0 : return COPYSEQ_SKIPPED;
319 : :
320 : : /*
321 : : * The publisher lacks the SELECT privilege required by
322 : : * pg_get_sequence_data(). Since has_sequence_privilege() returned
323 : : * false, not NULL, do not classify this sequence as missing on the
324 : : * publisher.
325 : : */
326 : 1 : seqinfo_local->found_on_pub = true;
327 : 1 : return COPYSEQ_PUBLISHER_INSUFFICIENT_PERM;
328 : : }
329 : :
330 : 28 : seqinfo_local->last_value = DatumGetInt64(datum);
331 : :
332 : 28 : seqinfo_local->is_called = DatumGetBool(slot_getattr(slot, ++col, &isnull));
333 : : Assert(!isnull);
334 : :
335 : 28 : seqinfo_local->page_lsn = DatumGetLSN(slot_getattr(slot, ++col, &isnull));
336 : : Assert(!isnull);
337 : :
338 : 28 : remote_typid = DatumGetObjectId(slot_getattr(slot, ++col, &isnull));
339 : : Assert(!isnull);
340 : :
341 : 28 : remote_start = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
342 : : Assert(!isnull);
343 : :
344 : 28 : remote_increment = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
345 : : Assert(!isnull);
346 : :
347 : 28 : remote_min = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
348 : : Assert(!isnull);
349 : :
350 : 28 : remote_max = DatumGetInt64(slot_getattr(slot, ++col, &isnull));
351 : : Assert(!isnull);
352 : :
353 : 28 : remote_cycle = DatumGetBool(slot_getattr(slot, ++col, &isnull));
354 : : Assert(!isnull);
355 : :
356 : : /* Sanity check */
357 : : Assert(col == REMOTE_SEQ_COL_COUNT);
358 : :
359 : 28 : seqinfo_local->found_on_pub = true;
360 : :
361 : 28 : *sequence_rel = try_table_open(seqinfo_local->localrelid, RowExclusiveLock);
362 : :
363 : : /* Sequence was concurrently dropped? */
364 [ - + ]: 28 : if (!*sequence_rel)
365 : 0 : return COPYSEQ_SKIPPED;
366 : :
367 : 28 : tup = SearchSysCache1(SEQRELID, ObjectIdGetDatum(seqinfo_local->localrelid));
368 : :
369 : : /* Sequence was concurrently dropped? */
370 [ - + ]: 28 : if (!HeapTupleIsValid(tup))
371 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u",
372 : : seqinfo_local->localrelid);
373 : :
374 : 28 : local_seq = (Form_pg_sequence) GETSTRUCT(tup);
375 : :
376 : : /* Sequence parameters for remote/local are the same? */
377 [ + - ]: 28 : if (local_seq->seqtypid != remote_typid ||
378 [ + + ]: 28 : local_seq->seqstart != remote_start ||
379 [ + + ]: 27 : local_seq->seqincrement != remote_increment ||
380 [ + - ]: 25 : local_seq->seqmin != remote_min ||
381 [ + - ]: 25 : local_seq->seqmax != remote_max ||
382 [ - + ]: 25 : local_seq->seqcycle != remote_cycle)
383 : 3 : result = COPYSEQ_MISMATCH;
384 : :
385 : : /* Sequence was concurrently renamed? */
386 [ + - ]: 28 : if (strcmp(seqinfo_local->nspname,
387 : 28 : get_namespace_name(RelationGetNamespace(*sequence_rel))) ||
388 [ - + ]: 28 : strcmp(seqinfo_local->seqname, RelationGetRelationName(*sequence_rel)))
389 : 0 : result = COPYSEQ_MISMATCH;
390 : :
391 : 28 : ReleaseSysCache(tup);
392 : 28 : return result;
393 : : }
394 : :
395 : : /*
396 : : * Apply remote sequence state to local sequence and mark it as
397 : : * synchronized (READY).
398 : : */
399 : : static CopySeqResult
400 : 25 : copy_sequence(LogicalRepSequenceInfo *seqinfo, Oid seqowner)
401 : : {
402 : : UserContext ucxt;
403 : : AclResult aclresult;
404 : 25 : bool run_as_owner = MySubscription->runasowner;
405 : 25 : Oid seqoid = seqinfo->localrelid;
406 : :
407 : : /*
408 : : * If the user did not opt to run as the owner of the subscription
409 : : * ('run_as_owner'), then copy the sequence as the owner of the sequence.
410 : : */
411 [ + - ]: 25 : if (!run_as_owner)
412 : 25 : SwitchToUntrustedUser(seqowner, &ucxt);
413 : :
414 : 25 : aclresult = pg_class_aclcheck(seqoid, GetUserId(), ACL_UPDATE);
415 : :
416 [ - + ]: 25 : if (aclresult != ACLCHECK_OK)
417 : : {
418 [ # # ]: 0 : if (!run_as_owner)
419 : 0 : RestoreUserContext(&ucxt);
420 : :
421 : 0 : return COPYSEQ_SUBSCRIBER_INSUFFICIENT_PERM;
422 : : }
423 : :
424 : : /*
425 : : * The log counter (log_cnt) tracks how many sequence values are still
426 : : * unused locally. It is only relevant to the local node and managed
427 : : * internally by nextval() when allocating new ranges. Since log_cnt does
428 : : * not affect the visible sequence state (like last_value or is_called)
429 : : * and is only used for local caching, it need not be copied to the
430 : : * subscriber during synchronization.
431 : : */
432 : 25 : SetSequence(seqoid, seqinfo->last_value, seqinfo->is_called);
433 : :
434 [ + - ]: 25 : if (!run_as_owner)
435 : 25 : RestoreUserContext(&ucxt);
436 : :
437 : : /*
438 : : * Record the remote sequence's LSN in pg_subscription_rel and mark the
439 : : * sequence as READY.
440 : : */
441 : 25 : UpdateSubscriptionRelState(MySubscription->oid, seqoid, SUBREL_STATE_READY,
442 : : seqinfo->page_lsn, false);
443 : :
444 : 25 : return COPYSEQ_SUCCESS;
445 : : }
446 : :
447 : : /*
448 : : * Copy existing data of sequences from the publisher.
449 : : */
450 : : static void
451 : 14 : copy_sequences(WalReceiverConn *conn)
452 : : {
453 : 14 : int cur_batch_base_index = 0;
454 : 14 : int n_seqinfos = list_length(seqinfos);
455 : 14 : List *mismatched_seqs_idx = NIL;
456 : 14 : List *missing_seqs_idx = NIL;
457 : 14 : List *sub_insuffperm_seqs_idx = NIL;
458 : 14 : List *pub_insuffperm_seqs_idx = NIL;
459 : : StringInfoData seqstr;
460 : : StringInfoData cmd;
461 : : MemoryContext oldctx;
462 : :
463 : : /*
464 : : * Sequence synchronization depends on publisher-side functionality
465 : : * introduced in PostgreSQL 19, so it cannot work against an older
466 : : * publisher.
467 : : */
468 [ - + ]: 14 : if (walrcv_server_version(conn) < 190000)
469 [ # # ]: 0 : ereport(ERROR,
470 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
471 : : errmsg("cannot synchronize sequences if the publisher is running a version earlier than PostgreSQL 19"));
472 : :
473 : 14 : initStringInfo(&seqstr);
474 : 14 : initStringInfo(&cmd);
475 : :
476 : : #define MAX_SEQUENCES_SYNC_PER_BATCH 100
477 : :
478 [ - + ]: 14 : elog(DEBUG1,
479 : : "logical replication sequence synchronization for subscription \"%s\" - total unsynchronized: %d",
480 : : MySubscription->name, n_seqinfos);
481 : :
482 [ + + ]: 28 : while (cur_batch_base_index < n_seqinfos)
483 : : {
484 : 14 : Oid seqRow[REMOTE_SEQ_COL_COUNT] = {INT8OID, BOOLOID, INT8OID,
485 : : BOOLOID, LSNOID, OIDOID, INT8OID, INT8OID, INT8OID, INT8OID, BOOLOID};
486 : 14 : int batch_size = 0;
487 : 14 : int batch_succeeded_count = 0;
488 : 14 : int batch_mismatched_count = 0;
489 : 14 : int batch_skipped_count = 0;
490 : 14 : int batch_sub_insuffperm_count = 0;
491 : 14 : int batch_pub_insuffperm_count = 0;
492 : : int batch_missing_count;
493 : :
494 : : WalRcvExecResult *res;
495 : : TupleTableSlot *slot;
496 : :
497 : 14 : StartTransactionCommand();
498 : 14 : maybe_reread_subscription();
499 : :
500 [ + + ]: 46 : for (int idx = cur_batch_base_index; idx < n_seqinfos; idx++)
501 : : {
502 : : char *nspname_literal;
503 : : char *seqname_literal;
504 : :
505 : : LogicalRepSequenceInfo *seqinfo =
506 : 32 : (LogicalRepSequenceInfo *) list_nth(seqinfos, idx);
507 : :
508 [ + + ]: 32 : if (seqstr.len > 0)
509 : 18 : appendStringInfoString(&seqstr, ", ");
510 : :
511 : 32 : nspname_literal = quote_literal_cstr(seqinfo->nspname);
512 : 32 : seqname_literal = quote_literal_cstr(seqinfo->seqname);
513 : :
514 : 32 : appendStringInfo(&seqstr, "(%s, %s, %d)",
515 : : nspname_literal, seqname_literal, idx);
516 : :
517 [ - + ]: 32 : if (++batch_size == MAX_SEQUENCES_SYNC_PER_BATCH)
518 : 0 : break;
519 : : }
520 : :
521 : : /*
522 : : * We deliberately avoid acquiring a local lock on the sequence before
523 : : * querying the publisher to prevent potential distributed deadlocks
524 : : * in bi-directional replication setups.
525 : : *
526 : : * Example scenario:
527 : : *
528 : : * - On each node, a background worker acquires a lock on a sequence
529 : : * as part of a sync operation.
530 : : *
531 : : * - Concurrently, a user transaction attempts to alter the same
532 : : * sequence, waiting on the background worker's lock.
533 : : *
534 : : * - Meanwhile, a query from the other node tries to access metadata
535 : : * that depends on the completion of the alter operation.
536 : : *
537 : : * - This creates a circular wait across nodes:
538 : : *
539 : : * Node-1: Query -> waits on Alter -> waits on Sync Worker
540 : : *
541 : : * Node-2: Query -> waits on Alter -> waits on Sync Worker
542 : : *
543 : : * Since each node only sees part of the wait graph, the deadlock may
544 : : * go undetected, leading to indefinite blocking.
545 : : *
546 : : * Note: Each entry in VALUES includes an index 'seqidx' that
547 : : * represents the sequence's position in the local 'seqinfos' list.
548 : : * This index is propagated to the query results and later used to
549 : : * directly map the fetched publisher sequence rows back to their
550 : : * corresponding local entries without relying on result order or name
551 : : * matching.
552 : : */
553 : 14 : appendStringInfo(&cmd,
554 : : "SELECT s.seqidx, has_sequence_privilege(c.oid, 'SELECT'),\n"
555 : : " ps.*, seq.seqtypid,\n"
556 : : " seq.seqstart, seq.seqincrement, seq.seqmin,\n"
557 : : " seq.seqmax, seq.seqcycle\n"
558 : : "FROM ( VALUES %s ) AS s (schname, seqname, seqidx)\n"
559 : : "JOIN pg_namespace n ON n.nspname = s.schname\n"
560 : : "JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = s.seqname\n"
561 : : "JOIN pg_sequence seq ON seq.seqrelid = c.oid\n"
562 : : "JOIN LATERAL pg_get_sequence_data(seq.seqrelid) AS ps ON true\n",
563 : : seqstr.data);
564 : :
565 : 14 : res = walrcv_exec(conn, cmd.data, lengthof(seqRow), seqRow);
566 [ - + ]: 14 : if (res->status != WALRCV_OK_TUPLES)
567 [ # # ]: 0 : ereport(ERROR,
568 : : errcode(ERRCODE_CONNECTION_FAILURE),
569 : : errmsg("could not fetch sequence information from the publisher: %s",
570 : : res->err));
571 : :
572 : 14 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
573 [ + + ]: 44 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
574 : : {
575 : : CopySeqResult sync_status;
576 : : LogicalRepSequenceInfo *seqinfo;
577 : 30 : Relation sequence_rel = NULL;
578 : : int seqidx;
579 : :
580 [ - + ]: 30 : CHECK_FOR_INTERRUPTS();
581 : :
582 [ - + ]: 30 : if (ConfigReloadPending)
583 : : {
584 : 0 : ConfigReloadPending = false;
585 : 0 : ProcessConfigFile(PGC_SIGHUP);
586 : : }
587 : :
588 : 30 : sync_status = get_and_validate_seq_info(slot, &sequence_rel,
589 : : &seqinfo, &seqidx);
590 [ + + ]: 30 : if (sync_status == COPYSEQ_SUCCESS)
591 : 25 : sync_status = copy_sequence(seqinfo,
592 : 25 : sequence_rel->rd_rel->relowner);
593 : :
594 [ + + - + : 30 : switch (sync_status)
+ - ]
595 : : {
596 : 25 : case COPYSEQ_SUCCESS:
597 [ - + ]: 25 : elog(DEBUG1,
598 : : "logical replication synchronization for subscription \"%s\", sequence \"%s.%s\" has finished",
599 : : MySubscription->name, seqinfo->nspname,
600 : : seqinfo->seqname);
601 : 25 : batch_succeeded_count++;
602 : 25 : break;
603 : 3 : case COPYSEQ_MISMATCH:
604 : :
605 : : /*
606 : : * Remember mismatched sequences in a long-lived memory
607 : : * context since these will be used after the transaction
608 : : * is committed.
609 : : */
610 : 3 : oldctx = MemoryContextSwitchTo(ApplyContext);
611 : 3 : mismatched_seqs_idx = lappend_int(mismatched_seqs_idx,
612 : : seqidx);
613 : 3 : MemoryContextSwitchTo(oldctx);
614 : 3 : batch_mismatched_count++;
615 : 3 : break;
616 : 0 : case COPYSEQ_SUBSCRIBER_INSUFFICIENT_PERM:
617 : :
618 : : /*
619 : : * Remember sequences with insufficient privileges in a
620 : : * long-lived memory context since these will be used
621 : : * after the transaction is committed.
622 : : */
623 : 0 : oldctx = MemoryContextSwitchTo(ApplyContext);
624 : 0 : sub_insuffperm_seqs_idx = lappend_int(sub_insuffperm_seqs_idx,
625 : : seqidx);
626 : 0 : MemoryContextSwitchTo(oldctx);
627 : 0 : batch_sub_insuffperm_count++;
628 : 0 : break;
629 : 1 : case COPYSEQ_PUBLISHER_INSUFFICIENT_PERM:
630 : :
631 : : /*
632 : : * Remember sequences for which the publisher lacks the
633 : : * privileges required by pg_get_sequence_data().
634 : : */
635 : 1 : oldctx = MemoryContextSwitchTo(ApplyContext);
636 : 1 : pub_insuffperm_seqs_idx = lappend_int(pub_insuffperm_seqs_idx,
637 : : seqidx);
638 : 1 : MemoryContextSwitchTo(oldctx);
639 : 1 : batch_pub_insuffperm_count++;
640 : 1 : break;
641 : 1 : case COPYSEQ_SKIPPED:
642 : :
643 : : /*
644 : : * Concurrent removal of a sequence on the subscriber is
645 : : * treated as success, since the only viable action is to
646 : : * skip the corresponding sequence data. Missing sequences
647 : : * on the publisher are treated as ERROR.
648 : : */
649 [ - + ]: 1 : if (seqinfo->found_on_pub)
650 : : {
651 [ # # ]: 0 : ereport(LOG,
652 : : errmsg("skip synchronization of sequence \"%s.%s\" because it has been dropped concurrently",
653 : : seqinfo->nspname,
654 : : seqinfo->seqname));
655 : 0 : batch_skipped_count++;
656 : : }
657 : 1 : break;
658 : : }
659 : :
660 [ + + ]: 30 : if (sequence_rel)
661 : 28 : table_close(sequence_rel, NoLock);
662 : : }
663 : :
664 : 14 : ExecDropSingleTupleTableSlot(slot);
665 : 14 : walrcv_clear_result(res);
666 : 14 : resetStringInfo(&seqstr);
667 : 14 : resetStringInfo(&cmd);
668 : :
669 : 14 : batch_missing_count = batch_size - (batch_succeeded_count +
670 : 14 : batch_mismatched_count +
671 : 14 : batch_sub_insuffperm_count +
672 : 14 : batch_pub_insuffperm_count +
673 : : batch_skipped_count);
674 : :
675 [ - + ]: 14 : elog(DEBUG1,
676 : : "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",
677 : : MySubscription->name,
678 : : (cur_batch_base_index / MAX_SEQUENCES_SYNC_PER_BATCH) + 1,
679 : : batch_size, batch_succeeded_count, batch_mismatched_count,
680 : : batch_sub_insuffperm_count, batch_pub_insuffperm_count, batch_missing_count, batch_skipped_count);
681 : :
682 : : /* Commit this batch, and prepare for next batch */
683 : 14 : CommitTransactionCommand();
684 : :
685 [ + + ]: 14 : if (batch_missing_count)
686 : : {
687 [ + + ]: 13 : for (int idx = cur_batch_base_index; idx < cur_batch_base_index + batch_size; idx++)
688 : : {
689 : : LogicalRepSequenceInfo *seqinfo =
690 : 10 : (LogicalRepSequenceInfo *) list_nth(seqinfos, idx);
691 : :
692 : : /* If the sequence was not found on publisher, record it */
693 [ + + ]: 10 : if (!seqinfo->found_on_pub)
694 : 3 : missing_seqs_idx = lappend_int(missing_seqs_idx, idx);
695 : : }
696 : : }
697 : :
698 : : /*
699 : : * cur_batch_base_index is not incremented sequentially because some
700 : : * sequences may be missing, and the number of fetched rows may not
701 : : * match the batch size.
702 : : */
703 : 14 : cur_batch_base_index += batch_size;
704 : : }
705 : :
706 : : /* Report mismatches, permission issues, or missing sequences */
707 : 14 : report_sequence_errors(mismatched_seqs_idx, sub_insuffperm_seqs_idx,
708 : : pub_insuffperm_seqs_idx, missing_seqs_idx);
709 : 7 : }
710 : :
711 : : /*
712 : : * Identifies sequences that require synchronization and initiates the
713 : : * synchronization process.
714 : : */
715 : : static void
716 : 15 : LogicalRepSyncSequences(void)
717 : : {
718 : : char *err;
719 : : bool must_use_password;
720 : : Relation rel;
721 : : HeapTuple tup;
722 : : ScanKeyData skey[2];
723 : : SysScanDesc scan;
724 : 15 : Oid subid = MyLogicalRepWorker->subid;
725 : : StringInfoData app_name;
726 : :
727 : 15 : StartTransactionCommand();
728 : 15 : maybe_reread_subscription();
729 : :
730 : 15 : rel = table_open(SubscriptionRelRelationId, AccessShareLock);
731 : :
732 : 15 : ScanKeyInit(&skey[0],
733 : : Anum_pg_subscription_rel_srsubid,
734 : : BTEqualStrategyNumber, F_OIDEQ,
735 : : ObjectIdGetDatum(subid));
736 : :
737 : 15 : ScanKeyInit(&skey[1],
738 : : Anum_pg_subscription_rel_srsubstate,
739 : : BTEqualStrategyNumber, F_CHAREQ,
740 : : CharGetDatum(SUBREL_STATE_INIT));
741 : :
742 : 15 : scan = systable_beginscan(rel, InvalidOid, false,
743 : : NULL, 2, skey);
744 [ + + ]: 49 : while (HeapTupleIsValid(tup = systable_getnext(scan)))
745 : : {
746 : : Form_pg_subscription_rel subrel;
747 : : LogicalRepSequenceInfo *seq;
748 : : Relation sequence_rel;
749 : : MemoryContext oldctx;
750 : :
751 [ - + ]: 34 : CHECK_FOR_INTERRUPTS();
752 : :
753 : 34 : subrel = (Form_pg_subscription_rel) GETSTRUCT(tup);
754 : :
755 : : /*
756 : : * Lock the sequence so its identity (namespace and name) cannot
757 : : * change under us via a concurrent DROP, RENAME or SET SCHEMA. The
758 : : * lock is released immediately rather than at the transaction end.
759 : : * The later synchronization does not depend on this captured identity
760 : : * remaining valid, as it re-opens the sequence and tolerates
761 : : * concurrent changes. Releasing early also avoids holding one lock
762 : : * per sequence, which could exhaust the lock table.
763 : : */
764 : 34 : sequence_rel = try_table_open(subrel->srrelid, AccessShareLock);
765 : :
766 : : /* Skip if sequence was dropped concurrently */
767 [ - + ]: 34 : if (!sequence_rel)
768 : 0 : continue;
769 : :
770 : : /* Skip if the relation is not a sequence */
771 [ + + ]: 34 : if (sequence_rel->rd_rel->relkind != RELKIND_SEQUENCE)
772 : : {
773 : 1 : table_close(sequence_rel, AccessShareLock);
774 : 1 : continue;
775 : : }
776 : :
777 : : /*
778 : : * Worker needs to process sequences across transaction boundary, so
779 : : * allocate them under long-lived context.
780 : : */
781 : 33 : oldctx = MemoryContextSwitchTo(ApplyContext);
782 : :
783 : 33 : seq = palloc0_object(LogicalRepSequenceInfo);
784 : 33 : seq->localrelid = subrel->srrelid;
785 : 33 : seq->nspname = get_namespace_name(RelationGetNamespace(sequence_rel));
786 : 33 : seq->seqname = pstrdup(RelationGetRelationName(sequence_rel));
787 : 33 : seqinfos = lappend(seqinfos, seq);
788 : :
789 : 33 : MemoryContextSwitchTo(oldctx);
790 : :
791 : 33 : table_close(sequence_rel, AccessShareLock);
792 : : }
793 : :
794 : : /* Cleanup */
795 : 15 : systable_endscan(scan);
796 : 15 : table_close(rel, AccessShareLock);
797 : :
798 : 15 : CommitTransactionCommand();
799 : :
800 : : /*
801 : : * Exit early if no catalog entries found, likely due to concurrent drops.
802 : : */
803 [ - + ]: 15 : if (!seqinfos)
804 : 0 : return;
805 : :
806 : : /* Is the use of a password mandatory? */
807 [ + - ]: 30 : must_use_password = MySubscription->passwordrequired &&
808 [ - + ]: 15 : !MySubscription->ownersuperuser;
809 : :
810 : 15 : initStringInfo(&app_name);
811 : 15 : appendStringInfo(&app_name, "pg_%u_sequence_sync_" UINT64_FORMAT,
812 : 15 : MySubscription->oid, GetSystemIdentifier());
813 : :
814 : : /*
815 : : * Establish the connection to the publisher for sequence synchronization.
816 : : */
817 : 14 : LogRepWorkerWalRcvConn =
818 : 15 : walrcv_connect(MySubscriptionConninfo, true, true,
819 : : must_use_password,
820 : : app_name.data, &err);
821 [ - + ]: 14 : if (LogRepWorkerWalRcvConn == NULL)
822 [ # # ]: 0 : ereport(ERROR,
823 : : errcode(ERRCODE_CONNECTION_FAILURE),
824 : : errmsg("sequencesync worker for subscription \"%s\" could not connect to the publisher: %s",
825 : : MySubscription->name, err));
826 : :
827 : 14 : pfree(app_name.data);
828 : :
829 : 14 : copy_sequences(LogRepWorkerWalRcvConn);
830 : : }
831 : :
832 : : /*
833 : : * Execute the initial sync with error handling. Disable the subscription,
834 : : * if required.
835 : : *
836 : : * Note that we don't handle FATAL errors which are probably because of system
837 : : * resource error and are not repeatable.
838 : : */
839 : : static void
840 : 15 : start_sequence_sync(void)
841 : : {
842 : : Assert(am_sequencesync_worker());
843 : :
844 [ + + ]: 15 : PG_TRY();
845 : : {
846 : : /* Call initial sync. */
847 : 15 : LogicalRepSyncSequences();
848 : : }
849 : 7 : PG_CATCH();
850 : : {
851 [ - + ]: 7 : if (MySubscription->disableonerr)
852 : 0 : DisableSubscriptionAndExit();
853 : : else
854 : : {
855 : : /*
856 : : * Report the worker failed during sequence synchronization. Abort
857 : : * the current transaction so that the stats message is sent in an
858 : : * idle state.
859 : : */
860 : 7 : AbortOutOfAnyTransaction();
861 : 7 : pgstat_report_subscription_error(MySubscription->oid);
862 : :
863 : 7 : PG_RE_THROW();
864 : : }
865 : : }
866 [ - + ]: 7 : PG_END_TRY();
867 : 7 : }
868 : :
869 : : /* Logical Replication sequencesync worker entry point */
870 : : void
871 : 15 : SequenceSyncWorkerMain(Datum main_arg)
872 : : {
873 : 15 : int worker_slot = DatumGetInt32(main_arg);
874 : :
875 : 15 : SetupApplyOrSyncWorker(worker_slot);
876 : :
877 : 15 : start_sequence_sync();
878 : :
879 : 7 : FinishSyncWorker();
880 : : }
|