LCOV - code coverage report
Current view: top level - src/backend/commands - repack_worker.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 94.3 % 174 164
Test Date: 2026-11-25 11:16:04 Functions: 100.0 % 9 9
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 62.9 % 62 39

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * repack_worker.c
       4                 :             :  *    Implementation of the background worker for ad-hoc logical decoding
       5                 :             :  *    during REPACK (CONCURRENTLY).
       6                 :             :  *
       7                 :             :  *
       8                 :             :  * Copyright (c) 2026, PostgreSQL Global Development Group
       9                 :             :  *
      10                 :             :  *
      11                 :             :  * IDENTIFICATION
      12                 :             :  *    src/backend/commands/repack_worker.c
      13                 :             :  *
      14                 :             :  *-------------------------------------------------------------------------
      15                 :             :  */
      16                 :             : #include "postgres.h"
      17                 :             : 
      18                 :             : #include "access/table.h"
      19                 :             : #include "access/xlog_internal.h"
      20                 :             : #include "access/xlogutils.h"
      21                 :             : #include "access/xlogwait.h"
      22                 :             : #include "commands/progress.h"
      23                 :             : #include "commands/repack.h"
      24                 :             : #include "commands/repack_internal.h"
      25                 :             : #include "libpq/libpq.h"
      26                 :             : #include "libpq/pqmq.h"
      27                 :             : #include "replication/snapbuild.h"
      28                 :             : #include "storage/ipc.h"
      29                 :             : #include "storage/proc.h"
      30                 :             : #include "tcop/tcopprot.h"
      31                 :             : #include "utils/guc.h"
      32                 :             : #include "utils/memutils.h"
      33                 :             : 
      34                 :             : #define PGREPACK_PLUGIN   "pgrepack"
      35                 :             : 
      36                 :             : static void RepackWorkerShutdown(int code, Datum arg);
      37                 :             : static void set_repack_worker_setup_phase(DecodingWorkerShared *shared,
      38                 :             :                                           int setup_phase);
      39                 :             : static LogicalDecodingContext *repack_setup_logical_decoding(Oid relid,
      40                 :             :                                                              DecodingWorkerShared *shared);
      41                 :             : static void repack_cleanup_logical_decoding(LogicalDecodingContext *ctx);
      42                 :             : static void export_initial_snapshot(Snapshot snapshot,
      43                 :             :                                     DecodingWorkerShared *shared);
      44                 :             : static bool decode_concurrent_changes(LogicalDecodingContext *ctx,
      45                 :             :                                       DecodingWorkerShared *shared);
      46                 :             : 
      47                 :             : /* Is this process a REPACK worker? */
      48                 :             : static bool am_repack_worker = false;
      49                 :             : 
      50                 :             : /* The WAL segment being decoded. */
      51                 :             : static XLogSegNo repack_current_segment = 0;
      52                 :             : 
      53                 :             : /*
      54                 :             :  * Keep track of the table we're processing, to skip logical decoding of data
      55                 :             :  * from other relations.
      56                 :             :  */
      57                 :             : static RelFileLocator repacked_rel_locator = {.relNumber = InvalidOid};
      58                 :             : static RelFileLocator repacked_rel_toast_locator = {.relNumber = InvalidOid};
      59                 :             : 
      60                 :             : 
      61                 :             : /* REPACK decoding worker entry point */
      62                 :             : void
      63                 :          13 : RepackWorkerMain(Datum main_arg)
      64                 :             : {
      65                 :             :     dsm_segment *seg;
      66                 :             :     DecodingWorkerShared *shared;
      67                 :             :     shm_mq     *mq;
      68                 :             :     shm_mq_handle *mqh;
      69                 :             :     LogicalDecodingContext *decoding_ctx;
      70                 :             :     SharedFileSet *sfs;
      71                 :             :     Snapshot    snapshot;
      72                 :             :     char        buf[32];
      73                 :             : 
      74                 :          13 :     am_repack_worker = true;
      75                 :             : 
      76                 :          13 :     BackgroundWorkerUnblockSignals();
      77                 :             : 
      78                 :          13 :     seg = dsm_attach(DatumGetUInt32(main_arg));
      79         [ -  + ]:          13 :     if (seg == NULL)
      80         [ #  # ]:           0 :         ereport(ERROR,
      81                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
      82                 :             :                 errmsg("could not map dynamic shared memory segment"));
      83                 :             : 
      84                 :          13 :     shared = (DecodingWorkerShared *) dsm_segment_address(seg);
      85                 :             : 
      86                 :             :     /* Arrange to signal the steering process if we exit. */
      87                 :          13 :     before_shmem_exit(RepackWorkerShutdown, PointerGetDatum(seg));
      88                 :             : 
      89                 :             :     /*
      90                 :             :      * Join locking group - see the comments around the call of
      91                 :             :      * start_repack_decoding_worker().
      92                 :             :      */
      93         [ -  + ]:          13 :     if (!BecomeLockGroupMember(GetPGProcByNumber(shared->backend_proc_number),
      94                 :             :                                shared->backend_pid))
      95                 :           0 :         return;                 /* The leader is not running anymore. */
      96                 :             : 
      97                 :             :     /*
      98                 :             :      * Setup a queue to send error messages to the backend that launched this
      99                 :             :      * worker.
     100                 :             :      */
     101                 :          13 :     mq = (shm_mq *) (char *) BUFFERALIGN(shared->error_queue);
     102                 :          13 :     shm_mq_set_sender(mq, MyProc);
     103                 :          13 :     mqh = shm_mq_attach(mq, seg, NULL);
     104                 :          13 :     pq_redirect_to_shm_mq(seg, mqh);
     105                 :          13 :     pq_set_parallel_leader(shared->backend_pid,
     106                 :             :                            shared->backend_proc_number);
     107                 :             : 
     108                 :             :     /*
     109                 :             :      * Connect to the database, skipping the connection authorization checks
     110                 :             :      * as parallel workers do.  Note that we run as the owner of the table
     111                 :             :      * being repacked, who need not be able to log in or connect; the leader
     112                 :             :      * checked the invoking user's privileges before starting us.
     113                 :             :      */
     114                 :          13 :     BackgroundWorkerInitializeConnectionByOid(shared->dbid, shared->roleid,
     115                 :             :                                               BGWORKER_BYPASS_ALLOWCONN |
     116                 :             :                                               BGWORKER_BYPASS_ROLELOGINCHECK);
     117                 :             : 
     118                 :             :     /* Adopt the steering backend's relevant settings. */
     119                 :          13 :     snprintf(buf, sizeof(buf), "%d", shared->lock_timeout);
     120                 :          13 :     SetConfigOption("lock_timeout", buf, PGC_SUSET, PGC_S_OVERRIDE);
     121                 :          13 :     snprintf(buf, sizeof(buf), "%d", shared->transaction_timeout);
     122                 :          13 :     SetConfigOption("transaction_timeout", buf, PGC_SUSET, PGC_S_OVERRIDE);
     123                 :          13 :     snprintf(buf, sizeof(buf), "%d", shared->temp_file_limit);
     124                 :          13 :     SetConfigOption("temp_file_limit", buf, PGC_SUSET, PGC_S_OVERRIDE);
     125                 :             : 
     126                 :             :     /*
     127                 :             :      * Transaction is needed to open relation, and it also provides us with a
     128                 :             :      * resource owner.
     129                 :             :      */
     130                 :          13 :     StartTransactionCommand();
     131                 :             : 
     132                 :          13 :     shared = (DecodingWorkerShared *) dsm_segment_address(seg);
     133                 :             : 
     134                 :             :     /*
     135                 :             :      * Not sure the spinlock is needed here - the backend should not change
     136                 :             :      * anything in the shared memory until we have serialized the snapshot.
     137                 :             :      */
     138                 :          13 :     SpinLockAcquire(&shared->mutex);
     139                 :             :     Assert(!XLogRecPtrIsValid(shared->lsn_upto));
     140                 :          13 :     sfs = &shared->sfs;
     141                 :          13 :     SpinLockRelease(&shared->mutex);
     142                 :             : 
     143                 :          13 :     SharedFileSetAttach(sfs, seg);
     144                 :             : 
     145                 :             :     /*
     146                 :             :      * Prepare to capture the concurrent data changes ourselves.
     147                 :             :      */
     148                 :          13 :     decoding_ctx = repack_setup_logical_decoding(shared->relid, shared);
     149                 :             : 
     150                 :             :     /* Announce that we're ready. */
     151                 :          13 :     SpinLockAcquire(&shared->mutex);
     152                 :          13 :     shared->initialized = true;
     153                 :          13 :     SpinLockRelease(&shared->mutex);
     154                 :          13 :     ConditionVariableSignal(&shared->cv);
     155                 :             : 
     156                 :             :     /* There doesn't seem to a nice API to set these */
     157                 :          13 :     XactIsoLevel = XACT_REPEATABLE_READ;
     158                 :          13 :     XactReadOnly = true;
     159                 :             : 
     160                 :             :     /* Build the initial snapshot and export it. */
     161                 :          13 :     snapshot = SnapBuildInitialSnapshot(decoding_ctx->snapshot_builder);
     162                 :          13 :     export_initial_snapshot(snapshot, shared);
     163                 :             : 
     164                 :             :     /*
     165                 :             :      * Only historic snapshots should be used now. Do not let us restrict the
     166                 :             :      * progress of xmin horizon.
     167                 :             :      */
     168                 :          13 :     InvalidateCatalogSnapshot();
     169                 :             : 
     170                 :             :     for (;;)
     171                 :          13 :     {
     172                 :          26 :         bool        stop = decode_concurrent_changes(decoding_ctx, shared);
     173                 :             : 
     174         [ +  + ]:          26 :         if (stop)
     175                 :          13 :             break;
     176                 :             :     }
     177                 :             : 
     178                 :             :     /* Clean up and report termination to our steering process */
     179                 :          13 :     repack_cleanup_logical_decoding(decoding_ctx);
     180                 :          13 :     CommitTransactionCommand();
     181                 :          13 :     pq_putmessage(PqRepackMsg_Terminate, NULL, 0);
     182                 :             : }
     183                 :             : 
     184                 :             : /*
     185                 :             :  * Make sure the repack steering process tries to read from our error queue one
     186                 :             :  * more time.  This guards against the case where we exit uncleanly without
     187                 :             :  * sending an ErrorResponse to the leader, for example because some code calls
     188                 :             :  * proc_exit directly.
     189                 :             :  */
     190                 :             : static void
     191                 :          13 : RepackWorkerShutdown(int code, Datum arg)
     192                 :             : {
     193                 :             :     dsm_segment *seg;
     194                 :             :     DecodingWorkerShared *shared;
     195                 :             :     pid_t       pid;
     196                 :             :     ProcNumber  procno;
     197                 :             : 
     198                 :          13 :     seg = (dsm_segment *) DatumGetPointer(arg);
     199                 :          13 :     shared = (DecodingWorkerShared *) dsm_segment_address(seg);
     200                 :          13 :     pid = shared->backend_pid;
     201                 :          13 :     procno = shared->backend_proc_number;
     202                 :             : 
     203                 :             :     /*
     204                 :             :      * Detach from the shared memory segment before we signal the backend.
     205                 :             :      * Detaching also detaches the error message queue, and the backend learns
     206                 :             :      * that we are gone by reading that queue when it handles our signal. If
     207                 :             :      * we signaled first, the backend could read the queue while it still
     208                 :             :      * looks attached, and nothing would make it read again.
     209                 :             :      */
     210                 :          13 :     dsm_detach(seg);
     211                 :             : 
     212                 :          13 :     SendProcSignal(pid, PROCSIG_REPACK_MESSAGE, procno);
     213                 :          13 : }
     214                 :             : 
     215                 :             : bool
     216                 :        2102 : AmRepackWorker(void)
     217                 :             : {
     218                 :        2102 :     return am_repack_worker;
     219                 :             : }
     220                 :             : 
     221                 :             : /*
     222                 :             :  * Tell the backend running REPACK which progress phase to report while we
     223                 :             :  * initialize the decoding.
     224                 :             :  */
     225                 :             : static void
     226                 :          26 : set_repack_worker_setup_phase(DecodingWorkerShared *shared, int setup_phase)
     227                 :             : {
     228                 :          26 :     SpinLockAcquire(&shared->mutex);
     229                 :          26 :     shared->setup_phase = setup_phase;
     230                 :          26 :     SpinLockRelease(&shared->mutex);
     231                 :          26 :     ConditionVariableSignal(&shared->cv);
     232                 :          26 : }
     233                 :             : 
     234                 :             : /*
     235                 :             :  * This function is much like pg_create_logical_replication_slot() except that
     236                 :             :  * the new slot is neither released (if anyone else could read changes from
     237                 :             :  * our slot, we could miss changes other backends do while we copy the
     238                 :             :  * existing data into temporary table), nor persisted (it's easier to handle
     239                 :             :  * crash by restarting all the work from scratch).
     240                 :             :  */
     241                 :             : static LogicalDecodingContext *
     242                 :          13 : repack_setup_logical_decoding(Oid relid, DecodingWorkerShared *shared)
     243                 :             : {
     244                 :             :     Relation    rel;
     245                 :             :     Oid         toastrelid;
     246                 :             :     LogicalDecodingContext *ctx;
     247                 :             :     char        slotname[NAMEDATALEN];
     248                 :             :     RepackDecodingState *dstate;
     249                 :             :     MemoryContext oldcxt;
     250                 :             : 
     251                 :             :     /*
     252                 :             :      * REPACK CONCURRENTLY is not allowed in a transaction block, so this
     253                 :             :      * should never fire.
     254                 :             :      */
     255                 :             :     Assert(!TransactionIdIsValid(GetTopTransactionIdIfAny()));
     256                 :             : 
     257                 :             :     /* Make sure we can use logical decoding */
     258                 :          13 :     CheckLogicalDecodingRequirements(true);
     259                 :             : 
     260                 :             :     /*
     261                 :             :      * Create the replication slot we'll use, and enable logical decoding in
     262                 :             :      * case it isn't already on.
     263                 :             :      *
     264                 :             :      * Make the slot RS_TEMPORARY so that it's removed on ERROR.  A backend
     265                 :             :      * cannot execute multiple REPACK commands at a time, so the PID is enough
     266                 :             :      * to make the slot name unique.
     267                 :             :      */
     268                 :          13 :     snprintf(slotname, NAMEDATALEN, "pg_repack_%d", MyProcPid);
     269                 :          13 :     ReplicationSlotCreate(slotname, true, RS_TEMPORARY, false, true,
     270                 :             :                           false, false);
     271                 :          13 :     set_repack_worker_setup_phase(shared,
     272                 :             :                                   PROGRESS_REPACK_PHASE_ENABLE_LOGICAL_DECODING);
     273                 :          13 :     EnsureLogicalDecodingEnabled();
     274                 :             : 
     275                 :             :     /*
     276                 :             :      * Set up repacked_rel_locator and repacked_rel_toast_locator, which we
     277                 :             :      * use to skip decoding of unrelated relations.  The steering backend
     278                 :             :      * already holds ShareUpdateExclusiveLock on both these tables, so we
     279                 :             :      * don't need any locks here, other than to avoid relation_open()'s
     280                 :             :      * assertion that we hold one.
     281                 :             :      */
     282                 :          13 :     rel = table_open(relid, AccessShareLock);
     283                 :          13 :     repacked_rel_locator = rel->rd_locator;
     284                 :          13 :     toastrelid = rel->rd_rel->reltoastrelid;
     285         [ +  + ]:          13 :     if (OidIsValid(toastrelid))
     286                 :             :     {
     287                 :             :         Relation    toastrel;
     288                 :             : 
     289                 :             :         /* Avoid logical decoding of other TOAST relations. */
     290                 :           8 :         toastrel = table_open(toastrelid, AccessShareLock);
     291                 :           8 :         repacked_rel_toast_locator = toastrel->rd_locator;
     292                 :           8 :         table_close(toastrel, AccessShareLock);
     293                 :             :     }
     294                 :          13 :     table_close(rel, AccessShareLock);
     295                 :             : 
     296                 :          13 :     set_repack_worker_setup_phase(shared,
     297                 :             :                                   PROGRESS_REPACK_PHASE_INIT_LOGICAL_DECODING);
     298                 :             : 
     299                 :             :     /*
     300                 :             :      * Set up our logical decoding context.  We initially use the blocking
     301                 :             :      * read_local_xlog_page until we find the start point, and switch to the
     302                 :             :      * non-blocking interface afterwards.
     303                 :             :      */
     304                 :          13 :     ctx = CreateInitDecodingContext(PGREPACK_PLUGIN,
     305                 :             :                                     NIL,
     306                 :             :                                     true,
     307                 :             :                                     true,
     308                 :             :                                     InvalidXLogRecPtr,
     309                 :          13 :                                     XL_ROUTINE(.page_read = read_local_xlog_page,
     310                 :             :                                                .segment_open = wal_segment_open,
     311                 :             :                                                .segment_close = wal_segment_close),
     312                 :             :                                     NULL, NULL, NULL);
     313                 :             : 
     314                 :             :     /* Complete setup of output_writer_private */
     315                 :          13 :     dstate = (RepackDecodingState *) ctx->output_writer_private;
     316                 :          13 :     dstate->relid = relid;
     317                 :          13 :     dstate->worker_cxt = CurrentMemoryContext;
     318                 :          13 :     dstate->worker_resowner = CurrentResourceOwner;
     319                 :             : 
     320                 :             :     /* We don't have control on fast_forward, but verify it's sane */
     321                 :             :     Assert(!ctx->fast_forward);
     322                 :             : 
     323                 :             :     /* Find our decoding starting point. */
     324                 :          13 :     DecodingContextFindStartpoint(ctx);
     325                 :             : 
     326                 :             :     /* From this point on, we need non-blocking WAL reads */
     327                 :          13 :     ctx->reader->routine.page_read = read_local_xlog_page_no_wait;
     328                 :             : 
     329                 :             :     /*
     330                 :             :      * Initialize repack_current_segment so that we can notice WAL segment
     331                 :             :      * boundaries.
     332                 :             :      */
     333                 :          13 :     XLByteToSeg(ctx->reader->EndRecPtr, repack_current_segment,
     334                 :             :                 wal_segment_size);
     335                 :             : 
     336                 :             :     /*
     337                 :             :      * Set up our reader private state to let the page-read callback notify
     338                 :             :      * when end-of-WAL has been reached.  This lives in the same context as
     339                 :             :      * the logical decoding itself.
     340                 :             :      */
     341                 :          13 :     oldcxt = MemoryContextSwitchTo(ctx->context);
     342                 :          13 :     ctx->reader->private_data = palloc0_object(ReadLocalXLogPageNoWaitPrivate);
     343                 :          13 :     MemoryContextSwitchTo(oldcxt);
     344                 :             : 
     345                 :          13 :     return ctx;
     346                 :             : }
     347                 :             : 
     348                 :             : static void
     349                 :          13 : repack_cleanup_logical_decoding(LogicalDecodingContext *ctx)
     350                 :             : {
     351                 :             :     RepackDecodingState *dstate;
     352                 :             : 
     353                 :          13 :     dstate = (RepackDecodingState *) ctx->output_writer_private;
     354         [ +  + ]:          13 :     if (dstate->slot)
     355                 :           4 :         ExecDropSingleTupleTableSlot(dstate->slot);
     356                 :             : 
     357                 :          13 :     FreeDecodingContext(ctx);
     358                 :          13 :     ReplicationSlotDropAcquired(true);
     359                 :          13 : }
     360                 :             : 
     361                 :             : /*
     362                 :             :  * Make snapshot available to the backend that launched the decoding worker.
     363                 :             :  */
     364                 :             : static void
     365                 :          13 : export_initial_snapshot(Snapshot snapshot, DecodingWorkerShared *shared)
     366                 :             : {
     367                 :             :     char        fname[MAXPGPATH];
     368                 :             :     BufFile    *file;
     369                 :             :     Size        snap_size;
     370                 :             :     char       *snap_space;
     371                 :             : 
     372                 :          13 :     snap_size = EstimateSnapshotSpace(snapshot);
     373                 :          13 :     snap_space = (char *) palloc(snap_size);
     374                 :          13 :     SerializeSnapshot(snapshot, snap_space);
     375                 :             : 
     376                 :          13 :     DecodingWorkerFileName(fname, shared->relid, shared->last_exported + 1);
     377                 :          13 :     file = BufFileCreateFileSet(&shared->sfs.fs, fname);
     378                 :             :     /* To make restoration easier, write the snapshot size first. */
     379                 :          13 :     BufFileWrite(file, &snap_size, sizeof(snap_size));
     380                 :          13 :     BufFileWrite(file, snap_space, snap_size);
     381                 :          13 :     BufFileClose(file);
     382                 :          13 :     pfree(snap_space);
     383                 :             : 
     384                 :             :     /* Increase the counter to tell the backend that the file is available. */
     385                 :          13 :     SpinLockAcquire(&shared->mutex);
     386                 :          13 :     shared->last_exported++;
     387                 :          13 :     SpinLockRelease(&shared->mutex);
     388                 :          13 :     ConditionVariableSignal(&shared->cv);
     389                 :          13 : }
     390                 :             : 
     391                 :             : /*
     392                 :             :  * Decode logical changes from the WAL sequence and store them to a file.
     393                 :             :  *
     394                 :             :  * If true is returned, there is no more work for the worker.
     395                 :             :  */
     396                 :             : static bool
     397                 :          26 : decode_concurrent_changes(LogicalDecodingContext *ctx,
     398                 :             :                           DecodingWorkerShared *shared)
     399                 :             : {
     400                 :             :     RepackDecodingState *dstate;
     401                 :             :     XLogRecPtr  lsn_upto;
     402                 :             :     bool        done;
     403                 :             :     char        fname[MAXPGPATH];
     404                 :             : 
     405                 :          26 :     dstate = (RepackDecodingState *) ctx->output_writer_private;
     406                 :             : 
     407                 :             :     /* Open the output file. */
     408                 :          26 :     DecodingWorkerFileName(fname, shared->relid, shared->last_exported + 1);
     409                 :          26 :     dstate->file = BufFileCreateFileSet(&shared->sfs.fs, fname);
     410                 :             : 
     411                 :          26 :     SpinLockAcquire(&shared->mutex);
     412                 :          26 :     lsn_upto = shared->lsn_upto;
     413                 :          26 :     done = shared->done;
     414                 :          26 :     SpinLockRelease(&shared->mutex);
     415                 :             : 
     416                 :             :     while (true)
     417                 :       17286 :     {
     418                 :             :         XLogRecord *record;
     419                 :             :         XLogSegNo   segno_new;
     420                 :       17312 :         char       *errm = NULL;
     421                 :             :         XLogRecPtr  end_lsn;
     422                 :             : 
     423         [ -  + ]:       17312 :         CHECK_FOR_INTERRUPTS();
     424                 :             : 
     425                 :       17312 :         record = XLogReadRecord(ctx->reader, &errm);
     426         [ +  + ]:       17312 :         if (record)
     427                 :             :         {
     428                 :        2985 :             LogicalDecodingProcessRecord(ctx, ctx->reader);
     429                 :             : 
     430                 :             :             /*
     431                 :             :              * We want to allow WAL to be recycled while REPACK is running.
     432                 :             :              *
     433                 :             :              * In normal usage of a replication slot, we need to be very
     434                 :             :              * careful not to advance the LSN until it's been confirmed as
     435                 :             :              * received by the remote.  In REPACK's case, this is not needed:
     436                 :             :              * REPACK will never try to replay the same WAL after a crash, and
     437                 :             :              * if there _is_ a crash, the whole REPACK has to be started from
     438                 :             :              * scratch anyway.
     439                 :             :              *
     440                 :             :              * So here we disregard the careful LSN tracking and just move the
     441                 :             :              * LSN locations forward to what we've processed.  Note that it
     442                 :             :              * would be bogus to move the xmin forward, though, so we don't
     443                 :             :              * touch that.
     444                 :             :              *
     445                 :             :              * This can be done on whatever schedule is convenient, but in
     446                 :             :              * order not to cause unnecessary load, we only do it as we cross
     447                 :             :              * each WAL segment boundary.
     448                 :             :              */
     449                 :        2985 :             end_lsn = ctx->reader->EndRecPtr;
     450                 :        2985 :             XLByteToSeg(end_lsn, segno_new, wal_segment_size);
     451         [ -  + ]:        2985 :             if (segno_new != repack_current_segment)
     452                 :             :             {
     453                 :           0 :                 LogicalIncreaseRestartDecodingForSlot(end_lsn, end_lsn);
     454                 :           0 :                 LogicalConfirmReceivedLocation(end_lsn);
     455         [ #  # ]:           0 :                 elog(DEBUG1, "REPACK: confirmed receive location %X/%08X",
     456                 :             :                      LSN_FORMAT_ARGS(end_lsn));
     457                 :           0 :                 repack_current_segment = segno_new;
     458                 :             :             }
     459                 :             :         }
     460                 :             :         else
     461                 :             :         {
     462                 :             :             ReadLocalXLogPageNoWaitPrivate *priv;
     463                 :             : 
     464         [ -  + ]:       14327 :             if (errm)
     465         [ #  # ]:           0 :                 ereport(ERROR,
     466                 :             :                         errcode_for_file_access(),
     467                 :             :                         errmsg("could not read WAL from timeline %u at %X/%08X: %s",
     468                 :             :                                ctx->reader->currTLI,
     469                 :             :                                LSN_FORMAT_ARGS(ctx->reader->EndRecPtr),
     470                 :             :                                errm));
     471                 :             : 
     472                 :             :             /*
     473                 :             :              * In the decoding loop we do not want to get blocked when there
     474                 :             :              * is no more WAL available, otherwise the loop would become
     475                 :             :              * uninterruptible.
     476                 :             :              */
     477                 :       14327 :             priv = (ReadLocalXLogPageNoWaitPrivate *) ctx->reader->private_data;
     478         [ +  - ]:       14327 :             if (priv->end_of_wal)
     479                 :             :                 /* Do not miss the end of WAL condition next time. */
     480                 :       14327 :                 priv->end_of_wal = false;
     481                 :             :             else
     482         [ #  # ]:           0 :                 ereport(ERROR,
     483                 :             :                         errcode(ERRCODE_DATA_CORRUPTED),
     484                 :             :                         errmsg("could not read WAL record"));
     485                 :             :         }
     486                 :             : 
     487                 :             :         /*
     488                 :             :          * Whether we could read new record or not, keep checking if
     489                 :             :          * 'lsn_upto' was specified.
     490                 :             :          */
     491         [ +  + ]:       17312 :         if (!XLogRecPtrIsValid(lsn_upto))
     492                 :             :         {
     493                 :       16818 :             SpinLockAcquire(&shared->mutex);
     494                 :       16818 :             lsn_upto = shared->lsn_upto;
     495                 :             :             /* 'done' should be set at the same time as 'lsn_upto' */
     496                 :       16818 :             done = shared->done;
     497                 :       16818 :             SpinLockRelease(&shared->mutex);
     498                 :             :         }
     499         [ +  + ]:       17312 :         if (XLogRecPtrIsValid(lsn_upto) &&
     500         [ +  + ]:         518 :             ctx->reader->EndRecPtr >= lsn_upto)
     501                 :          26 :             break;
     502                 :             : 
     503         [ +  + ]:       17286 :         if (record == NULL)
     504                 :             :         {
     505                 :       14316 :             int         timeout = 0;
     506                 :             :             WaitLSNResult res;
     507                 :             : 
     508                 :             :             /*
     509                 :             :              * Before we retry reading, wait until new WAL is flushed.
     510                 :             :              *
     511                 :             :              * There is a race condition such that the backend executing
     512                 :             :              * REPACK determines 'lsn_upto', but before it sets the shared
     513                 :             :              * variable, we reach the end of WAL. In that case we'd need to
     514                 :             :              * wait until the next WAL flush (unrelated to REPACK). Although
     515                 :             :              * that should not be a problem in a busy system, it might be
     516                 :             :              * noticeable in other cases, including regression tests (which
     517                 :             :              * are not necessarily executed in parallel). Therefore it makes
     518                 :             :              * sense to use timeout.
     519                 :             :              *
     520                 :             :              * If lsn_upto is valid, WAL records having LSN lower than that
     521                 :             :              * should already have been flushed to disk.
     522                 :             :              */
     523         [ +  - ]:       14316 :             if (!XLogRecPtrIsValid(lsn_upto))
     524                 :       14316 :                 timeout = 100;
     525                 :       14316 :             res = WaitForLSN(WAIT_LSN_TYPE_PRIMARY_FLUSH,
     526                 :       14316 :                              ctx->reader->EndRecPtr + 1,
     527                 :             :                              timeout);
     528   [ +  +  -  + ]:       14316 :             if (res != WAIT_LSN_RESULT_SUCCESS &&
     529                 :             :                 res != WAIT_LSN_RESULT_TIMEOUT)
     530         [ #  # ]:           0 :                 ereport(ERROR,
     531                 :             :                         errcode(ERRCODE_INTERNAL_ERROR),
     532                 :             :                         errmsg("waiting for WAL failed"));
     533                 :             :         }
     534                 :             :     }
     535                 :             : 
     536                 :             :     /*
     537                 :             :      * Close the file so we can make it available to the backend.
     538                 :             :      */
     539                 :          26 :     BufFileClose(dstate->file);
     540                 :          26 :     dstate->file = NULL;
     541                 :          26 :     SpinLockAcquire(&shared->mutex);
     542                 :          26 :     shared->lsn_upto = InvalidXLogRecPtr;
     543                 :          26 :     shared->last_exported++;
     544                 :          26 :     SpinLockRelease(&shared->mutex);
     545                 :          26 :     ConditionVariableSignal(&shared->cv);
     546                 :             : 
     547                 :          26 :     return done;
     548                 :             : }
     549                 :             : 
     550                 :             : /*
     551                 :             :  * Does the WAL record contain a data change that this backend does not need
     552                 :             :  * to decode on behalf of REPACK (CONCURRENTLY)?
     553                 :             :  */
     554                 :             : bool
     555                 :     1413805 : change_useless_for_repack(XLogRecordBuffer *buf)
     556                 :             : {
     557                 :     1413805 :     XLogReaderState *r = buf->record;
     558                 :             :     RelFileLocator locator;
     559                 :             : 
     560                 :             :     /* TOAST locator should not be set unless the main is. */
     561                 :             :     Assert(!OidIsValid(repacked_rel_toast_locator.relNumber) ||
     562                 :             :            OidIsValid(repacked_rel_locator.relNumber));
     563                 :             : 
     564                 :             :     /*
     565                 :             :      * Backends not involved in REPACK (CONCURRENTLY) should not do the
     566                 :             :      * filtering.
     567                 :             :      */
     568         [ +  + ]:     1413805 :     if (!OidIsValid(repacked_rel_locator.relNumber))
     569                 :     1412934 :         return false;
     570                 :             : 
     571                 :             :     /*
     572                 :             :      * If the record does not contain the block 0, it's probably not INSERT /
     573                 :             :      * UPDATE / DELETE. In any case, we do not have enough information to
     574                 :             :      * filter the change out.
     575                 :             :      */
     576         [ -  + ]:         871 :     if (!XLogRecGetBlockTagExtended(r, 0, &locator, NULL, NULL, NULL))
     577                 :           0 :         return false;
     578                 :             : 
     579                 :             :     /*
     580                 :             :      * Decode the change if it belongs to the table we are repacking, or if it
     581                 :             :      * belongs to its TOAST relation.
     582                 :             :      */
     583   [ +  +  +  -  :         871 :     if (RelFileLocatorEquals(locator, repacked_rel_locator))
                   +  - ]
     584                 :          57 :         return false;
     585         [ +  + ]:         814 :     if (OidIsValid(repacked_rel_toast_locator.relNumber) &&
     586   [ +  +  +  -  :         692 :         RelFileLocatorEquals(locator, repacked_rel_toast_locator))
                   +  - ]
     587                 :         112 :         return false;
     588                 :             : 
     589                 :             :     /* Filter out changes of other tables. */
     590                 :         702 :     return true;
     591                 :             : }
        

Generated by: LCOV version 2.0-1