Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * reorderbuffer.c
4 : : * PostgreSQL logical replay/reorder buffer management
5 : : *
6 : : *
7 : : * Copyright (c) 2012-2026, PostgreSQL Global Development Group
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/replication/logical/reorderbuffer.c
12 : : *
13 : : * NOTES
14 : : * This module gets handed individual pieces of transactions in the order
15 : : * they are written to the WAL and is responsible to reassemble them into
16 : : * toplevel transaction sized pieces. When a transaction is completely
17 : : * reassembled - signaled by reading the transaction commit record - it
18 : : * will then call the output plugin (cf. ReorderBufferCommit()) with the
19 : : * individual changes. The output plugins rely on snapshots built by
20 : : * snapbuild.c which hands them to us.
21 : : *
22 : : * Transactions and subtransactions/savepoints in postgres are not
23 : : * immediately linked to each other from outside the performing
24 : : * backend. Only at commit/abort (or special xact_assignment records) they
25 : : * are linked together. Which means that we will have to splice together a
26 : : * toplevel transaction from its subtransactions. To do that efficiently we
27 : : * build a binary heap indexed by the smallest current lsn of the individual
28 : : * subtransactions' changestreams. As the individual streams are inherently
29 : : * ordered by LSN - since that is where we build them from - the transaction
30 : : * can easily be reassembled by always using the subtransaction with the
31 : : * smallest current LSN from the heap.
32 : : *
33 : : * In order to cope with large transactions - which can be several times as
34 : : * big as the available memory - this module supports spooling the contents
35 : : * of large transactions to disk. When the transaction is replayed the
36 : : * contents of individual (sub-)transactions will be read from disk in
37 : : * chunks.
38 : : *
39 : : * This module also has to deal with reassembling toast records from the
40 : : * individual chunks stored in WAL. When a new (or initial) version of a
41 : : * tuple is stored in WAL it will always be preceded by the toast chunks
42 : : * emitted for the columns stored out of line. Within a single toplevel
43 : : * transaction there will be no other data carrying records between a row's
44 : : * toast chunks and the row data itself. See ReorderBufferToast* for
45 : : * details.
46 : : *
47 : : * ReorderBuffer uses two special memory context types - SlabContext for
48 : : * allocations of fixed-length structures (changes and transactions), and
49 : : * GenerationContext for the variable-length transaction data (allocated
50 : : * and freed in groups with similar lifespans).
51 : : *
52 : : * To limit the amount of memory used by decoded changes, we track memory
53 : : * used at the reorder buffer level (i.e. total amount of memory), and for
54 : : * each transaction. When the total amount of used memory exceeds the
55 : : * limit, the transaction consuming the most memory is then serialized to
56 : : * disk.
57 : : *
58 : : * Only decoded changes are evicted from memory (spilled to disk), not the
59 : : * transaction records. The number of toplevel transactions is limited,
60 : : * but a transaction with many subtransactions may still consume significant
61 : : * amounts of memory. However, the transaction records are fairly small and
62 : : * are not included in the memory limit.
63 : : *
64 : : * The current eviction algorithm is very simple - the transaction is
65 : : * picked merely by size, while it might be useful to also consider age
66 : : * (LSN) of the changes for example. With the new Generational memory
67 : : * allocator, evicting the oldest changes would make it more likely the
68 : : * memory gets actually freed.
69 : : *
70 : : * We use a max-heap with transaction size as the key to efficiently find
71 : : * the largest transaction. We update the max-heap whenever the memory
72 : : * counter is updated; however transactions with size 0 are not stored in
73 : : * the heap, because they have no changes to evict.
74 : : *
75 : : * We still rely on max_changes_in_memory when loading serialized changes
76 : : * back into memory. At that point we can't use the memory limit directly
77 : : * as we load the subxacts independently. One option to deal with this
78 : : * would be to count the subxacts, and allow each to allocate 1/N of the
79 : : * memory limit. That however does not seem very appealing, because with
80 : : * many subtransactions it may easily cause thrashing (short cycles of
81 : : * deserializing and applying very few changes). We probably should give
82 : : * a bit more memory to the oldest subtransactions, because it's likely
83 : : * they are the source for the next sequence of changes.
84 : : *
85 : : * -------------------------------------------------------------------------
86 : : */
87 : : #include "postgres.h"
88 : :
89 : : #include <unistd.h>
90 : : #include <sys/stat.h>
91 : :
92 : : #include "access/detoast.h"
93 : : #include "access/heapam.h"
94 : : #include "access/rewriteheap.h"
95 : : #include "access/transam.h"
96 : : #include "access/xact.h"
97 : : #include "access/xlog_internal.h"
98 : : #include "catalog/catalog.h"
99 : : #include "common/int.h"
100 : : #include "lib/binaryheap.h"
101 : : #include "miscadmin.h"
102 : : #include "pgstat.h"
103 : : #include "replication/logical.h"
104 : : #include "replication/reorderbuffer.h"
105 : : #include "replication/slot.h"
106 : : #include "replication/snapbuild.h" /* just for SnapBuildSnapDecRefcount */
107 : : #include "storage/bufmgr.h"
108 : : #include "storage/fd.h"
109 : : #include "storage/procarray.h"
110 : : #include "storage/sinval.h"
111 : : #include "utils/builtins.h"
112 : : #include "utils/inval.h"
113 : : #include "utils/memutils.h"
114 : : #include "utils/rel.h"
115 : : #include "utils/relfilenumbermap.h"
116 : : #include "utils/wait_event.h"
117 : :
118 : : /*
119 : : * Each transaction has an 8MB limit for invalidation messages distributed from
120 : : * other transactions. This limit is set considering scenarios with many
121 : : * concurrent logical decoding operations. When the distributed invalidation
122 : : * messages reach this threshold, the transaction is marked as
123 : : * RBTXN_DISTR_INVAL_OVERFLOWED to invalidate the complete cache as we have lost
124 : : * some inval messages and hence don't know what needs to be invalidated.
125 : : */
126 : : #define MAX_DISTR_INVAL_MSG_PER_TXN \
127 : : ((8 * 1024 * 1024) / sizeof(SharedInvalidationMessage))
128 : :
129 : : /* entry for a hash table we use to map from xid to our transaction state */
130 : : typedef struct ReorderBufferTXNByIdEnt
131 : : {
132 : : TransactionId xid;
133 : : ReorderBufferTXN *txn;
134 : : } ReorderBufferTXNByIdEnt;
135 : :
136 : : /* data structures for (relfilelocator, ctid) => (cmin, cmax) mapping */
137 : : typedef struct ReorderBufferTupleCidKey
138 : : {
139 : : RelFileLocator rlocator;
140 : : ItemPointerData tid;
141 : : } ReorderBufferTupleCidKey;
142 : :
143 : : typedef struct ReorderBufferTupleCidEnt
144 : : {
145 : : ReorderBufferTupleCidKey key;
146 : : CommandId cmin;
147 : : CommandId cmax;
148 : : CommandId combocid; /* just for debugging */
149 : : } ReorderBufferTupleCidEnt;
150 : :
151 : : /* Virtual file descriptor with file offset tracking */
152 : : typedef struct TXNEntryFile
153 : : {
154 : : File vfd; /* -1 when the file is closed */
155 : : off_t curOffset; /* offset for next write or read. Reset to 0
156 : : * when vfd is opened. */
157 : : } TXNEntryFile;
158 : :
159 : : /* k-way in-order change iteration support structures */
160 : : typedef struct ReorderBufferIterTXNEntry
161 : : {
162 : : XLogRecPtr lsn;
163 : : ReorderBufferChange *change;
164 : : ReorderBufferTXN *txn;
165 : : TXNEntryFile file;
166 : : XLogSegNo segno;
167 : : } ReorderBufferIterTXNEntry;
168 : :
169 : : typedef struct ReorderBufferIterTXNState
170 : : {
171 : : binaryheap *heap;
172 : : Size nr_txns;
173 : : dlist_head old_change;
174 : : pg_attribute_counted_by(nr_txns) ReorderBufferIterTXNEntry entries[FLEXIBLE_ARRAY_MEMBER];
175 : : } ReorderBufferIterTXNState;
176 : :
177 : : /* toast datastructures */
178 : : typedef struct ReorderBufferToastEnt
179 : : {
180 : : Oid8 chunk_id; /* toast_table.chunk_id */
181 : : int32 last_chunk_seq; /* toast_table.chunk_seq of the last chunk we
182 : : * have seen */
183 : : Size num_chunks; /* number of chunks we've already seen */
184 : : Size size; /* combined size of chunks seen */
185 : : dlist_head chunks; /* linked list of chunks */
186 : : varlena *reconstructed; /* reconstructed varlena now pointed to in
187 : : * main tup */
188 : : } ReorderBufferToastEnt;
189 : :
190 : : /* Disk serialization support datastructures */
191 : : typedef struct ReorderBufferDiskChange
192 : : {
193 : : Size size;
194 : : ReorderBufferChange change;
195 : : /* data follows */
196 : : } ReorderBufferDiskChange;
197 : :
198 : : #define IsSpecInsert(action) \
199 : : ( \
200 : : ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT) \
201 : : )
202 : : #define IsSpecConfirmOrAbort(action) \
203 : : ( \
204 : : (((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM) || \
205 : : ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT)) \
206 : : )
207 : : #define IsInsertOrUpdate(action) \
208 : : ( \
209 : : (((action) == REORDER_BUFFER_CHANGE_INSERT) || \
210 : : ((action) == REORDER_BUFFER_CHANGE_UPDATE) || \
211 : : ((action) == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT)) \
212 : : )
213 : :
214 : : /*
215 : : * Maximum number of changes kept in memory, per transaction. After that,
216 : : * changes are spooled to disk.
217 : : *
218 : : * The current value should be sufficient to decode the entire transaction
219 : : * without hitting disk in OLTP workloads, while starting to spool to disk in
220 : : * other workloads reasonably fast.
221 : : *
222 : : * At some point in the future it probably makes sense to have a more elaborate
223 : : * resource management here, but it's not entirely clear what that would look
224 : : * like.
225 : : */
226 : : int logical_decoding_work_mem;
227 : : static const Size max_changes_in_memory = 4096; /* XXX for restore only */
228 : :
229 : : /* GUC variable */
230 : : int debug_logical_replication_streaming = DEBUG_LOGICAL_REP_STREAMING_BUFFERED;
231 : :
232 : : /* ---------------------------------------
233 : : * primary reorderbuffer support routines
234 : : * ---------------------------------------
235 : : */
236 : : static ReorderBufferTXN *ReorderBufferAllocTXN(ReorderBuffer *rb);
237 : : static void ReorderBufferFreeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
238 : : static ReorderBufferTXN *ReorderBufferTXNByXid(ReorderBuffer *rb,
239 : : TransactionId xid, bool create, bool *is_new,
240 : : XLogRecPtr lsn, bool create_as_top);
241 : : static void ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
242 : : ReorderBufferTXN *subtxn);
243 : :
244 : : static void AssertTXNLsnOrder(ReorderBuffer *rb);
245 : : static bool TransactionIdInSubxactArray(TransactionId xid,
246 : : TransactionId *subxacts, int nsubxacts);
247 : :
248 : : /* ---------------------------------------
249 : : * support functions for lsn-order iterating over the ->changes of a
250 : : * transaction and its subtransactions
251 : : *
252 : : * used for iteration over the k-way heap merge of a transaction and its
253 : : * subtransactions
254 : : * ---------------------------------------
255 : : */
256 : : static void ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn,
257 : : ReorderBufferIterTXNState *volatile *iter_state);
258 : : static ReorderBufferChange *ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state);
259 : : static void ReorderBufferIterTXNFinish(ReorderBuffer *rb,
260 : : ReorderBufferIterTXNState *state);
261 : : static void ReorderBufferExecuteInvalidations(uint32 nmsgs, SharedInvalidationMessage *msgs);
262 : :
263 : : /*
264 : : * ---------------------------------------
265 : : * Disk serialization support functions
266 : : * ---------------------------------------
267 : : */
268 : : static void ReorderBufferCheckMemoryLimit(ReorderBuffer *rb);
269 : : static void ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
270 : : static void ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
271 : : int fd, ReorderBufferChange *change);
272 : : static Size ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
273 : : TXNEntryFile *file, XLogSegNo *segno);
274 : : static void ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
275 : : char *data);
276 : : static void ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn);
277 : : static void ReorderBufferTruncateTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
278 : : bool txn_prepared);
279 : : static void ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn);
280 : : static bool ReorderBufferCheckAndTruncateAbortedTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
281 : : static void ReorderBufferCleanupSerializedTXNs(const char *slotname);
282 : : static void ReorderBufferSerializedPath(char *path, ReplicationSlot *slot,
283 : : TransactionId xid, XLogSegNo segno);
284 : : static int ReorderBufferTXNSizeCompare(const pairingheap_node *a, const pairingheap_node *b, void *arg);
285 : :
286 : : static void ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap);
287 : : static Snapshot ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
288 : : ReorderBufferTXN *txn, CommandId cid);
289 : :
290 : : /*
291 : : * ---------------------------------------
292 : : * Streaming support functions
293 : : * ---------------------------------------
294 : : */
295 : : static inline bool ReorderBufferCanStream(ReorderBuffer *rb);
296 : : static inline bool ReorderBufferCanStartStreaming(ReorderBuffer *rb);
297 : : static void ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn);
298 : : static void ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn);
299 : :
300 : : /* ---------------------------------------
301 : : * toast reassembly support
302 : : * ---------------------------------------
303 : : */
304 : : static void ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn);
305 : : static void ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn);
306 : : static void ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
307 : : Relation relation, ReorderBufferChange *change);
308 : : static void ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
309 : : Relation relation, ReorderBufferChange *change);
310 : :
311 : : /*
312 : : * ---------------------------------------
313 : : * memory accounting
314 : : * ---------------------------------------
315 : : */
316 : : static Size ReorderBufferChangeSize(ReorderBufferChange *change);
317 : : static void ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
318 : : ReorderBufferChange *change,
319 : : ReorderBufferTXN *txn,
320 : : bool addition, Size sz);
321 : :
322 : : /*
323 : : * Allocate a new ReorderBuffer and clean out any old serialized state from
324 : : * prior ReorderBuffer instances for the same slot.
325 : : */
326 : : ReorderBuffer *
327 : 1310 : ReorderBufferAllocate(void)
328 : : {
329 : : ReorderBuffer *buffer;
330 : : HASHCTL hash_ctl;
331 : : MemoryContext new_ctx;
332 : :
333 : : Assert(MyReplicationSlot != NULL);
334 : :
335 : : /* allocate memory in own context, to have better accountability */
336 : 1310 : new_ctx = AllocSetContextCreate(CurrentMemoryContext,
337 : : "ReorderBuffer",
338 : : ALLOCSET_DEFAULT_SIZES);
339 : :
340 : : buffer =
341 : 1310 : (ReorderBuffer *) MemoryContextAlloc(new_ctx, sizeof(ReorderBuffer));
342 : :
343 : 1310 : memset(&hash_ctl, 0, sizeof(hash_ctl));
344 : :
345 : 1310 : buffer->context = new_ctx;
346 : :
347 : 1310 : buffer->change_context = SlabContextCreate(new_ctx,
348 : : "Change",
349 : : SLAB_DEFAULT_BLOCK_SIZE,
350 : : sizeof(ReorderBufferChange));
351 : :
352 : 1310 : buffer->txn_context = SlabContextCreate(new_ctx,
353 : : "TXN",
354 : : SLAB_DEFAULT_BLOCK_SIZE,
355 : : sizeof(ReorderBufferTXN));
356 : :
357 : : /*
358 : : * To minimize memory fragmentation caused by long-running transactions
359 : : * with changes spanning multiple memory blocks, we use a single
360 : : * fixed-size memory block for decoded tuple storage. The performance
361 : : * testing showed that the default memory block size maintains logical
362 : : * decoding performance without causing fragmentation due to concurrent
363 : : * transactions. One might think that we can use the max size as
364 : : * SLAB_LARGE_BLOCK_SIZE but the test also showed it doesn't help resolve
365 : : * the memory fragmentation.
366 : : */
367 : 1310 : buffer->tup_context = GenerationContextCreate(new_ctx,
368 : : "Tuples",
369 : : SLAB_DEFAULT_BLOCK_SIZE,
370 : : SLAB_DEFAULT_BLOCK_SIZE,
371 : : SLAB_DEFAULT_BLOCK_SIZE);
372 : :
373 : 1310 : hash_ctl.keysize = sizeof(TransactionId);
374 : 1310 : hash_ctl.entrysize = sizeof(ReorderBufferTXNByIdEnt);
375 : 1310 : hash_ctl.hcxt = buffer->context;
376 : :
377 : 1310 : buffer->by_txn = hash_create("ReorderBufferByXid", 1000, &hash_ctl,
378 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
379 : :
380 : 1310 : buffer->by_txn_last_xid = InvalidTransactionId;
381 : 1310 : buffer->by_txn_last_txn = NULL;
382 : :
383 : 1310 : buffer->outbuf = NULL;
384 : 1310 : buffer->outbufsize = 0;
385 : 1310 : buffer->size = 0;
386 : :
387 : : /* txn_heap is ordered by transaction size */
388 : 1310 : buffer->txn_heap = pairingheap_allocate(ReorderBufferTXNSizeCompare, NULL);
389 : :
390 : 1310 : buffer->spillTxns = 0;
391 : 1310 : buffer->spillCount = 0;
392 : 1310 : buffer->spillBytes = 0;
393 : 1310 : buffer->streamTxns = 0;
394 : 1310 : buffer->streamCount = 0;
395 : 1310 : buffer->streamBytes = 0;
396 : 1310 : buffer->memExceededCount = 0;
397 : 1310 : buffer->totalTxns = 0;
398 : 1310 : buffer->totalBytes = 0;
399 : :
400 : 1310 : buffer->current_restart_decoding_lsn = InvalidXLogRecPtr;
401 : :
402 : 1310 : dlist_init(&buffer->toplevel_by_lsn);
403 : 1310 : dlist_init(&buffer->txns_by_base_snapshot_lsn);
404 : 1310 : dclist_init(&buffer->catchange_txns);
405 : :
406 : : /*
407 : : * Ensure there's no stale data from prior uses of this slot, in case some
408 : : * prior exit avoided calling ReorderBufferFree. Failure to do this can
409 : : * produce duplicated txns, and it's very cheap if there's nothing there.
410 : : */
411 : 1310 : ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
412 : :
413 : 1310 : return buffer;
414 : : }
415 : :
416 : : /*
417 : : * Free a ReorderBuffer
418 : : */
419 : : void
420 : 1011 : ReorderBufferFree(ReorderBuffer *rb)
421 : : {
422 : 1011 : MemoryContext context = rb->context;
423 : :
424 : : /*
425 : : * We free separately allocated data by entirely scrapping reorderbuffer's
426 : : * memory context.
427 : : */
428 : 1011 : MemoryContextDelete(context);
429 : :
430 : : /* Free disk space used by unconsumed reorder buffers */
431 : 1011 : ReorderBufferCleanupSerializedTXNs(NameStr(MyReplicationSlot->data.name));
432 : 1011 : }
433 : :
434 : : /*
435 : : * Allocate a new ReorderBufferTXN.
436 : : */
437 : : static ReorderBufferTXN *
438 : 5537 : ReorderBufferAllocTXN(ReorderBuffer *rb)
439 : : {
440 : : ReorderBufferTXN *txn;
441 : :
442 : : txn = (ReorderBufferTXN *)
443 : 5537 : MemoryContextAlloc(rb->txn_context, sizeof(ReorderBufferTXN));
444 : :
445 : 5537 : memset(txn, 0, sizeof(ReorderBufferTXN));
446 : :
447 : 5537 : dlist_init(&txn->changes);
448 : 5537 : dlist_init(&txn->tuplecids);
449 : 5537 : dlist_init(&txn->subtxns);
450 : :
451 : : /* InvalidCommandId is not zero, so set it explicitly */
452 : 5537 : txn->command_id = InvalidCommandId;
453 : 5537 : txn->output_plugin_private = NULL;
454 : :
455 : 5537 : return txn;
456 : : }
457 : :
458 : : /*
459 : : * Free a ReorderBufferTXN.
460 : : */
461 : : static void
462 : 5452 : ReorderBufferFreeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
463 : : {
464 : : /* clean the lookup cache if we were cached (quite likely) */
465 [ + + ]: 5452 : if (rb->by_txn_last_xid == txn->xid)
466 : : {
467 : 5258 : rb->by_txn_last_xid = InvalidTransactionId;
468 : 5258 : rb->by_txn_last_txn = NULL;
469 : : }
470 : :
471 : : /* free data that's contained */
472 : :
473 [ + + ]: 5452 : if (txn->gid != NULL)
474 : : {
475 : 49 : pfree(txn->gid);
476 : 49 : txn->gid = NULL;
477 : : }
478 : :
479 [ + + ]: 5452 : if (txn->tuplecid_hash != NULL)
480 : : {
481 : 1364 : hash_destroy(txn->tuplecid_hash);
482 : 1364 : txn->tuplecid_hash = NULL;
483 : : }
484 : :
485 [ + + ]: 5452 : if (txn->invalidations)
486 : : {
487 : 2045 : pfree(txn->invalidations);
488 : 2045 : txn->invalidations = NULL;
489 : : }
490 : :
491 [ + + ]: 5452 : if (txn->invalidations_distributed)
492 : : {
493 : 21 : pfree(txn->invalidations_distributed);
494 : 21 : txn->invalidations_distributed = NULL;
495 : : }
496 : :
497 : : /* Reset the toast hash */
498 : 5452 : ReorderBufferToastReset(rb, txn);
499 : :
500 : : /* All changes must be deallocated */
501 : : Assert(txn->size == 0);
502 : :
503 : 5452 : pfree(txn);
504 : 5452 : }
505 : :
506 : : /*
507 : : * Allocate a ReorderBufferChange.
508 : : */
509 : : ReorderBufferChange *
510 : 1653193 : ReorderBufferAllocChange(ReorderBuffer *rb)
511 : : {
512 : : ReorderBufferChange *change;
513 : :
514 : : change = (ReorderBufferChange *)
515 : 1653193 : MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange));
516 : :
517 : 1653193 : memset(change, 0, sizeof(ReorderBufferChange));
518 : 1653193 : return change;
519 : : }
520 : :
521 : : /*
522 : : * Free a ReorderBufferChange and update memory accounting, if requested.
523 : : */
524 : : void
525 : 1631489 : ReorderBufferFreeChange(ReorderBuffer *rb, ReorderBufferChange *change,
526 : : bool upd_mem)
527 : : {
528 : : /* update memory accounting info */
529 [ + + ]: 1631489 : if (upd_mem)
530 : 209579 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, false,
531 : : ReorderBufferChangeSize(change));
532 : :
533 : : /* free contained data */
534 [ + + + + : 1631489 : switch (change->action)
+ + - ]
535 : : {
536 : 1537056 : case REORDER_BUFFER_CHANGE_INSERT:
537 : : case REORDER_BUFFER_CHANGE_UPDATE:
538 : : case REORDER_BUFFER_CHANGE_DELETE:
539 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
540 [ + + ]: 1537056 : if (change->data.tp.newtuple)
541 : : {
542 : 1276996 : ReorderBufferFreeTupleBuf(change->data.tp.newtuple);
543 : 1276996 : change->data.tp.newtuple = NULL;
544 : : }
545 : :
546 [ + + ]: 1537056 : if (change->data.tp.oldtuple)
547 : : {
548 : 186228 : ReorderBufferFreeTupleBuf(change->data.tp.oldtuple);
549 : 186228 : change->data.tp.oldtuple = NULL;
550 : : }
551 : 1537056 : break;
552 : 42 : case REORDER_BUFFER_CHANGE_MESSAGE:
553 [ + - ]: 42 : if (change->data.msg.prefix != NULL)
554 : 42 : pfree(change->data.msg.prefix);
555 : 42 : change->data.msg.prefix = NULL;
556 [ + - ]: 42 : if (change->data.msg.message != NULL)
557 : 42 : pfree(change->data.msg.message);
558 : 42 : change->data.msg.message = NULL;
559 : 42 : break;
560 : 6945 : case REORDER_BUFFER_CHANGE_INVALIDATION:
561 [ + - ]: 6945 : if (change->data.inval.invalidations)
562 : 6945 : pfree(change->data.inval.invalidations);
563 : 6945 : change->data.inval.invalidations = NULL;
564 : 6945 : break;
565 : 2082 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
566 [ + - ]: 2082 : if (change->data.snapshot)
567 : : {
568 : 2082 : ReorderBufferFreeSnap(rb, change->data.snapshot);
569 : 2082 : change->data.snapshot = NULL;
570 : : }
571 : 2082 : break;
572 : : /* no data in addition to the struct itself */
573 : 49 : case REORDER_BUFFER_CHANGE_TRUNCATE:
574 [ + - ]: 49 : if (change->data.truncate.relids != NULL)
575 : : {
576 : 49 : ReorderBufferFreeRelids(rb, change->data.truncate.relids);
577 : 49 : change->data.truncate.relids = NULL;
578 : : }
579 : 49 : break;
580 : 85315 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
581 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
582 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
583 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
584 : 85315 : break;
585 : : }
586 : :
587 : 1631489 : pfree(change);
588 : 1631489 : }
589 : :
590 : : /*
591 : : * Allocate a HeapTuple fitting a tuple of size tuple_len (excluding header
592 : : * overhead).
593 : : */
594 : : HeapTuple
595 : 1483583 : ReorderBufferAllocTupleBuf(ReorderBuffer *rb, Size tuple_len)
596 : : {
597 : : HeapTuple tuple;
598 : : Size alloc_len;
599 : :
600 : 1483583 : alloc_len = tuple_len + SizeofHeapTupleHeader;
601 : :
602 : 1483583 : tuple = (HeapTuple) MemoryContextAlloc(rb->tup_context,
603 : : HEAPTUPLESIZE + alloc_len);
604 : 1483583 : tuple->t_data = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
605 : :
606 : 1483583 : return tuple;
607 : : }
608 : :
609 : : /*
610 : : * Free a HeapTuple returned by ReorderBufferAllocTupleBuf().
611 : : */
612 : : void
613 : 1463224 : ReorderBufferFreeTupleBuf(HeapTuple tuple)
614 : : {
615 : 1463224 : pfree(tuple);
616 : 1463224 : }
617 : :
618 : : /*
619 : : * Allocate an array for relids of truncated relations.
620 : : *
621 : : * We use the global memory context (for the whole reorder buffer), because
622 : : * none of the existing ones seems like a good match (some are SLAB, so we
623 : : * can't use those, and tup_context is meant for tuple data, not relids). We
624 : : * could add yet another context, but it seems like an overkill - TRUNCATE is
625 : : * not particularly common operation, so it does not seem worth it.
626 : : */
627 : : Oid *
628 : 54 : ReorderBufferAllocRelids(ReorderBuffer *rb, int nrelids)
629 : : {
630 : : Oid *relids;
631 : : Size alloc_len;
632 : :
633 : 54 : alloc_len = sizeof(Oid) * nrelids;
634 : :
635 : 54 : relids = (Oid *) MemoryContextAlloc(rb->context, alloc_len);
636 : :
637 : 54 : return relids;
638 : : }
639 : :
640 : : /*
641 : : * Free an array of relids.
642 : : */
643 : : void
644 : 49 : ReorderBufferFreeRelids(ReorderBuffer *rb, Oid *relids)
645 : : {
646 : 49 : pfree(relids);
647 : 49 : }
648 : :
649 : : /*
650 : : * Return the ReorderBufferTXN from the given buffer, specified by Xid.
651 : : * If create is true, and a transaction doesn't already exist, create it
652 : : * (with the given LSN, and as top transaction if that's specified);
653 : : * when this happens, is_new is set to true.
654 : : */
655 : : static ReorderBufferTXN *
656 : 5534672 : ReorderBufferTXNByXid(ReorderBuffer *rb, TransactionId xid, bool create,
657 : : bool *is_new, XLogRecPtr lsn, bool create_as_top)
658 : : {
659 : : ReorderBufferTXN *txn;
660 : : ReorderBufferTXNByIdEnt *ent;
661 : : bool found;
662 : :
663 : : Assert(TransactionIdIsValid(xid));
664 : :
665 : : /*
666 : : * Check the one-entry lookup cache first
667 : : */
668 [ + + ]: 5534672 : if (TransactionIdIsValid(rb->by_txn_last_xid) &&
669 [ + + ]: 5529349 : rb->by_txn_last_xid == xid)
670 : : {
671 : 4888593 : txn = rb->by_txn_last_txn;
672 : :
673 [ + + ]: 4888593 : if (txn != NULL)
674 : : {
675 : : /* found it, and it's valid */
676 [ + + ]: 4888518 : if (is_new)
677 : 4784 : *is_new = false;
678 : 4888518 : return txn;
679 : : }
680 : :
681 : : /*
682 : : * cached as non-existent, and asked not to create? Then nothing else
683 : : * to do.
684 : : */
685 [ + + ]: 75 : if (!create)
686 : 72 : return NULL;
687 : : /* otherwise fall through to create it */
688 : : }
689 : :
690 : : /*
691 : : * If the cache wasn't hit or it yielded a "does-not-exist" and we want to
692 : : * create an entry.
693 : : */
694 : :
695 : : /* search the lookup table */
696 : : ent = (ReorderBufferTXNByIdEnt *)
697 : 646082 : hash_search(rb->by_txn,
698 : : &xid,
699 : : create ? HASH_ENTER : HASH_FIND,
700 : : &found);
701 [ + + ]: 646082 : if (found)
702 : 639039 : txn = ent->txn;
703 [ + + ]: 7043 : else if (create)
704 : : {
705 : : /* initialize the new entry, if creation was requested */
706 : : Assert(ent != NULL);
707 : : Assert(XLogRecPtrIsValid(lsn));
708 : :
709 : 5537 : ent->txn = ReorderBufferAllocTXN(rb);
710 : 5537 : ent->txn->xid = xid;
711 : 5537 : txn = ent->txn;
712 : 5537 : txn->first_lsn = lsn;
713 : 5537 : txn->restart_decoding_lsn = rb->current_restart_decoding_lsn;
714 : :
715 [ + + ]: 5537 : if (create_as_top)
716 : : {
717 : 4865 : dlist_push_tail(&rb->toplevel_by_lsn, &txn->node);
718 : 4865 : AssertTXNLsnOrder(rb);
719 : : }
720 : : }
721 : : else
722 : 1506 : txn = NULL; /* not found and not asked to create */
723 : :
724 : : /* update cache */
725 : 646082 : rb->by_txn_last_xid = xid;
726 : 646082 : rb->by_txn_last_txn = txn;
727 : :
728 [ + + ]: 646082 : if (is_new)
729 : 1772 : *is_new = !found;
730 : :
731 : : Assert(!create || txn != NULL);
732 : 646082 : return txn;
733 : : }
734 : :
735 : : /*
736 : : * Record the partial change for the streaming of in-progress transactions. We
737 : : * can stream only complete changes so if we have a partial change like toast
738 : : * table insert or speculative insert then we mark such a 'txn' so that it
739 : : * can't be streamed. We also ensure that if the changes in such a 'txn' can
740 : : * be streamed and are above logical_decoding_work_mem threshold then we stream
741 : : * them as soon as we have a complete change.
742 : : */
743 : : static void
744 : 1428410 : ReorderBufferProcessPartialChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
745 : : ReorderBufferChange *change,
746 : : bool toast_insert)
747 : : {
748 : : ReorderBufferTXN *toptxn;
749 : :
750 : : /*
751 : : * The partial changes need to be processed only while streaming
752 : : * in-progress transactions.
753 : : */
754 [ + + ]: 1428410 : if (!ReorderBufferCanStream(rb))
755 : 961304 : return;
756 : :
757 : : /* Get the top transaction. */
758 [ + + ]: 467106 : toptxn = rbtxn_get_toptxn(txn);
759 : :
760 : : /*
761 : : * Indicate a partial change for toast inserts. The change will be
762 : : * considered as complete once we get the insert or update on the main
763 : : * table and we are sure that the pending toast chunks are not required
764 : : * anymore.
765 : : *
766 : : * If we allow streaming when there are pending toast chunks then such
767 : : * chunks won't be released till the insert (multi_insert) is complete and
768 : : * we expect the txn to have streamed all changes after streaming. This
769 : : * restriction is mainly to ensure the correctness of streamed
770 : : * transactions and it doesn't seem worth uplifting such a restriction
771 : : * just to allow this case because anyway we will stream the transaction
772 : : * once such an insert is complete.
773 : : */
774 [ + + ]: 467106 : if (toast_insert)
775 : 1649 : toptxn->txn_flags |= RBTXN_HAS_PARTIAL_CHANGE;
776 [ + + ]: 465457 : else if (rbtxn_has_partial_change(toptxn) &&
777 [ + + + - : 60 : IsInsertOrUpdate(change->action) &&
- + ]
778 [ + + ]: 57 : change->data.tp.clear_toast_afterwards)
779 : 37 : toptxn->txn_flags &= ~RBTXN_HAS_PARTIAL_CHANGE;
780 : :
781 : : /*
782 : : * Indicate a partial change for speculative inserts. The change will be
783 : : * considered as complete once we get the speculative confirm or abort
784 : : * token.
785 : : */
786 [ + + ]: 467106 : if (IsSpecInsert(change->action))
787 : 3 : toptxn->txn_flags |= RBTXN_HAS_PARTIAL_CHANGE;
788 [ + + ]: 467103 : else if (rbtxn_has_partial_change(toptxn) &&
789 [ + + - + ]: 1672 : IsSpecConfirmOrAbort(change->action))
790 : 3 : toptxn->txn_flags &= ~RBTXN_HAS_PARTIAL_CHANGE;
791 : :
792 : : /*
793 : : * Stream the transaction if it is serialized before and the changes are
794 : : * now complete in the top-level transaction.
795 : : *
796 : : * The reason for doing the streaming of such a transaction as soon as we
797 : : * get the complete change for it is that previously it would have reached
798 : : * the memory threshold and wouldn't get streamed because of incomplete
799 : : * changes. Delaying such transactions would increase apply lag for them.
800 : : */
801 [ + + ]: 467106 : if (ReorderBufferCanStartStreaming(rb) &&
802 [ + + ]: 210008 : !(rbtxn_has_partial_change(toptxn)) &&
803 [ + + ]: 208474 : rbtxn_is_serialized(txn) &&
804 [ + + ]: 56 : rbtxn_has_streamable_change(toptxn))
805 : 8 : ReorderBufferStreamTXN(rb, toptxn);
806 : : }
807 : :
808 : : /*
809 : : * Queue a change into a transaction so it can be replayed upon commit or will be
810 : : * streamed when we reach logical_decoding_work_mem threshold.
811 : : */
812 : : void
813 : 1442396 : ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
814 : : ReorderBufferChange *change, bool toast_insert)
815 : : {
816 : : ReorderBufferTXN *txn;
817 : :
818 : 1442396 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
819 : :
820 : : /*
821 : : * If we have detected that the transaction is aborted while streaming the
822 : : * previous changes or by checking its CLOG, there is no point in
823 : : * collecting further changes for it.
824 : : */
825 [ + + ]: 1442396 : if (rbtxn_is_aborted(txn))
826 : : {
827 : : /*
828 : : * We don't need to update memory accounting for this change as we
829 : : * have not added it to the queue yet.
830 : : */
831 : 13986 : ReorderBufferFreeChange(rb, change, false);
832 : 13986 : return;
833 : : }
834 : :
835 : : /*
836 : : * The changes that are sent downstream are considered streamable. We
837 : : * remember such transactions so that only those will later be considered
838 : : * for streaming.
839 : : */
840 [ + + ]: 1428410 : if (change->action == REORDER_BUFFER_CHANGE_INSERT ||
841 [ + + ]: 517234 : change->action == REORDER_BUFFER_CHANGE_UPDATE ||
842 [ + + ]: 330795 : change->action == REORDER_BUFFER_CHANGE_DELETE ||
843 [ + + ]: 80952 : change->action == REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT ||
844 [ + + ]: 61250 : change->action == REORDER_BUFFER_CHANGE_TRUNCATE ||
845 [ + + ]: 61207 : change->action == REORDER_BUFFER_CHANGE_MESSAGE)
846 : : {
847 [ + + ]: 1367244 : ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
848 : :
849 : 1367244 : toptxn->txn_flags |= RBTXN_HAS_STREAMABLE_CHANGE;
850 : : }
851 : :
852 : 1428410 : change->lsn = lsn;
853 : 1428410 : change->txn = txn;
854 : :
855 : : Assert(XLogRecPtrIsValid(lsn));
856 : 1428410 : dlist_push_tail(&txn->changes, &change->node);
857 : 1428410 : txn->nentries++;
858 : 1428410 : txn->nentries_mem++;
859 : :
860 : : /* update memory accounting information */
861 : 1428410 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
862 : : ReorderBufferChangeSize(change));
863 : :
864 : : /* process partial change */
865 : 1428410 : ReorderBufferProcessPartialChange(rb, txn, change, toast_insert);
866 : :
867 : : /* check the memory limits and evict something if needed */
868 : 1428410 : ReorderBufferCheckMemoryLimit(rb);
869 : : }
870 : :
871 : : /*
872 : : * A transactional message is queued to be processed upon commit and a
873 : : * non-transactional message gets processed immediately.
874 : : */
875 : : void
876 : 49 : ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
877 : : Snapshot snap, XLogRecPtr lsn,
878 : : bool transactional, const char *prefix,
879 : : Size message_size, const char *message)
880 : : {
881 [ + + ]: 49 : if (transactional)
882 : : {
883 : : MemoryContext oldcontext;
884 : : ReorderBufferChange *change;
885 : :
886 : : Assert(xid != InvalidTransactionId);
887 : :
888 : : /*
889 : : * We don't expect snapshots for transactional changes - we'll use the
890 : : * snapshot derived later during apply (unless the change gets
891 : : * skipped).
892 : : */
893 : : Assert(!snap);
894 : :
895 : 41 : oldcontext = MemoryContextSwitchTo(rb->context);
896 : :
897 : 41 : change = ReorderBufferAllocChange(rb);
898 : 41 : change->action = REORDER_BUFFER_CHANGE_MESSAGE;
899 : 41 : change->data.msg.prefix = pstrdup(prefix);
900 : 41 : change->data.msg.message_size = message_size;
901 : 41 : change->data.msg.message = palloc(message_size);
902 : 41 : memcpy(change->data.msg.message, message, message_size);
903 : :
904 : 41 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
905 : :
906 : 41 : MemoryContextSwitchTo(oldcontext);
907 : : }
908 : : else
909 : : {
910 : 8 : ReorderBufferTXN *txn = NULL;
911 : 8 : volatile Snapshot snapshot_now = snap;
912 : :
913 : : /* Non-transactional changes require a valid snapshot. */
914 : : Assert(snapshot_now);
915 : :
916 [ + + ]: 8 : if (xid != InvalidTransactionId)
917 : 3 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
918 : :
919 : : /* setup snapshot to allow catalog access */
920 : 8 : SetupHistoricSnapshot(snapshot_now, NULL);
921 [ + - ]: 8 : PG_TRY();
922 : : {
923 : 8 : rb->message(rb, txn, lsn, false, prefix, message_size, message);
924 : :
925 : 8 : TeardownHistoricSnapshot(false);
926 : : }
927 : 0 : PG_CATCH();
928 : : {
929 : 0 : TeardownHistoricSnapshot(true);
930 : 0 : PG_RE_THROW();
931 : : }
932 [ - + ]: 8 : PG_END_TRY();
933 : : }
934 : 49 : }
935 : :
936 : : /*
937 : : * AssertTXNLsnOrder
938 : : * Verify LSN ordering of transaction lists in the reorderbuffer
939 : : *
940 : : * Other LSN-related invariants are checked too.
941 : : *
942 : : * No-op if assertions are not in use.
943 : : */
944 : : static void
945 : 11591 : AssertTXNLsnOrder(ReorderBuffer *rb)
946 : : {
947 : : #ifdef USE_ASSERT_CHECKING
948 : : LogicalDecodingContext *ctx = rb->private_data;
949 : : dlist_iter iter;
950 : : XLogRecPtr prev_first_lsn = InvalidXLogRecPtr;
951 : : XLogRecPtr prev_base_snap_lsn = InvalidXLogRecPtr;
952 : :
953 : : /*
954 : : * Skip the verification if we don't reach the LSN at which we start
955 : : * decoding the contents of transactions yet because until we reach the
956 : : * LSN, we could have transactions that don't have the association between
957 : : * the top-level transaction and subtransaction yet and consequently have
958 : : * the same LSN. We don't guarantee this association until we try to
959 : : * decode the actual contents of transaction. The ordering of the records
960 : : * prior to the start_decoding_at LSN should have been checked before the
961 : : * restart.
962 : : */
963 : : if (SnapBuildXactNeedsSkip(ctx->snapshot_builder, ctx->reader->EndRecPtr))
964 : : return;
965 : :
966 : : dlist_foreach(iter, &rb->toplevel_by_lsn)
967 : : {
968 : : ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN, node,
969 : : iter.cur);
970 : :
971 : : /* start LSN must be set */
972 : : Assert(XLogRecPtrIsValid(cur_txn->first_lsn));
973 : :
974 : : /* If there is an end LSN, it must be higher than start LSN */
975 : : if (XLogRecPtrIsValid(cur_txn->end_lsn))
976 : : Assert(cur_txn->first_lsn <= cur_txn->end_lsn);
977 : :
978 : : /* Current initial LSN must be strictly higher than previous */
979 : : if (XLogRecPtrIsValid(prev_first_lsn))
980 : : Assert(prev_first_lsn < cur_txn->first_lsn);
981 : :
982 : : /* known-as-subtxn txns must not be listed */
983 : : Assert(!rbtxn_is_known_subxact(cur_txn));
984 : :
985 : : prev_first_lsn = cur_txn->first_lsn;
986 : : }
987 : :
988 : : dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
989 : : {
990 : : ReorderBufferTXN *cur_txn = dlist_container(ReorderBufferTXN,
991 : : base_snapshot_node,
992 : : iter.cur);
993 : :
994 : : /* base snapshot (and its LSN) must be set */
995 : : Assert(cur_txn->base_snapshot != NULL);
996 : : Assert(XLogRecPtrIsValid(cur_txn->base_snapshot_lsn));
997 : :
998 : : /* current LSN must be strictly higher than previous */
999 : : if (XLogRecPtrIsValid(prev_base_snap_lsn))
1000 : : Assert(prev_base_snap_lsn < cur_txn->base_snapshot_lsn);
1001 : :
1002 : : /* known-as-subtxn txns must not be listed */
1003 : : Assert(!rbtxn_is_known_subxact(cur_txn));
1004 : :
1005 : : prev_base_snap_lsn = cur_txn->base_snapshot_lsn;
1006 : : }
1007 : : #endif
1008 : 11591 : }
1009 : :
1010 : : /*
1011 : : * AssertChangeLsnOrder
1012 : : *
1013 : : * Check ordering of changes in the (sub)transaction.
1014 : : */
1015 : : static void
1016 : 3651 : AssertChangeLsnOrder(ReorderBufferTXN *txn)
1017 : : {
1018 : : #ifdef USE_ASSERT_CHECKING
1019 : : dlist_iter iter;
1020 : : XLogRecPtr prev_lsn = txn->first_lsn;
1021 : :
1022 : : dlist_foreach(iter, &txn->changes)
1023 : : {
1024 : : ReorderBufferChange *cur_change;
1025 : :
1026 : : cur_change = dlist_container(ReorderBufferChange, node, iter.cur);
1027 : :
1028 : : Assert(XLogRecPtrIsValid(txn->first_lsn));
1029 : : Assert(XLogRecPtrIsValid(cur_change->lsn));
1030 : : Assert(txn->first_lsn <= cur_change->lsn);
1031 : :
1032 : : if (XLogRecPtrIsValid(txn->end_lsn))
1033 : : Assert(cur_change->lsn <= txn->end_lsn);
1034 : :
1035 : : Assert(prev_lsn <= cur_change->lsn);
1036 : :
1037 : : prev_lsn = cur_change->lsn;
1038 : : }
1039 : : #endif
1040 : 3651 : }
1041 : :
1042 : : /*
1043 : : * ReorderBufferGetOldestTXN
1044 : : * Return oldest transaction in reorderbuffer
1045 : : */
1046 : : ReorderBufferTXN *
1047 : 600 : ReorderBufferGetOldestTXN(ReorderBuffer *rb)
1048 : : {
1049 : : ReorderBufferTXN *txn;
1050 : :
1051 : 600 : AssertTXNLsnOrder(rb);
1052 : :
1053 [ + + ]: 600 : if (dlist_is_empty(&rb->toplevel_by_lsn))
1054 : 535 : return NULL;
1055 : :
1056 : 65 : txn = dlist_head_element(ReorderBufferTXN, node, &rb->toplevel_by_lsn);
1057 : :
1058 : : Assert(!rbtxn_is_known_subxact(txn));
1059 : : Assert(XLogRecPtrIsValid(txn->first_lsn));
1060 : 65 : return txn;
1061 : : }
1062 : :
1063 : : /*
1064 : : * ReorderBufferGetOldestXmin
1065 : : * Return oldest Xmin in reorderbuffer
1066 : : *
1067 : : * Returns oldest possibly running Xid from the point of view of snapshots
1068 : : * used in the transactions kept by reorderbuffer, or InvalidTransactionId if
1069 : : * there are none.
1070 : : *
1071 : : * Since snapshots are assigned monotonically, this equals the Xmin of the
1072 : : * base snapshot with minimal base_snapshot_lsn.
1073 : : */
1074 : : TransactionId
1075 : 624 : ReorderBufferGetOldestXmin(ReorderBuffer *rb)
1076 : : {
1077 : : ReorderBufferTXN *txn;
1078 : :
1079 : 624 : AssertTXNLsnOrder(rb);
1080 : :
1081 [ + + ]: 624 : if (dlist_is_empty(&rb->txns_by_base_snapshot_lsn))
1082 : 568 : return InvalidTransactionId;
1083 : :
1084 : 56 : txn = dlist_head_element(ReorderBufferTXN, base_snapshot_node,
1085 : : &rb->txns_by_base_snapshot_lsn);
1086 : 56 : return txn->base_snapshot->xmin;
1087 : : }
1088 : :
1089 : : void
1090 : 726 : ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
1091 : : {
1092 : 726 : rb->current_restart_decoding_lsn = ptr;
1093 : 726 : }
1094 : :
1095 : : /*
1096 : : * ReorderBufferAssignChild
1097 : : *
1098 : : * Make note that we know that subxid is a subtransaction of xid, seen as of
1099 : : * the given lsn.
1100 : : */
1101 : : void
1102 : 863 : ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
1103 : : TransactionId subxid, XLogRecPtr lsn)
1104 : : {
1105 : : ReorderBufferTXN *txn;
1106 : : ReorderBufferTXN *subtxn;
1107 : : bool new_top;
1108 : : bool new_sub;
1109 : :
1110 : 863 : txn = ReorderBufferTXNByXid(rb, xid, true, &new_top, lsn, true);
1111 : 863 : subtxn = ReorderBufferTXNByXid(rb, subxid, true, &new_sub, lsn, false);
1112 : :
1113 [ + + ]: 863 : if (!new_sub)
1114 : : {
1115 [ + - ]: 191 : if (rbtxn_is_known_subxact(subtxn))
1116 : : {
1117 : : /* already associated, nothing to do */
1118 : 191 : return;
1119 : : }
1120 : : else
1121 : : {
1122 : : /*
1123 : : * We already saw this transaction, but initially added it to the
1124 : : * list of top-level txns. Now that we know it's not top-level,
1125 : : * remove it from there.
1126 : : */
1127 : 0 : dlist_delete(&subtxn->node);
1128 : : }
1129 : : }
1130 : :
1131 : 672 : subtxn->txn_flags |= RBTXN_IS_SUBXACT;
1132 : 672 : subtxn->toplevel_xid = xid;
1133 : : Assert(subtxn->nsubtxns == 0);
1134 : :
1135 : : /* set the reference to top-level transaction */
1136 : 672 : subtxn->toptxn = txn;
1137 : :
1138 : : /* add to subtransaction list */
1139 : 672 : dlist_push_tail(&txn->subtxns, &subtxn->node);
1140 : 672 : txn->nsubtxns++;
1141 : :
1142 : : /* Possibly transfer the subtxn's snapshot to its top-level txn. */
1143 : 672 : ReorderBufferTransferSnapToParent(txn, subtxn);
1144 : :
1145 : : /* Verify LSN-ordering invariant */
1146 : 672 : AssertTXNLsnOrder(rb);
1147 : : }
1148 : :
1149 : : /*
1150 : : * ReorderBufferTransferSnapToParent
1151 : : * Transfer base snapshot from subtxn to top-level txn, if needed
1152 : : *
1153 : : * This is done if the top-level txn doesn't have a base snapshot, or if the
1154 : : * subtxn's base snapshot has an earlier LSN than the top-level txn's base
1155 : : * snapshot's LSN. This can happen if there are no changes in the toplevel
1156 : : * txn but there are some in the subtxn, or the first change in subtxn has
1157 : : * earlier LSN than first change in the top-level txn and we learned about
1158 : : * their kinship only now.
1159 : : *
1160 : : * The subtransaction's snapshot is cleared regardless of the transfer
1161 : : * happening, since it's not needed anymore in either case.
1162 : : *
1163 : : * We do this as soon as we become aware of their kinship, to avoid queueing
1164 : : * extra snapshots to txns known-as-subtxns -- only top-level txns will
1165 : : * receive further snapshots.
1166 : : */
1167 : : static void
1168 : 676 : ReorderBufferTransferSnapToParent(ReorderBufferTXN *txn,
1169 : : ReorderBufferTXN *subtxn)
1170 : : {
1171 : : Assert(subtxn->toplevel_xid == txn->xid);
1172 : :
1173 [ - + ]: 676 : if (subtxn->base_snapshot != NULL)
1174 : : {
1175 [ # # ]: 0 : if (txn->base_snapshot == NULL ||
1176 [ # # ]: 0 : subtxn->base_snapshot_lsn < txn->base_snapshot_lsn)
1177 : : {
1178 : : /*
1179 : : * If the toplevel transaction already has a base snapshot but
1180 : : * it's newer than the subxact's, purge it.
1181 : : */
1182 [ # # ]: 0 : if (txn->base_snapshot != NULL)
1183 : : {
1184 : 0 : SnapBuildSnapDecRefcount(txn->base_snapshot);
1185 : 0 : dlist_delete(&txn->base_snapshot_node);
1186 : : }
1187 : :
1188 : : /*
1189 : : * The snapshot is now the top transaction's; transfer it, and
1190 : : * adjust the list position of the top transaction in the list by
1191 : : * moving it to where the subtransaction is.
1192 : : */
1193 : 0 : txn->base_snapshot = subtxn->base_snapshot;
1194 : 0 : txn->base_snapshot_lsn = subtxn->base_snapshot_lsn;
1195 : 0 : dlist_insert_before(&subtxn->base_snapshot_node,
1196 : : &txn->base_snapshot_node);
1197 : :
1198 : : /*
1199 : : * The subtransaction doesn't have a snapshot anymore (so it
1200 : : * mustn't be in the list.)
1201 : : */
1202 : 0 : subtxn->base_snapshot = NULL;
1203 : 0 : subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
1204 : 0 : dlist_delete(&subtxn->base_snapshot_node);
1205 : : }
1206 : : else
1207 : : {
1208 : : /* Base snap of toplevel is fine, so subxact's is not needed */
1209 : 0 : SnapBuildSnapDecRefcount(subtxn->base_snapshot);
1210 : 0 : dlist_delete(&subtxn->base_snapshot_node);
1211 : 0 : subtxn->base_snapshot = NULL;
1212 : 0 : subtxn->base_snapshot_lsn = InvalidXLogRecPtr;
1213 : : }
1214 : : }
1215 : 676 : }
1216 : :
1217 : : /*
1218 : : * Associate a subtransaction with its toplevel transaction at commit
1219 : : * time. There may be no further changes added after this.
1220 : : */
1221 : : void
1222 : 272 : ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
1223 : : TransactionId subxid, XLogRecPtr commit_lsn,
1224 : : XLogRecPtr end_lsn)
1225 : : {
1226 : : ReorderBufferTXN *subtxn;
1227 : :
1228 : 272 : subtxn = ReorderBufferTXNByXid(rb, subxid, false, NULL,
1229 : : InvalidXLogRecPtr, false);
1230 : :
1231 : : /*
1232 : : * No need to do anything if that subtxn didn't contain any changes
1233 : : */
1234 [ + + ]: 272 : if (!subtxn)
1235 : 81 : return;
1236 : :
1237 : 191 : subtxn->final_lsn = commit_lsn;
1238 : 191 : subtxn->end_lsn = end_lsn;
1239 : :
1240 : : /*
1241 : : * Assign this subxact as a child of the toplevel xact (no-op if already
1242 : : * done.)
1243 : : */
1244 : 191 : ReorderBufferAssignChild(rb, xid, subxid, InvalidXLogRecPtr);
1245 : : }
1246 : :
1247 : :
1248 : : /*
1249 : : * Support for efficiently iterating over a transaction's and its
1250 : : * subtransactions' changes.
1251 : : *
1252 : : * We do by doing a k-way merge between transactions/subtransactions. For that
1253 : : * we model the current heads of the different transactions as a binary heap
1254 : : * so we easily know which (sub-)transaction has the change with the smallest
1255 : : * lsn next.
1256 : : *
1257 : : * We assume the changes in individual transactions are already sorted by LSN.
1258 : : */
1259 : :
1260 : : /*
1261 : : * Binary heap comparison function.
1262 : : */
1263 : : static int
1264 : 51676 : ReorderBufferIterCompare(Datum a, Datum b, void *arg)
1265 : : {
1266 : 51676 : ReorderBufferIterTXNState *state = (ReorderBufferIterTXNState *) arg;
1267 : 51676 : XLogRecPtr pos_a = state->entries[DatumGetInt32(a)].lsn;
1268 : 51676 : XLogRecPtr pos_b = state->entries[DatumGetInt32(b)].lsn;
1269 : :
1270 [ + + ]: 51676 : if (pos_a < pos_b)
1271 : 50817 : return 1;
1272 [ - + ]: 859 : else if (pos_a == pos_b)
1273 : 0 : return 0;
1274 : 859 : return -1;
1275 : : }
1276 : :
1277 : : /*
1278 : : * Allocate & initialize an iterator which iterates in lsn order over a
1279 : : * transaction and all its subtransactions.
1280 : : *
1281 : : * Note: The iterator state is returned through iter_state parameter rather
1282 : : * than the function's return value. This is because the state gets cleaned up
1283 : : * in a PG_CATCH block in the caller, so we want to make sure the caller gets
1284 : : * back the state even if this function throws an exception.
1285 : : */
1286 : : static void
1287 : 3182 : ReorderBufferIterTXNInit(ReorderBuffer *rb, ReorderBufferTXN *txn,
1288 : : ReorderBufferIterTXNState *volatile *iter_state)
1289 : : {
1290 : 3182 : Size nr_txns = 0;
1291 : : ReorderBufferIterTXNState *state;
1292 : : dlist_iter cur_txn_i;
1293 : : Size off;
1294 : :
1295 : 3182 : *iter_state = NULL;
1296 : :
1297 : : /* Check ordering of changes in the toplevel transaction. */
1298 : 3182 : AssertChangeLsnOrder(txn);
1299 : :
1300 : : /*
1301 : : * Calculate the size of our heap: one element for every transaction that
1302 : : * contains changes. (Besides the transactions already in the reorder
1303 : : * buffer, we count the one we were directly passed.)
1304 : : */
1305 [ + + ]: 3182 : if (txn->nentries > 0)
1306 : 2990 : nr_txns++;
1307 : :
1308 [ + - + + ]: 3651 : dlist_foreach(cur_txn_i, &txn->subtxns)
1309 : : {
1310 : : ReorderBufferTXN *cur_txn;
1311 : :
1312 : 469 : cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
1313 : :
1314 : : /* Check ordering of changes in this subtransaction. */
1315 : 469 : AssertChangeLsnOrder(cur_txn);
1316 : :
1317 [ + + ]: 469 : if (cur_txn->nentries > 0)
1318 : 307 : nr_txns++;
1319 : : }
1320 : :
1321 : : /* allocate iteration state */
1322 : : state = (ReorderBufferIterTXNState *)
1323 : 3182 : MemoryContextAllocZero(rb->context,
1324 : : sizeof(ReorderBufferIterTXNState) +
1325 : 3182 : sizeof(ReorderBufferIterTXNEntry) * nr_txns);
1326 : :
1327 : 3182 : state->nr_txns = nr_txns;
1328 : 3182 : dlist_init(&state->old_change);
1329 : :
1330 [ + + ]: 6479 : for (off = 0; off < state->nr_txns; off++)
1331 : : {
1332 : 3297 : state->entries[off].file.vfd = -1;
1333 : 3297 : state->entries[off].segno = 0;
1334 : : }
1335 : :
1336 : : /* allocate heap */
1337 : 3182 : state->heap = binaryheap_allocate(state->nr_txns,
1338 : : ReorderBufferIterCompare,
1339 : : state);
1340 : :
1341 : : /* Now that the state fields are initialized, it is safe to return it. */
1342 : 3182 : *iter_state = state;
1343 : :
1344 : : /*
1345 : : * Now insert items into the binary heap, in an unordered fashion. (We
1346 : : * will run a heap assembly step at the end; this is more efficient.)
1347 : : */
1348 : :
1349 : 3182 : off = 0;
1350 : :
1351 : : /* add toplevel transaction if it contains changes */
1352 [ + + ]: 3182 : if (txn->nentries > 0)
1353 : : {
1354 : : ReorderBufferChange *cur_change;
1355 : :
1356 [ + + ]: 2990 : if (rbtxn_is_serialized(txn))
1357 : : {
1358 : : /* serialize remaining changes */
1359 : 24 : ReorderBufferSerializeTXN(rb, txn);
1360 : 24 : ReorderBufferRestoreChanges(rb, txn, &state->entries[off].file,
1361 : : &state->entries[off].segno);
1362 : : }
1363 : :
1364 : 2990 : cur_change = dlist_head_element(ReorderBufferChange, node,
1365 : : &txn->changes);
1366 : :
1367 : 2990 : state->entries[off].lsn = cur_change->lsn;
1368 : 2990 : state->entries[off].change = cur_change;
1369 : 2990 : state->entries[off].txn = txn;
1370 : :
1371 : 2990 : binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
1372 : : }
1373 : :
1374 : : /* add subtransactions if they contain changes */
1375 [ + - + + ]: 3651 : dlist_foreach(cur_txn_i, &txn->subtxns)
1376 : : {
1377 : : ReorderBufferTXN *cur_txn;
1378 : :
1379 : 469 : cur_txn = dlist_container(ReorderBufferTXN, node, cur_txn_i.cur);
1380 : :
1381 [ + + ]: 469 : if (cur_txn->nentries > 0)
1382 : : {
1383 : : ReorderBufferChange *cur_change;
1384 : :
1385 [ + + ]: 307 : if (rbtxn_is_serialized(cur_txn))
1386 : : {
1387 : : /* serialize remaining changes */
1388 : 17 : ReorderBufferSerializeTXN(rb, cur_txn);
1389 : 17 : ReorderBufferRestoreChanges(rb, cur_txn,
1390 : : &state->entries[off].file,
1391 : : &state->entries[off].segno);
1392 : : }
1393 : 307 : cur_change = dlist_head_element(ReorderBufferChange, node,
1394 : : &cur_txn->changes);
1395 : :
1396 : 307 : state->entries[off].lsn = cur_change->lsn;
1397 : 307 : state->entries[off].change = cur_change;
1398 : 307 : state->entries[off].txn = cur_txn;
1399 : :
1400 : 307 : binaryheap_add_unordered(state->heap, Int32GetDatum(off++));
1401 : : }
1402 : : }
1403 : :
1404 : : /* assemble a valid binary heap */
1405 : 3182 : binaryheap_build(state->heap);
1406 : 3182 : }
1407 : :
1408 : : /*
1409 : : * Return the next change when iterating over a transaction and its
1410 : : * subtransactions.
1411 : : *
1412 : : * Returns NULL when no further changes exist.
1413 : : */
1414 : : static ReorderBufferChange *
1415 : 395639 : ReorderBufferIterTXNNext(ReorderBuffer *rb, ReorderBufferIterTXNState *state)
1416 : : {
1417 : : ReorderBufferChange *change;
1418 : : ReorderBufferIterTXNEntry *entry;
1419 : : int32 off;
1420 : :
1421 : : /* nothing there anymore */
1422 [ + + ]: 395639 : if (binaryheap_empty(state->heap))
1423 : 3169 : return NULL;
1424 : :
1425 : 392470 : off = DatumGetInt32(binaryheap_first(state->heap));
1426 : 392470 : entry = &state->entries[off];
1427 : :
1428 : : /* free memory we might have "leaked" in the previous *Next call */
1429 [ + + ]: 392470 : if (!dlist_is_empty(&state->old_change))
1430 : : {
1431 : 45 : change = dlist_container(ReorderBufferChange, node,
1432 : : dlist_pop_head_node(&state->old_change));
1433 : 45 : ReorderBufferFreeChange(rb, change, true);
1434 : : Assert(dlist_is_empty(&state->old_change));
1435 : : }
1436 : :
1437 : 392470 : change = entry->change;
1438 : :
1439 : : /*
1440 : : * update heap with information about which transaction has the next
1441 : : * relevant change in LSN order
1442 : : */
1443 : :
1444 : : /* there are in-memory changes */
1445 [ + + ]: 392470 : if (dlist_has_next(&entry->txn->changes, &entry->change->node))
1446 : : {
1447 : 389142 : dlist_node *next = dlist_next_node(&entry->txn->changes, &change->node);
1448 : 389142 : ReorderBufferChange *next_change =
1449 : : dlist_container(ReorderBufferChange, node, next);
1450 : :
1451 : : /* txn stays the same */
1452 : 389142 : state->entries[off].lsn = next_change->lsn;
1453 : 389142 : state->entries[off].change = next_change;
1454 : :
1455 : 389142 : binaryheap_replace_first(state->heap, Int32GetDatum(off));
1456 : 389142 : return change;
1457 : : }
1458 : :
1459 : : /* try to load changes from disk */
1460 [ + + ]: 3328 : if (entry->txn->nentries != entry->txn->nentries_mem)
1461 : : {
1462 : : /*
1463 : : * Ugly: restoring changes will reuse *Change records, thus delete the
1464 : : * current one from the per-tx list and only free in the next call.
1465 : : */
1466 : 65 : dlist_delete(&change->node);
1467 : 65 : dlist_push_tail(&state->old_change, &change->node);
1468 : :
1469 : : /*
1470 : : * Update the total bytes processed by the txn for which we are
1471 : : * releasing the current set of changes and restoring the new set of
1472 : : * changes.
1473 : : */
1474 : 65 : rb->totalBytes += entry->txn->size;
1475 [ + + ]: 65 : if (ReorderBufferRestoreChanges(rb, entry->txn, &entry->file,
1476 : : &state->entries[off].segno))
1477 : : {
1478 : : /* successfully restored changes from disk */
1479 : : ReorderBufferChange *next_change =
1480 : 36 : dlist_head_element(ReorderBufferChange, node,
1481 : : &entry->txn->changes);
1482 : :
1483 [ - + ]: 36 : elog(DEBUG2, "restored %u/%u changes from disk",
1484 : : (uint32) entry->txn->nentries_mem,
1485 : : (uint32) entry->txn->nentries);
1486 : :
1487 : : Assert(entry->txn->nentries_mem);
1488 : : /* txn stays the same */
1489 : 36 : state->entries[off].lsn = next_change->lsn;
1490 : 36 : state->entries[off].change = next_change;
1491 : 36 : binaryheap_replace_first(state->heap, Int32GetDatum(off));
1492 : :
1493 : 36 : return change;
1494 : : }
1495 : : }
1496 : :
1497 : : /* ok, no changes there anymore, remove */
1498 : 3292 : binaryheap_remove_first(state->heap);
1499 : :
1500 : 3292 : return change;
1501 : : }
1502 : :
1503 : : /*
1504 : : * Deallocate the iterator
1505 : : */
1506 : : static void
1507 : 3179 : ReorderBufferIterTXNFinish(ReorderBuffer *rb,
1508 : : ReorderBufferIterTXNState *state)
1509 : : {
1510 : : Size off;
1511 : :
1512 [ + + ]: 6473 : for (off = 0; off < state->nr_txns; off++)
1513 : : {
1514 [ - + ]: 3294 : if (state->entries[off].file.vfd != -1)
1515 : 0 : FileClose(state->entries[off].file.vfd);
1516 : : }
1517 : :
1518 : : /* free memory we might have "leaked" in the last *Next call */
1519 [ + + ]: 3179 : if (!dlist_is_empty(&state->old_change))
1520 : : {
1521 : : ReorderBufferChange *change;
1522 : :
1523 : 19 : change = dlist_container(ReorderBufferChange, node,
1524 : : dlist_pop_head_node(&state->old_change));
1525 : 19 : ReorderBufferFreeChange(rb, change, true);
1526 : : Assert(dlist_is_empty(&state->old_change));
1527 : : }
1528 : :
1529 : 3179 : binaryheap_free(state->heap);
1530 : 3179 : pfree(state);
1531 : 3179 : }
1532 : :
1533 : : /*
1534 : : * Cleanup the contents of a transaction, usually after the transaction
1535 : : * committed or aborted.
1536 : : */
1537 : : static void
1538 : 5452 : ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1539 : : {
1540 : : bool found;
1541 : : dlist_mutable_iter iter;
1542 : 5452 : Size mem_freed = 0;
1543 : :
1544 : : /* cleanup subtransactions & their changes */
1545 [ + - + + ]: 5644 : dlist_foreach_modify(iter, &txn->subtxns)
1546 : : {
1547 : : ReorderBufferTXN *subtxn;
1548 : :
1549 : 192 : subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1550 : :
1551 : : /*
1552 : : * Subtransactions are always associated to the toplevel TXN, even if
1553 : : * they originally were happening inside another subtxn, so we won't
1554 : : * ever recurse more than one level deep here.
1555 : : */
1556 : : Assert(rbtxn_is_known_subxact(subtxn));
1557 : : Assert(subtxn->nsubtxns == 0);
1558 : :
1559 : 192 : ReorderBufferCleanupTXN(rb, subtxn);
1560 : : }
1561 : :
1562 : : /* cleanup changes in the txn */
1563 [ + - + + ]: 114475 : dlist_foreach_modify(iter, &txn->changes)
1564 : : {
1565 : : ReorderBufferChange *change;
1566 : :
1567 : 109023 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1568 : :
1569 : : /* Check we're not mixing changes from different transactions. */
1570 : : Assert(change->txn == txn);
1571 : :
1572 : : /*
1573 : : * Instead of updating the memory counter for individual changes, we
1574 : : * sum up the size of memory to free so we can update the memory
1575 : : * counter all together below. This saves costs of maintaining the
1576 : : * max-heap.
1577 : : */
1578 : 109023 : mem_freed += ReorderBufferChangeSize(change);
1579 : :
1580 : 109023 : ReorderBufferFreeChange(rb, change, false);
1581 : : }
1582 : :
1583 : : /* Update the memory counter */
1584 : 5452 : ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
1585 : :
1586 : : /*
1587 : : * Cleanup the tuplecids we stored for decoding catalog snapshot access.
1588 : : * They are always stored in the toplevel transaction.
1589 : : */
1590 [ + - + + ]: 36498 : dlist_foreach_modify(iter, &txn->tuplecids)
1591 : : {
1592 : : ReorderBufferChange *change;
1593 : :
1594 : 31046 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1595 : :
1596 : : /* Check we're not mixing changes from different transactions. */
1597 : : Assert(change->txn == txn);
1598 : : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1599 : :
1600 : 31046 : ReorderBufferFreeChange(rb, change, true);
1601 : : }
1602 : :
1603 : : /*
1604 : : * Cleanup the base snapshot, if set.
1605 : : */
1606 [ + + ]: 5452 : if (txn->base_snapshot != NULL)
1607 : : {
1608 : 4756 : SnapBuildSnapDecRefcount(txn->base_snapshot);
1609 : 4756 : dlist_delete(&txn->base_snapshot_node);
1610 : : }
1611 : :
1612 : : /*
1613 : : * Cleanup the snapshot for the last streamed run.
1614 : : */
1615 [ + + ]: 5452 : if (txn->snapshot_now != NULL)
1616 : : {
1617 : : Assert(rbtxn_is_streamed(txn));
1618 : 66 : ReorderBufferFreeSnap(rb, txn->snapshot_now);
1619 : : }
1620 : :
1621 : : /*
1622 : : * Remove TXN from its containing lists.
1623 : : *
1624 : : * Note: if txn is known as subxact, we are deleting the TXN from its
1625 : : * parent's list of known subxacts; this leaves the parent's nsubxacts
1626 : : * count too high, but we don't care. Otherwise, we are deleting the TXN
1627 : : * from the LSN-ordered list of toplevel TXNs. We remove the TXN from the
1628 : : * list of catalog modifying transactions as well.
1629 : : */
1630 : 5452 : dlist_delete(&txn->node);
1631 [ + + ]: 5452 : if (rbtxn_has_catalog_changes(txn))
1632 : 2128 : dclist_delete_from(&rb->catchange_txns, &txn->catchange_node);
1633 : :
1634 : : /* now remove reference from buffer */
1635 : 5452 : hash_search(rb->by_txn, &txn->xid, HASH_REMOVE, &found);
1636 : : Assert(found);
1637 : :
1638 : : /* remove entries spilled to disk */
1639 [ + + ]: 5452 : if (rbtxn_is_serialized(txn))
1640 : 284 : ReorderBufferRestoreCleanup(rb, txn);
1641 : :
1642 : : /* deallocate */
1643 : 5452 : ReorderBufferFreeTXN(rb, txn);
1644 : 5452 : }
1645 : :
1646 : : /*
1647 : : * Discard changes from a transaction (and subtransactions), either after
1648 : : * streaming, decoding them at PREPARE, or detecting the transaction abort.
1649 : : * Keep the remaining info - transactions, tuplecids, invalidations and
1650 : : * snapshots.
1651 : : *
1652 : : * We additionally remove tuplecids after decoding the transaction at prepare
1653 : : * time as we only need to perform invalidation at rollback or commit prepared.
1654 : : *
1655 : : * 'txn_prepared' indicates that we have decoded the transaction at prepare
1656 : : * time.
1657 : : */
1658 : : static void
1659 : 1082 : ReorderBufferTruncateTXN(ReorderBuffer *rb, ReorderBufferTXN *txn, bool txn_prepared)
1660 : : {
1661 : : dlist_mutable_iter iter;
1662 : 1082 : Size mem_freed = 0;
1663 : :
1664 : : /* cleanup subtransactions & their changes */
1665 [ + - + + ]: 1381 : dlist_foreach_modify(iter, &txn->subtxns)
1666 : : {
1667 : : ReorderBufferTXN *subtxn;
1668 : :
1669 : 299 : subtxn = dlist_container(ReorderBufferTXN, node, iter.cur);
1670 : :
1671 : : /*
1672 : : * Subtransactions are always associated to the toplevel TXN, even if
1673 : : * they originally were happening inside another subtxn, so we won't
1674 : : * ever recurse more than one level deep here.
1675 : : */
1676 : : Assert(rbtxn_is_known_subxact(subtxn));
1677 : : Assert(subtxn->nsubtxns == 0);
1678 : :
1679 : 299 : ReorderBufferMaybeMarkTXNStreamed(rb, subtxn);
1680 : 299 : ReorderBufferTruncateTXN(rb, subtxn, txn_prepared);
1681 : : }
1682 : :
1683 : : /* cleanup changes in the txn */
1684 [ + - + + ]: 158963 : dlist_foreach_modify(iter, &txn->changes)
1685 : : {
1686 : : ReorderBufferChange *change;
1687 : :
1688 : 157881 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1689 : :
1690 : : /* Check we're not mixing changes from different transactions. */
1691 : : Assert(change->txn == txn);
1692 : :
1693 : : /* remove the change from its containing list */
1694 : 157881 : dlist_delete(&change->node);
1695 : :
1696 : : /*
1697 : : * Instead of updating the memory counter for individual changes, we
1698 : : * sum up the size of memory to free so we can update the memory
1699 : : * counter all together below. This saves costs of maintaining the
1700 : : * max-heap.
1701 : : */
1702 : 157881 : mem_freed += ReorderBufferChangeSize(change);
1703 : :
1704 : 157881 : ReorderBufferFreeChange(rb, change, false);
1705 : : }
1706 : :
1707 : : /* Update the memory counter */
1708 : 1082 : ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, mem_freed);
1709 : :
1710 [ + + ]: 1082 : if (txn_prepared)
1711 : : {
1712 : : /*
1713 : : * If this is a prepared txn, cleanup the tuplecids we stored for
1714 : : * decoding catalog snapshot access. They are always stored in the
1715 : : * toplevel transaction.
1716 : : */
1717 [ + - + + ]: 183 : dlist_foreach_modify(iter, &txn->tuplecids)
1718 : : {
1719 : : ReorderBufferChange *change;
1720 : :
1721 : 117 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1722 : :
1723 : : /* Check we're not mixing changes from different transactions. */
1724 : : Assert(change->txn == txn);
1725 : : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1726 : :
1727 : : /* Remove the change from its containing list. */
1728 : 117 : dlist_delete(&change->node);
1729 : :
1730 : 117 : ReorderBufferFreeChange(rb, change, true);
1731 : : }
1732 : : }
1733 : :
1734 : : /*
1735 : : * Destroy the (relfilelocator, ctid) hashtable, so that we don't leak any
1736 : : * memory. We could also keep the hash table and update it with new ctid
1737 : : * values, but this seems simpler and good enough for now.
1738 : : */
1739 [ + + ]: 1082 : if (txn->tuplecid_hash != NULL)
1740 : : {
1741 : 26 : hash_destroy(txn->tuplecid_hash);
1742 : 26 : txn->tuplecid_hash = NULL;
1743 : : }
1744 : :
1745 : : /* If this txn is serialized then clean the disk space. */
1746 [ + + ]: 1082 : if (rbtxn_is_serialized(txn))
1747 : : {
1748 : 9 : ReorderBufferRestoreCleanup(rb, txn);
1749 : 9 : txn->txn_flags &= ~RBTXN_IS_SERIALIZED;
1750 : :
1751 : : /*
1752 : : * We set this flag to indicate if the transaction is ever serialized.
1753 : : * We need this to accurately update the stats as otherwise the same
1754 : : * transaction can be counted as serialized multiple times.
1755 : : */
1756 : 9 : txn->txn_flags |= RBTXN_IS_SERIALIZED_CLEAR;
1757 : : }
1758 : :
1759 : : /* also reset the number of entries in the transaction */
1760 : 1082 : txn->nentries_mem = 0;
1761 : 1082 : txn->nentries = 0;
1762 : 1082 : }
1763 : :
1764 : : /*
1765 : : * Check the transaction status by CLOG lookup and discard all changes if
1766 : : * the transaction is aborted. The transaction status is cached in
1767 : : * txn->txn_flags so we can skip future changes and avoid CLOG lookups on the
1768 : : * next call.
1769 : : *
1770 : : * Return true if the transaction is aborted, otherwise return false.
1771 : : *
1772 : : * When the 'debug_logical_replication_streaming' is set to "immediate", we
1773 : : * don't check the transaction status, meaning the caller will always process
1774 : : * this transaction.
1775 : : */
1776 : : static bool
1777 : 4339 : ReorderBufferCheckAndTruncateAbortedTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
1778 : : {
1779 : : /* Quick return for regression tests */
1780 [ + + ]: 4339 : if (unlikely(debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE))
1781 : 1110 : return false;
1782 : :
1783 : : /*
1784 : : * Quick return if the transaction status is already known.
1785 : : */
1786 : :
1787 [ + + ]: 3229 : if (rbtxn_is_committed(txn))
1788 : 2804 : return false;
1789 [ - + ]: 425 : if (rbtxn_is_aborted(txn))
1790 : : {
1791 : : /* Already-aborted transactions should not have any changes */
1792 : : Assert(txn->size == 0);
1793 : :
1794 : 0 : return true;
1795 : : }
1796 : :
1797 : : /* Otherwise, check the transaction status using CLOG lookup */
1798 : :
1799 [ + + ]: 425 : if (TransactionIdIsInProgress(txn->xid))
1800 : 222 : return false;
1801 : :
1802 [ + + ]: 203 : if (TransactionIdDidCommit(txn->xid))
1803 : : {
1804 : : /*
1805 : : * Remember the transaction is committed so that we can skip CLOG
1806 : : * check next time, avoiding the pressure on CLOG lookup.
1807 : : */
1808 : : Assert(!rbtxn_is_aborted(txn));
1809 : 191 : txn->txn_flags |= RBTXN_IS_COMMITTED;
1810 : 191 : return false;
1811 : : }
1812 : :
1813 : : /*
1814 : : * The transaction aborted. We discard both the changes collected so far
1815 : : * and the toast reconstruction data. The full cleanup will happen as part
1816 : : * of decoding ABORT record of this transaction.
1817 : : */
1818 : 12 : ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
1819 : 12 : ReorderBufferToastReset(rb, txn);
1820 : :
1821 : : /* All changes should be discarded */
1822 : : Assert(txn->size == 0);
1823 : :
1824 : : /*
1825 : : * Mark the transaction as aborted so we can ignore future changes of this
1826 : : * transaction.
1827 : : */
1828 : : Assert(!rbtxn_is_committed(txn));
1829 : 12 : txn->txn_flags |= RBTXN_IS_ABORTED;
1830 : :
1831 : 12 : return true;
1832 : : }
1833 : :
1834 : : /*
1835 : : * Build a hash with a (relfilelocator, ctid) -> (cmin, cmax) mapping for use by
1836 : : * HeapTupleSatisfiesHistoricMVCC.
1837 : : */
1838 : : static void
1839 : 3182 : ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
1840 : : {
1841 : : dlist_iter iter;
1842 : : HASHCTL hash_ctl;
1843 : :
1844 [ + + + + ]: 3182 : if (!rbtxn_has_catalog_changes(txn) || dlist_is_empty(&txn->tuplecids))
1845 : 1792 : return;
1846 : :
1847 : 1390 : hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
1848 : 1390 : hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
1849 : 1390 : hash_ctl.hcxt = rb->context;
1850 : :
1851 : : /*
1852 : : * create the hash with the exact number of to-be-stored tuplecids from
1853 : : * the start
1854 : : */
1855 : 1390 : txn->tuplecid_hash =
1856 : 1390 : hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
1857 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
1858 : :
1859 [ + - + + ]: 17749 : dlist_foreach(iter, &txn->tuplecids)
1860 : : {
1861 : : ReorderBufferTupleCidKey key;
1862 : : ReorderBufferTupleCidEnt *ent;
1863 : : bool found;
1864 : : ReorderBufferChange *change;
1865 : :
1866 : 16359 : change = dlist_container(ReorderBufferChange, node, iter.cur);
1867 : :
1868 : : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
1869 : :
1870 : : /* be careful about padding */
1871 : 16359 : memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
1872 : :
1873 : 16359 : key.rlocator = change->data.tuplecid.locator;
1874 : :
1875 : 16359 : ItemPointerCopy(&change->data.tuplecid.tid,
1876 : : &key.tid);
1877 : :
1878 : : ent = (ReorderBufferTupleCidEnt *)
1879 : 16359 : hash_search(txn->tuplecid_hash, &key, HASH_ENTER, &found);
1880 [ + + ]: 16359 : if (!found)
1881 : : {
1882 : 14713 : ent->cmin = change->data.tuplecid.cmin;
1883 : 14713 : ent->cmax = change->data.tuplecid.cmax;
1884 : 14713 : ent->combocid = change->data.tuplecid.combocid;
1885 : : }
1886 : : else
1887 : : {
1888 : : /*
1889 : : * Maybe we already saw this tuple before in this transaction, but
1890 : : * if so it must have the same cmin.
1891 : : */
1892 : : Assert(ent->cmin == change->data.tuplecid.cmin);
1893 : :
1894 : : /*
1895 : : * cmax may be initially invalid, but once set it can only grow,
1896 : : * and never become invalid again.
1897 : : */
1898 : : Assert((ent->cmax == InvalidCommandId) ||
1899 : : ((change->data.tuplecid.cmax != InvalidCommandId) &&
1900 : : (change->data.tuplecid.cmax > ent->cmax)));
1901 : 1646 : ent->cmax = change->data.tuplecid.cmax;
1902 : : }
1903 : : }
1904 : : }
1905 : :
1906 : : /*
1907 : : * Copy a provided snapshot so we can modify it privately. This is needed so
1908 : : * that catalog modifying transactions can look into intermediate catalog
1909 : : * states.
1910 : : */
1911 : : static Snapshot
1912 : 3463 : ReorderBufferCopySnap(ReorderBuffer *rb, Snapshot orig_snap,
1913 : : ReorderBufferTXN *txn, CommandId cid)
1914 : : {
1915 : : Snapshot snap;
1916 : : dlist_iter iter;
1917 : 3463 : int i = 0;
1918 : : Size size;
1919 : :
1920 : 3463 : size = sizeof(SnapshotData) +
1921 : 3463 : sizeof(TransactionId) * orig_snap->xcnt +
1922 : 3463 : sizeof(TransactionId) * (txn->nsubtxns + 1);
1923 : :
1924 : 3463 : snap = MemoryContextAllocZero(rb->context, size);
1925 : 3463 : memcpy(snap, orig_snap, sizeof(SnapshotData));
1926 : :
1927 : 3463 : snap->copied = true;
1928 : 3463 : snap->active_count = 1; /* mark as active so nobody frees it */
1929 : 3463 : snap->regd_count = 0;
1930 : 3463 : snap->xip = (TransactionId *) (snap + 1);
1931 : :
1932 : 3463 : memcpy(snap->xip, orig_snap->xip, sizeof(TransactionId) * snap->xcnt);
1933 : :
1934 : : /*
1935 : : * snap->subxip contains all txids that belong to our transaction which we
1936 : : * need to check via cmin/cmax. That's why we store the toplevel
1937 : : * transaction in there as well.
1938 : : */
1939 : 3463 : snap->subxip = snap->xip + snap->xcnt;
1940 : 3463 : snap->subxip[i++] = txn->xid;
1941 : :
1942 : : /*
1943 : : * txn->nsubtxns isn't decreased when subtransactions abort, so count
1944 : : * manually. Since it's an upper boundary it is safe to use it for the
1945 : : * allocation above.
1946 : : */
1947 : 3463 : snap->subxcnt = 1;
1948 : :
1949 [ + - + + ]: 3777 : dlist_foreach(iter, &txn->subtxns)
1950 : : {
1951 : : ReorderBufferTXN *sub_txn;
1952 : :
1953 : 314 : sub_txn = dlist_container(ReorderBufferTXN, node, iter.cur);
1954 : 314 : snap->subxip[i++] = sub_txn->xid;
1955 : 314 : snap->subxcnt++;
1956 : : }
1957 : :
1958 : : /* sort so we can bsearch() later */
1959 : 3463 : qsort(snap->subxip, snap->subxcnt, sizeof(TransactionId), xidComparator);
1960 : :
1961 : : /* store the specified current CommandId */
1962 : 3463 : snap->curcid = cid;
1963 : :
1964 : 3463 : return snap;
1965 : : }
1966 : :
1967 : : /*
1968 : : * Free a previously ReorderBufferCopySnap'ed snapshot
1969 : : */
1970 : : static void
1971 : 5539 : ReorderBufferFreeSnap(ReorderBuffer *rb, Snapshot snap)
1972 : : {
1973 [ + + ]: 5539 : if (snap->copied)
1974 : 3459 : pfree(snap);
1975 : : else
1976 : 2080 : SnapBuildSnapDecRefcount(snap);
1977 : 5539 : }
1978 : :
1979 : : /*
1980 : : * If the transaction was (partially) streamed, we need to prepare or commit
1981 : : * it in a 'streamed' way. That is, we first stream the remaining part of the
1982 : : * transaction, and then invoke stream_prepare or stream_commit message as per
1983 : : * the case.
1984 : : */
1985 : : static void
1986 : 67 : ReorderBufferStreamCommit(ReorderBuffer *rb, ReorderBufferTXN *txn)
1987 : : {
1988 : : /* we should only call this for previously streamed transactions */
1989 : : Assert(rbtxn_is_streamed(txn));
1990 : :
1991 : 67 : ReorderBufferStreamTXN(rb, txn);
1992 : :
1993 [ + + ]: 66 : if (rbtxn_is_prepared(txn))
1994 : : {
1995 : : /*
1996 : : * Note, we send stream prepare even if a concurrent abort is
1997 : : * detected. See DecodePrepare for more information.
1998 : : */
1999 : : Assert(!rbtxn_sent_prepare(txn));
2000 : 17 : rb->stream_prepare(rb, txn, txn->final_lsn);
2001 : 17 : txn->txn_flags |= RBTXN_SENT_PREPARE;
2002 : :
2003 : : /*
2004 : : * This is a PREPARED transaction, part of a two-phase commit. The
2005 : : * full cleanup will happen as part of the COMMIT PREPAREDs, so now
2006 : : * just truncate txn by removing changes and tuplecids.
2007 : : */
2008 : 17 : ReorderBufferTruncateTXN(rb, txn, true);
2009 : : /* Reset the CheckXidAlive */
2010 : 17 : CheckXidAlive = InvalidTransactionId;
2011 : : }
2012 : : else
2013 : : {
2014 : 49 : rb->stream_commit(rb, txn, txn->final_lsn);
2015 : 49 : ReorderBufferCleanupTXN(rb, txn);
2016 : : }
2017 : 66 : }
2018 : :
2019 : : /*
2020 : : * Set xid to detect concurrent aborts.
2021 : : *
2022 : : * While streaming an in-progress transaction or decoding a prepared
2023 : : * transaction there is a possibility that the (sub)transaction might get
2024 : : * aborted concurrently. In such case if the (sub)transaction has catalog
2025 : : * update then we might decode the tuple using wrong catalog version. For
2026 : : * example, suppose there is one catalog tuple with (xmin: 500, xmax: 0). Now,
2027 : : * the transaction 501 updates the catalog tuple and after that we will have
2028 : : * two tuples (xmin: 500, xmax: 501) and (xmin: 501, xmax: 0). Now, if 501 is
2029 : : * aborted and some other transaction say 502 updates the same catalog tuple
2030 : : * then the first tuple will be changed to (xmin: 500, xmax: 502). So, the
2031 : : * problem is that when we try to decode the tuple inserted/updated in 501
2032 : : * after the catalog update, we will see the catalog tuple with (xmin: 500,
2033 : : * xmax: 502) as visible because it will consider that the tuple is deleted by
2034 : : * xid 502 which is not visible to our snapshot. And when we will try to
2035 : : * decode with that catalog tuple, it can lead to a wrong result or a crash.
2036 : : * So, it is necessary to detect concurrent aborts to allow streaming of
2037 : : * in-progress transactions or decoding of prepared transactions.
2038 : : *
2039 : : * For detecting the concurrent abort we set CheckXidAlive to the current
2040 : : * (sub)transaction's xid for which this change belongs to. And, during
2041 : : * catalog scan we can check the status of the xid and if it is aborted we will
2042 : : * report a specific error so that we can stop streaming current transaction
2043 : : * and discard the already streamed changes on such an error. We might have
2044 : : * already streamed some of the changes for the aborted (sub)transaction, but
2045 : : * that is fine because when we decode the abort we will stream abort message
2046 : : * to truncate the changes in the subscriber. Similarly, for prepared
2047 : : * transactions, we stop decoding if concurrent abort is detected and then
2048 : : * rollback the changes when rollback prepared is encountered. See
2049 : : * DecodePrepare.
2050 : : */
2051 : : static inline void
2052 : 172722 : SetupCheckXidLive(TransactionId xid)
2053 : : {
2054 : : /*
2055 : : * If the input transaction id is already set as a CheckXidAlive then
2056 : : * nothing to do.
2057 : : */
2058 [ + + ]: 172722 : if (TransactionIdEquals(CheckXidAlive, xid))
2059 : 84203 : return;
2060 : :
2061 : : /*
2062 : : * setup CheckXidAlive if it's not committed yet. We don't check if the
2063 : : * xid is aborted. That will happen during catalog access.
2064 : : */
2065 [ + + ]: 88519 : if (!TransactionIdDidCommit(xid))
2066 : 360 : CheckXidAlive = xid;
2067 : : else
2068 : 88159 : CheckXidAlive = InvalidTransactionId;
2069 : : }
2070 : :
2071 : : /*
2072 : : * Helper function for ReorderBufferProcessTXN for applying change.
2073 : : */
2074 : : static inline void
2075 : 361710 : ReorderBufferApplyChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
2076 : : Relation relation, ReorderBufferChange *change,
2077 : : bool streaming)
2078 : : {
2079 [ + + ]: 361710 : if (streaming)
2080 : 170912 : rb->stream_change(rb, txn, relation, change);
2081 : : else
2082 : 190798 : rb->apply_change(rb, txn, relation, change);
2083 : 361705 : }
2084 : :
2085 : : /*
2086 : : * Helper function for ReorderBufferProcessTXN for applying the truncate.
2087 : : */
2088 : : static inline void
2089 : 29 : ReorderBufferApplyTruncate(ReorderBuffer *rb, ReorderBufferTXN *txn,
2090 : : int nrelations, Relation *relations,
2091 : : ReorderBufferChange *change, bool streaming)
2092 : : {
2093 [ - + ]: 29 : if (streaming)
2094 : 0 : rb->stream_truncate(rb, txn, nrelations, relations, change);
2095 : : else
2096 : 29 : rb->apply_truncate(rb, txn, nrelations, relations, change);
2097 : 29 : }
2098 : :
2099 : : /*
2100 : : * Helper function for ReorderBufferProcessTXN for applying the message.
2101 : : */
2102 : : static inline void
2103 : 11 : ReorderBufferApplyMessage(ReorderBuffer *rb, ReorderBufferTXN *txn,
2104 : : ReorderBufferChange *change, bool streaming)
2105 : : {
2106 [ + + ]: 11 : if (streaming)
2107 : 3 : rb->stream_message(rb, txn, change->lsn, true,
2108 : 3 : change->data.msg.prefix,
2109 : : change->data.msg.message_size,
2110 : 3 : change->data.msg.message);
2111 : : else
2112 : 8 : rb->message(rb, txn, change->lsn, true,
2113 : 8 : change->data.msg.prefix,
2114 : : change->data.msg.message_size,
2115 : 8 : change->data.msg.message);
2116 : 11 : }
2117 : :
2118 : : /*
2119 : : * Function to store the command id and snapshot at the end of the current
2120 : : * stream so that we can reuse the same while sending the next stream.
2121 : : */
2122 : : static inline void
2123 : 724 : ReorderBufferSaveTXNSnapshot(ReorderBuffer *rb, ReorderBufferTXN *txn,
2124 : : Snapshot snapshot_now, CommandId command_id)
2125 : : {
2126 : 724 : txn->command_id = command_id;
2127 : :
2128 : : /* Avoid copying if it's already copied. */
2129 [ + - ]: 724 : if (snapshot_now->copied)
2130 : 724 : txn->snapshot_now = snapshot_now;
2131 : : else
2132 : 0 : txn->snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
2133 : : txn, command_id);
2134 : 724 : }
2135 : :
2136 : : /*
2137 : : * Mark the given transaction as streamed, if appropriate.
2138 : : *
2139 : : * A top-level transaction is always marked. A subtransaction is marked
2140 : : * only when it has changes and its top-level transaction is already
2141 : : * marked as streamed.
2142 : : */
2143 : : static void
2144 : 1023 : ReorderBufferMaybeMarkTXNStreamed(ReorderBuffer *rb, ReorderBufferTXN *txn)
2145 : : {
2146 : : /*
2147 : : * The top-level transaction is marked as streamed always, even if it does
2148 : : * not contain any changes (that is, when all the changes are in
2149 : : * subtransactions). The downstream always knows about it, since we send
2150 : : * its XID in every message.
2151 : : */
2152 [ + + ]: 1023 : if (rbtxn_is_toptxn(txn))
2153 : : {
2154 : : /* We only reach here when streaming is supported. */
2155 : : Assert(ReorderBufferCanStream(rb));
2156 : 724 : txn->txn_flags |= RBTXN_IS_STREAMED;
2157 : 724 : return;
2158 : : }
2159 : :
2160 : : /*
2161 : : * A subtransaction is marked only when it has changes, and only when its
2162 : : * top-level transaction has already been marked as streamed. We never
2163 : : * stream XIDs of empty subxacts, and we must not send an abort for an XID
2164 : : * the downstream has never heard of.
2165 : : */
2166 [ + + + - : 299 : if (txn->nentries_mem != 0 && rbtxn_is_streamed(rbtxn_get_toptxn(txn)))
+ + ]
2167 : 136 : txn->txn_flags |= RBTXN_IS_STREAMED;
2168 : : }
2169 : :
2170 : : /*
2171 : : * Helper function for ReorderBufferProcessTXN to handle the concurrent
2172 : : * abort of the streaming transaction. This resets the TXN such that it
2173 : : * can be used to stream the remaining data of transaction being processed.
2174 : : * This can happen when the subtransaction is aborted and we still want to
2175 : : * continue processing the main or other subtransactions data.
2176 : : */
2177 : : static void
2178 : 8 : ReorderBufferResetTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
2179 : : Snapshot snapshot_now,
2180 : : CommandId command_id,
2181 : : XLogRecPtr last_lsn)
2182 : : {
2183 : : /* Discard the changes that we just streamed */
2184 : 8 : ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
2185 : :
2186 : : /* Free all resources allocated for toast reconstruction */
2187 : 8 : ReorderBufferToastReset(rb, txn);
2188 : :
2189 : : /*
2190 : : * For the streaming case, stop the stream and remember the command ID and
2191 : : * snapshot for the streaming run.
2192 : : */
2193 [ + - ]: 8 : if (rbtxn_is_streamed(txn))
2194 : : {
2195 : 8 : rb->stream_stop(rb, txn, last_lsn);
2196 : 8 : ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
2197 : : }
2198 : :
2199 : : /* All changes must be deallocated */
2200 : : Assert(txn->size == 0);
2201 : 8 : }
2202 : :
2203 : : /*
2204 : : * Helper function for ReorderBufferReplay and ReorderBufferStreamTXN.
2205 : : *
2206 : : * Send data of a transaction (and its subtransactions) to the
2207 : : * output plugin. We iterate over the top and subtransactions (using a k-way
2208 : : * merge) and replay the changes in lsn order.
2209 : : *
2210 : : * If streaming is true then data will be sent using stream API.
2211 : : *
2212 : : * Note: "volatile" markers on some parameters are to avoid trouble with
2213 : : * PG_TRY inside the function.
2214 : : */
2215 : : static void
2216 : 3182 : ReorderBufferProcessTXN(ReorderBuffer *rb, ReorderBufferTXN *txn,
2217 : : XLogRecPtr commit_lsn,
2218 : : volatile Snapshot snapshot_now,
2219 : : volatile CommandId command_id,
2220 : : bool streaming)
2221 : : {
2222 : : bool using_subtxn;
2223 : 3182 : MemoryContext ccxt = CurrentMemoryContext;
2224 : 3182 : ResourceOwner cowner = CurrentResourceOwner;
2225 : 3182 : ReorderBufferIterTXNState *volatile iterstate = NULL;
2226 : 3182 : volatile XLogRecPtr prev_lsn = InvalidXLogRecPtr;
2227 : 3182 : ReorderBufferChange *volatile specinsert = NULL;
2228 : 3182 : volatile bool stream_started = false;
2229 : 3182 : ReorderBufferTXN *volatile curtxn = NULL;
2230 : :
2231 : : /* build data to be able to lookup the CommandIds of catalog tuples */
2232 : 3182 : ReorderBufferBuildTupleCidHash(rb, txn);
2233 : :
2234 : : /* setup the initial snapshot */
2235 : 3182 : SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
2236 : :
2237 : : /*
2238 : : * Decoding needs access to syscaches et al., which in turn use
2239 : : * heavyweight locks and such. Thus we need to have enough state around to
2240 : : * keep track of those. The easiest way is to simply use a transaction
2241 : : * internally. That also allows us to easily enforce that nothing writes
2242 : : * to the database by checking for xid assignments.
2243 : : *
2244 : : * When we're called via the SQL SRF there's already a transaction
2245 : : * started, so start an explicit subtransaction there.
2246 : : */
2247 : 3182 : using_subtxn = IsTransactionOrTransactionBlock();
2248 : :
2249 [ + + ]: 3182 : PG_TRY();
2250 : : {
2251 : : ReorderBufferChange *change;
2252 : 3182 : int changes_count = 0; /* used to accumulate the number of
2253 : : * changes */
2254 : :
2255 [ + + ]: 3182 : if (using_subtxn)
2256 [ + + ]: 514 : BeginInternalSubTransaction(streaming ? "stream" : "replay");
2257 : : else
2258 : 2668 : StartTransactionCommand();
2259 : :
2260 : : /*
2261 : : * We only need to send begin/begin-prepare for non-streamed
2262 : : * transactions.
2263 : : */
2264 [ + + ]: 3182 : if (!streaming)
2265 : : {
2266 [ + + ]: 2457 : if (rbtxn_is_prepared(txn))
2267 : 30 : rb->begin_prepare(rb, txn);
2268 : : else
2269 : 2427 : rb->begin(rb, txn);
2270 : : }
2271 : :
2272 : 3182 : ReorderBufferIterTXNInit(rb, txn, &iterstate);
2273 [ + + ]: 398821 : while ((change = ReorderBufferIterTXNNext(rb, iterstate)) != NULL)
2274 : : {
2275 : 392470 : Relation relation = NULL;
2276 : : Oid reloid;
2277 : :
2278 [ - + ]: 392470 : CHECK_FOR_INTERRUPTS();
2279 : :
2280 : : /*
2281 : : * We can't call start stream callback before processing first
2282 : : * change.
2283 : : */
2284 [ + + ]: 392470 : if (!XLogRecPtrIsValid(prev_lsn))
2285 : : {
2286 [ + + ]: 3135 : if (streaming)
2287 : : {
2288 : 684 : txn->origin_id = change->origin_id;
2289 : 684 : rb->stream_start(rb, txn, change->lsn);
2290 : 684 : stream_started = true;
2291 : : }
2292 : : }
2293 : :
2294 : : /*
2295 : : * Enforce correct ordering of changes, merged from multiple
2296 : : * subtransactions. The changes may have the same LSN due to
2297 : : * MULTI_INSERT xlog records.
2298 : : */
2299 : : Assert(!XLogRecPtrIsValid(prev_lsn) || prev_lsn <= change->lsn);
2300 : :
2301 : 392470 : prev_lsn = change->lsn;
2302 : :
2303 : : /*
2304 : : * Set the current xid to detect concurrent aborts. This is
2305 : : * required for the cases when we decode the changes before the
2306 : : * COMMIT record is processed.
2307 : : */
2308 [ + + + + ]: 392470 : if (streaming || rbtxn_is_prepared(change->txn))
2309 : : {
2310 : 172722 : curtxn = change->txn;
2311 : 172722 : SetupCheckXidLive(curtxn->xid);
2312 : : }
2313 : :
2314 [ + + + - : 392470 : switch (change->action)
+ + + + +
- - ]
2315 : : {
2316 : 1786 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
2317 : :
2318 : : /*
2319 : : * Confirmation for speculative insertion arrived. Simply
2320 : : * use as a normal record. It'll be cleaned up at the end
2321 : : * of INSERT processing.
2322 : : */
2323 [ - + ]: 1786 : if (specinsert == NULL)
2324 [ # # ]: 0 : elog(ERROR, "invalid ordering of speculative insertion changes");
2325 : : Assert(specinsert->data.tp.oldtuple == NULL);
2326 : 1786 : change = specinsert;
2327 : 1786 : change->action = REORDER_BUFFER_CHANGE_INSERT;
2328 : :
2329 : : /* intentionally fall through */
2330 : : pg_fallthrough;
2331 : 369138 : case REORDER_BUFFER_CHANGE_INSERT:
2332 : : case REORDER_BUFFER_CHANGE_UPDATE:
2333 : : case REORDER_BUFFER_CHANGE_DELETE:
2334 : : Assert(snapshot_now);
2335 : :
2336 : 369138 : reloid = RelidByRelfilenumber(change->data.tp.rlocator.spcOid,
2337 : : change->data.tp.rlocator.relNumber);
2338 : :
2339 : : /*
2340 : : * Mapped catalog tuple without data, emitted while
2341 : : * catalog table was in the process of being rewritten. We
2342 : : * can fail to look up the relfilenumber, because the
2343 : : * relmapper has no "historic" view, in contrast to the
2344 : : * normal catalog during decoding. Thus repeated rewrites
2345 : : * can cause a lookup failure. That's OK because we do not
2346 : : * decode catalog changes anyway. Normally such tuples
2347 : : * would be skipped over below, but we can't identify
2348 : : * whether the table should be logically logged without
2349 : : * mapping the relfilenumber to the oid.
2350 : : */
2351 [ + + ]: 369130 : if (reloid == InvalidOid &&
2352 [ + - ]: 27 : change->data.tp.newtuple == NULL &&
2353 [ + - ]: 27 : change->data.tp.oldtuple == NULL)
2354 : 27 : goto change_done;
2355 [ - + ]: 369103 : else if (reloid == InvalidOid)
2356 [ # # ]: 0 : elog(ERROR, "could not map filenumber \"%s\" to relation OID",
2357 : : relpathperm(change->data.tp.rlocator,
2358 : : MAIN_FORKNUM).str);
2359 : :
2360 : 369103 : relation = RelationIdGetRelation(reloid);
2361 : :
2362 [ - + ]: 369103 : if (!RelationIsValid(relation))
2363 [ # # ]: 0 : elog(ERROR, "could not open relation with OID %u (for filenumber \"%s\")",
2364 : : reloid,
2365 : : relpathperm(change->data.tp.rlocator,
2366 : : MAIN_FORKNUM).str);
2367 : :
2368 [ + + + - : 369103 : if (!RelationIsLogicallyLogged(relation))
+ - - + -
- - - + -
+ + ]
2369 : 5067 : goto change_done;
2370 : :
2371 : : /*
2372 : : * Ignore temporary heaps created during DDL unless the
2373 : : * plugin has asked for them.
2374 : : */
2375 [ + + + + ]: 364036 : if (relation->rd_rel->relrewrite && !rb->output_rewrites)
2376 : 26 : goto change_done;
2377 : :
2378 : : /*
2379 : : * For now ignore sequence changes entirely. Most of the
2380 : : * time they don't log changes using records we
2381 : : * understand, so it doesn't make sense to handle the few
2382 : : * cases we do.
2383 : : */
2384 [ - + ]: 364010 : if (relation->rd_rel->relkind == RELKIND_SEQUENCE)
2385 : 0 : goto change_done;
2386 : :
2387 : : /* user-triggered change */
2388 [ + + ]: 364010 : if (!IsToastRelation(relation))
2389 : : {
2390 : 361710 : ReorderBufferToastReplace(rb, txn, relation, change);
2391 : 361710 : ReorderBufferApplyChange(rb, txn, relation, change,
2392 : : streaming);
2393 : :
2394 : : /*
2395 : : * Only clear reassembled toast chunks if we're sure
2396 : : * they're not required anymore. The creator of the
2397 : : * tuple tells us.
2398 : : */
2399 [ + + ]: 361705 : if (change->data.tp.clear_toast_afterwards)
2400 : 361493 : ReorderBufferToastReset(rb, txn);
2401 : : }
2402 : : /* we're not interested in toast deletions */
2403 [ + + ]: 2300 : else if (change->action == REORDER_BUFFER_CHANGE_INSERT)
2404 : : {
2405 : : /*
2406 : : * Need to reassemble the full toasted Datum in
2407 : : * memory, to ensure the chunks don't get reused till
2408 : : * we're done remove it from the list of this
2409 : : * transaction's changes. Otherwise it will get
2410 : : * freed/reused while restoring spooled data from
2411 : : * disk.
2412 : : */
2413 : : Assert(change->data.tp.newtuple != NULL);
2414 : :
2415 : 1952 : dlist_delete(&change->node);
2416 : 1952 : ReorderBufferToastAppendChunk(rb, txn, relation,
2417 : : change);
2418 : : }
2419 : :
2420 : 348 : change_done:
2421 : :
2422 : : /*
2423 : : * If speculative insertion was confirmed, the record
2424 : : * isn't needed anymore.
2425 : : */
2426 [ + + ]: 369125 : if (specinsert != NULL)
2427 : : {
2428 : 1785 : ReorderBufferFreeChange(rb, specinsert, true);
2429 : 1785 : specinsert = NULL;
2430 : : }
2431 : :
2432 [ + + ]: 369125 : if (RelationIsValid(relation))
2433 : : {
2434 : 369098 : RelationClose(relation);
2435 : 369098 : relation = NULL;
2436 : : }
2437 : 369125 : break;
2438 : :
2439 : 1786 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
2440 : :
2441 : : /*
2442 : : * Speculative insertions are dealt with by delaying the
2443 : : * processing of the insert until the confirmation record
2444 : : * arrives. For that we simply unlink the record from the
2445 : : * chain, so it does not get freed/reused while restoring
2446 : : * spooled data from disk.
2447 : : *
2448 : : * This is safe in the face of concurrent catalog changes
2449 : : * because the relevant relation can't be changed between
2450 : : * speculative insertion and confirmation due to
2451 : : * CheckTableNotInUse() and locking.
2452 : : */
2453 : :
2454 : : /* Previous speculative insertion must be aborted */
2455 : : Assert(specinsert == NULL);
2456 : :
2457 : : /* and memorize the pending insertion */
2458 : 1786 : dlist_delete(&change->node);
2459 : 1786 : specinsert = change;
2460 : 1786 : break;
2461 : :
2462 : 0 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
2463 : :
2464 : : /*
2465 : : * Abort for speculative insertion arrived. So cleanup the
2466 : : * specinsert tuple and toast hash.
2467 : : *
2468 : : * Note that we get the spec abort change for each toast
2469 : : * entry but we need to perform the cleanup only the first
2470 : : * time we get it for the main table.
2471 : : */
2472 [ # # ]: 0 : if (specinsert != NULL)
2473 : : {
2474 : : /*
2475 : : * We must clean the toast hash before processing a
2476 : : * completely new tuple to avoid confusion about the
2477 : : * previous tuple's toast chunks.
2478 : : */
2479 : : Assert(change->data.tp.clear_toast_afterwards);
2480 : 0 : ReorderBufferToastReset(rb, txn);
2481 : :
2482 : : /* We don't need this record anymore. */
2483 : 0 : ReorderBufferFreeChange(rb, specinsert, true);
2484 : 0 : specinsert = NULL;
2485 : : }
2486 : 0 : break;
2487 : :
2488 : 29 : case REORDER_BUFFER_CHANGE_TRUNCATE:
2489 : : {
2490 : : int i;
2491 : 29 : int nrelids = change->data.truncate.nrelids;
2492 : 29 : int nrelations = 0;
2493 : : Relation *relations;
2494 : :
2495 : 29 : relations = palloc0_array(Relation, nrelids);
2496 [ + + ]: 78 : for (i = 0; i < nrelids; i++)
2497 : : {
2498 : 49 : Oid relid = change->data.truncate.relids[i];
2499 : : Relation rel;
2500 : :
2501 : 49 : rel = RelationIdGetRelation(relid);
2502 : :
2503 [ - + ]: 49 : if (!RelationIsValid(rel))
2504 [ # # ]: 0 : elog(ERROR, "could not open relation with OID %u", relid);
2505 : :
2506 [ - + - - : 49 : if (!RelationIsLogicallyLogged(rel))
+ - - + -
- - - + -
- + ]
2507 : : {
2508 : 0 : RelationClose(rel);
2509 : 0 : continue;
2510 : : }
2511 : :
2512 : 49 : relations[nrelations++] = rel;
2513 : : }
2514 : :
2515 : : /* Apply the truncate. */
2516 : 29 : ReorderBufferApplyTruncate(rb, txn, nrelations,
2517 : : relations, change,
2518 : : streaming);
2519 : :
2520 [ + + ]: 78 : for (i = 0; i < nrelations; i++)
2521 : 49 : RelationClose(relations[i]);
2522 : :
2523 : 29 : break;
2524 : : }
2525 : :
2526 : 11 : case REORDER_BUFFER_CHANGE_MESSAGE:
2527 : 11 : ReorderBufferApplyMessage(rb, txn, change, streaming);
2528 : 11 : break;
2529 : :
2530 : 3808 : case REORDER_BUFFER_CHANGE_INVALIDATION:
2531 : : /* Execute the invalidation messages locally */
2532 : 3808 : ReorderBufferExecuteInvalidations(change->data.inval.ninvalidations,
2533 : : change->data.inval.invalidations);
2534 : 3808 : break;
2535 : :
2536 : 1396 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
2537 : : /* get rid of the old */
2538 : 1396 : TeardownHistoricSnapshot(false);
2539 : :
2540 [ + + ]: 1396 : if (snapshot_now->copied)
2541 : : {
2542 : 1371 : ReorderBufferFreeSnap(rb, snapshot_now);
2543 : 1371 : snapshot_now =
2544 : 1371 : ReorderBufferCopySnap(rb, change->data.snapshot,
2545 : : txn, command_id);
2546 : : }
2547 : :
2548 : : /*
2549 : : * Restored from disk, need to be careful not to double
2550 : : * free. We could introduce refcounting for that, but for
2551 : : * now this seems infrequent enough not to care.
2552 : : */
2553 [ - + ]: 25 : else if (change->data.snapshot->copied)
2554 : : {
2555 : 0 : snapshot_now =
2556 : 0 : ReorderBufferCopySnap(rb, change->data.snapshot,
2557 : : txn, command_id);
2558 : : }
2559 : : else
2560 : : {
2561 : 25 : snapshot_now = change->data.snapshot;
2562 : : }
2563 : :
2564 : : /* and continue with the new one */
2565 : 1396 : SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
2566 : 1396 : break;
2567 : :
2568 : 16302 : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
2569 : : Assert(change->data.command_id != InvalidCommandId);
2570 : :
2571 [ + + ]: 16302 : if (command_id < change->data.command_id)
2572 : : {
2573 : 3388 : command_id = change->data.command_id;
2574 : :
2575 [ + + ]: 3388 : if (!snapshot_now->copied)
2576 : : {
2577 : : /* we don't use the global one anymore */
2578 : 1367 : snapshot_now = ReorderBufferCopySnap(rb, snapshot_now,
2579 : : txn, command_id);
2580 : : }
2581 : :
2582 : 3388 : snapshot_now->curcid = command_id;
2583 : :
2584 : 3388 : TeardownHistoricSnapshot(false);
2585 : 3388 : SetupHistoricSnapshot(snapshot_now, txn->tuplecid_hash);
2586 : : }
2587 : :
2588 : 16302 : break;
2589 : :
2590 : 0 : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
2591 [ # # ]: 0 : elog(ERROR, "tuplecid value in changequeue");
2592 : : break;
2593 : : }
2594 : :
2595 : : /*
2596 : : * It is possible that the data is not sent to downstream for a
2597 : : * long time either because the output plugin filtered it or there
2598 : : * is a DDL that generates a lot of data that is not processed by
2599 : : * the plugin. So, in such cases, the downstream can timeout. To
2600 : : * avoid that we try to send a keepalive message if required.
2601 : : * Trying to send a keepalive message after every change has some
2602 : : * overhead, but testing showed there is no noticeable overhead if
2603 : : * we do it after every ~100 changes.
2604 : : */
2605 : : #define CHANGES_THRESHOLD 100
2606 : :
2607 [ + + ]: 392457 : if (++changes_count >= CHANGES_THRESHOLD)
2608 : : {
2609 : 3402 : rb->update_progress_txn(rb, txn, prev_lsn);
2610 : 3402 : changes_count = 0;
2611 : : }
2612 : : }
2613 : :
2614 : : /* speculative insertion record must be freed by now */
2615 : : Assert(!specinsert);
2616 : :
2617 : : /* clean up the iterator */
2618 : 3169 : ReorderBufferIterTXNFinish(rb, iterstate);
2619 : 3169 : iterstate = NULL;
2620 : :
2621 : : /*
2622 : : * Update total transaction count and total bytes processed by the
2623 : : * transaction and its subtransactions. Ensure to not count the
2624 : : * streamed transaction multiple times.
2625 : : *
2626 : : * Note that the statistics computation has to be done after
2627 : : * ReorderBufferIterTXNFinish as it releases the serialized change
2628 : : * which we have already accounted in ReorderBufferIterTXNNext.
2629 : : */
2630 [ + + ]: 3169 : if (!rbtxn_is_streamed(txn))
2631 : 2521 : rb->totalTxns++;
2632 : :
2633 : 3169 : rb->totalBytes += txn->total_size;
2634 : :
2635 : : /*
2636 : : * Done with current changes, send the last message for this set of
2637 : : * changes depending upon streaming mode.
2638 : : */
2639 [ + + ]: 3169 : if (streaming)
2640 : : {
2641 [ + + ]: 716 : if (stream_started)
2642 : : {
2643 : 675 : rb->stream_stop(rb, txn, prev_lsn);
2644 : 675 : stream_started = false;
2645 : : }
2646 : : }
2647 : : else
2648 : : {
2649 : : /*
2650 : : * Call either PREPARE (for two-phase transactions) or COMMIT (for
2651 : : * regular ones).
2652 : : */
2653 [ + + ]: 2453 : if (rbtxn_is_prepared(txn))
2654 : : {
2655 : : Assert(!rbtxn_sent_prepare(txn));
2656 : 30 : rb->prepare(rb, txn, commit_lsn);
2657 : 30 : txn->txn_flags |= RBTXN_SENT_PREPARE;
2658 : : }
2659 : : else
2660 : 2423 : rb->commit(rb, txn, commit_lsn);
2661 : : }
2662 : :
2663 : : /* this is just a sanity check against bad output plugin behaviour */
2664 [ - + ]: 3164 : if (GetCurrentTransactionIdIfAny() != InvalidTransactionId)
2665 [ # # ]: 0 : elog(ERROR, "output plugin used XID %u",
2666 : : GetCurrentTransactionId());
2667 : :
2668 : : /*
2669 : : * Remember the command ID and snapshot for the next set of changes in
2670 : : * streaming mode.
2671 : : */
2672 [ + + ]: 3164 : if (streaming)
2673 : 716 : ReorderBufferSaveTXNSnapshot(rb, txn, snapshot_now, command_id);
2674 [ + + ]: 2448 : else if (snapshot_now->copied)
2675 : 1367 : ReorderBufferFreeSnap(rb, snapshot_now);
2676 : :
2677 : : /* cleanup */
2678 : 3164 : TeardownHistoricSnapshot(false);
2679 : :
2680 : : /*
2681 : : * Aborting the current (sub-)transaction as a whole has the right
2682 : : * semantics. We want all locks acquired in here to be released, not
2683 : : * reassigned to the parent and we do not want any database access
2684 : : * have persistent effects.
2685 : : */
2686 : 3164 : AbortCurrentTransaction();
2687 : :
2688 : : /* make sure there's no cache pollution */
2689 [ - + ]: 3164 : if (rbtxn_distr_inval_overflowed(txn))
2690 : : {
2691 : : Assert(txn->ninvalidations_distributed == 0);
2692 : 0 : InvalidateSystemCaches();
2693 : : }
2694 : : else
2695 : : {
2696 : 3164 : ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
2697 : 3164 : ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
2698 : : txn->invalidations_distributed);
2699 : : }
2700 : :
2701 [ + + ]: 3164 : if (using_subtxn)
2702 : : {
2703 : 509 : RollbackAndReleaseCurrentSubTransaction();
2704 : 509 : MemoryContextSwitchTo(ccxt);
2705 : 509 : CurrentResourceOwner = cowner;
2706 : : }
2707 : :
2708 : : /*
2709 : : * We are here due to one of the four reasons: 1. Decoding an
2710 : : * in-progress txn. 2. Decoding a prepared txn. 3. Decoding of a
2711 : : * prepared txn that was (partially) streamed. 4. Decoding a committed
2712 : : * txn.
2713 : : *
2714 : : * For 1, we allow truncation of txn data by removing the changes
2715 : : * already streamed but still keeping other things like invalidations,
2716 : : * snapshot, and tuplecids. For 2 and 3, we indicate
2717 : : * ReorderBufferTruncateTXN to do more elaborate truncation of txn
2718 : : * data as the entire transaction has been decoded except for commit.
2719 : : * For 4, as the entire txn has been decoded, we can fully clean up
2720 : : * the TXN reorder buffer.
2721 : : */
2722 [ + + + + ]: 3164 : if (streaming || rbtxn_is_prepared(txn))
2723 : : {
2724 [ + + ]: 746 : if (streaming)
2725 : 716 : ReorderBufferMaybeMarkTXNStreamed(rb, txn);
2726 : :
2727 : 746 : ReorderBufferTruncateTXN(rb, txn, rbtxn_is_prepared(txn));
2728 : : /* Reset the CheckXidAlive */
2729 : 746 : CheckXidAlive = InvalidTransactionId;
2730 : : }
2731 : : else
2732 : 2418 : ReorderBufferCleanupTXN(rb, txn);
2733 : : }
2734 : 10 : PG_CATCH();
2735 : : {
2736 : 10 : MemoryContext ecxt = MemoryContextSwitchTo(ccxt);
2737 : 10 : ErrorData *errdata = CopyErrorData();
2738 : :
2739 : : /* TODO: Encapsulate cleanup from the PG_TRY and PG_CATCH blocks */
2740 [ + - ]: 10 : if (iterstate)
2741 : 10 : ReorderBufferIterTXNFinish(rb, iterstate);
2742 : :
2743 : 10 : TeardownHistoricSnapshot(true);
2744 : :
2745 : : /*
2746 : : * Force cache invalidation to happen outside of a valid transaction
2747 : : * to prevent catalog access as we just caught an error.
2748 : : */
2749 : 10 : AbortCurrentTransaction();
2750 : :
2751 : : /* make sure there's no cache pollution */
2752 [ - + ]: 10 : if (rbtxn_distr_inval_overflowed(txn))
2753 : : {
2754 : : Assert(txn->ninvalidations_distributed == 0);
2755 : 0 : InvalidateSystemCaches();
2756 : : }
2757 : : else
2758 : : {
2759 : 10 : ReorderBufferExecuteInvalidations(txn->ninvalidations, txn->invalidations);
2760 : 10 : ReorderBufferExecuteInvalidations(txn->ninvalidations_distributed,
2761 : : txn->invalidations_distributed);
2762 : : }
2763 : :
2764 [ + + ]: 10 : if (using_subtxn)
2765 : : {
2766 : 5 : RollbackAndReleaseCurrentSubTransaction();
2767 : 5 : MemoryContextSwitchTo(ccxt);
2768 : 5 : CurrentResourceOwner = cowner;
2769 : : }
2770 : :
2771 : : /* Free the specinsert change before freeing the ReorderBufferTXN */
2772 [ + + ]: 10 : if (specinsert != NULL)
2773 : : {
2774 : 1 : ReorderBufferFreeChange(rb, specinsert, true);
2775 : 1 : specinsert = NULL;
2776 : : }
2777 : :
2778 : : /*
2779 : : * The error code ERRCODE_TRANSACTION_ROLLBACK indicates a concurrent
2780 : : * abort of the (sub)transaction we are streaming or preparing. We
2781 : : * need to do the cleanup and return gracefully on this error, see
2782 : : * SetupCheckXidLive.
2783 : : *
2784 : : * This error code can be thrown by one of the callbacks we call
2785 : : * during decoding so we need to ensure that we return gracefully only
2786 : : * when we are sending the data in streaming mode and the streaming is
2787 : : * not finished yet or when we are sending the data out on a PREPARE
2788 : : * during a two-phase commit.
2789 : : */
2790 [ + + ]: 10 : if (errdata->sqlerrcode == ERRCODE_TRANSACTION_ROLLBACK &&
2791 [ - + - - ]: 8 : (stream_started || rbtxn_is_prepared(txn)))
2792 : : {
2793 : : /* curtxn must be set for streaming or prepared transactions */
2794 : : Assert(curtxn);
2795 : :
2796 : : /* Cleanup the temporary error state. */
2797 : 8 : FlushErrorState();
2798 : 8 : FreeErrorData(errdata);
2799 : 8 : errdata = NULL;
2800 : :
2801 : : /* Remember the transaction is aborted. */
2802 : : Assert(!rbtxn_is_committed(curtxn));
2803 : 8 : curtxn->txn_flags |= RBTXN_IS_ABORTED;
2804 : :
2805 : : /* Mark the transaction is streamed if appropriate */
2806 [ + - ]: 8 : if (stream_started)
2807 : 8 : ReorderBufferMaybeMarkTXNStreamed(rb, txn);
2808 : :
2809 : : /* Reset the TXN so that it is allowed to stream remaining data. */
2810 : 8 : ReorderBufferResetTXN(rb, txn, snapshot_now,
2811 : : command_id, prev_lsn);
2812 : : }
2813 : : else
2814 : : {
2815 : 2 : ReorderBufferCleanupTXN(rb, txn);
2816 : 2 : MemoryContextSwitchTo(ecxt);
2817 : 2 : PG_RE_THROW();
2818 : : }
2819 : : }
2820 [ - + ]: 3172 : PG_END_TRY();
2821 : 3172 : }
2822 : :
2823 : : /*
2824 : : * Perform the replay of a transaction and its non-aborted subtransactions.
2825 : : *
2826 : : * Subtransactions previously have to be processed by
2827 : : * ReorderBufferCommitChild(), even if previously assigned to the toplevel
2828 : : * transaction with ReorderBufferAssignChild.
2829 : : *
2830 : : * This interface is called once a prepare or toplevel commit is read for both
2831 : : * streamed as well as non-streamed transactions.
2832 : : */
2833 : : static void
2834 : 2531 : ReorderBufferReplay(ReorderBufferTXN *txn,
2835 : : ReorderBuffer *rb, TransactionId xid,
2836 : : XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
2837 : : TimestampTz commit_time,
2838 : : ReplOriginId origin_id, XLogRecPtr origin_lsn)
2839 : : {
2840 : : Snapshot snapshot_now;
2841 : 2531 : CommandId command_id = FirstCommandId;
2842 : :
2843 : 2531 : txn->final_lsn = commit_lsn;
2844 : 2531 : txn->end_lsn = end_lsn;
2845 : 2531 : txn->commit_time = commit_time;
2846 : 2531 : txn->origin_id = origin_id;
2847 : 2531 : txn->origin_lsn = origin_lsn;
2848 : :
2849 : : /*
2850 : : * If the transaction was (partially) streamed, we need to commit it in a
2851 : : * 'streamed' way. That is, we first stream the remaining part of the
2852 : : * transaction, and then invoke stream_commit message.
2853 : : *
2854 : : * Called after everything (origin ID, LSN, ...) is stored in the
2855 : : * transaction to avoid passing that information directly.
2856 : : */
2857 [ + + ]: 2531 : if (rbtxn_is_streamed(txn))
2858 : : {
2859 : 67 : ReorderBufferStreamCommit(rb, txn);
2860 : 66 : return;
2861 : : }
2862 : :
2863 : : /*
2864 : : * If this transaction has no snapshot, it didn't make any changes to the
2865 : : * database, so there's nothing to decode. Note that
2866 : : * ReorderBufferCommitChild will have transferred any snapshots from
2867 : : * subtransactions if there were any.
2868 : : */
2869 [ + + ]: 2464 : if (txn->base_snapshot == NULL)
2870 : : {
2871 : : Assert(txn->ninvalidations == 0);
2872 : :
2873 : : /*
2874 : : * Removing this txn before a commit might result in the computation
2875 : : * of an incorrect restart_lsn. See SnapBuildProcessRunningXacts.
2876 : : */
2877 [ + + ]: 7 : if (!rbtxn_is_prepared(txn))
2878 : 3 : ReorderBufferCleanupTXN(rb, txn);
2879 : 7 : return;
2880 : : }
2881 : :
2882 : 2457 : snapshot_now = txn->base_snapshot;
2883 : :
2884 : : /* Process and send the changes to output plugin. */
2885 : 2457 : ReorderBufferProcessTXN(rb, txn, commit_lsn, snapshot_now,
2886 : : command_id, false);
2887 : : }
2888 : :
2889 : : /*
2890 : : * Commit a transaction.
2891 : : *
2892 : : * See comments for ReorderBufferReplay().
2893 : : */
2894 : : void
2895 : 2541 : ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
2896 : : XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
2897 : : TimestampTz commit_time,
2898 : : ReplOriginId origin_id, XLogRecPtr origin_lsn)
2899 : : {
2900 : : ReorderBufferTXN *txn;
2901 : :
2902 : 2541 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2903 : : false);
2904 : :
2905 : : /* unknown transaction, nothing to replay */
2906 [ + + ]: 2541 : if (txn == NULL)
2907 : 61 : return;
2908 : :
2909 : 2480 : ReorderBufferReplay(txn, rb, xid, commit_lsn, end_lsn, commit_time,
2910 : : origin_id, origin_lsn);
2911 : : }
2912 : :
2913 : : /*
2914 : : * Record the prepare information for a transaction. Also, mark the transaction
2915 : : * as a prepared transaction.
2916 : : */
2917 : : bool
2918 : 182 : ReorderBufferRememberPrepareInfo(ReorderBuffer *rb, TransactionId xid,
2919 : : XLogRecPtr prepare_lsn, XLogRecPtr end_lsn,
2920 : : TimestampTz prepare_time,
2921 : : ReplOriginId origin_id, XLogRecPtr origin_lsn)
2922 : : {
2923 : : ReorderBufferTXN *txn;
2924 : :
2925 : 182 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
2926 : :
2927 : : /* unknown transaction, nothing to do */
2928 [ - + ]: 182 : if (txn == NULL)
2929 : 0 : return false;
2930 : :
2931 : : /*
2932 : : * Remember the prepare information to be later used by commit prepared in
2933 : : * case we skip doing prepare.
2934 : : */
2935 : 182 : txn->final_lsn = prepare_lsn;
2936 : 182 : txn->end_lsn = end_lsn;
2937 : 182 : txn->prepare_time = prepare_time;
2938 : 182 : txn->origin_id = origin_id;
2939 : 182 : txn->origin_lsn = origin_lsn;
2940 : :
2941 : : /* Mark this transaction as a prepared transaction */
2942 : : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == 0);
2943 : 182 : txn->txn_flags |= RBTXN_IS_PREPARED;
2944 : :
2945 : 182 : return true;
2946 : : }
2947 : :
2948 : : /* Remember that we have skipped prepare */
2949 : : void
2950 : 134 : ReorderBufferSkipPrepare(ReorderBuffer *rb, TransactionId xid)
2951 : : {
2952 : : ReorderBufferTXN *txn;
2953 : :
2954 : 134 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
2955 : :
2956 : : /* unknown transaction, nothing to do */
2957 [ - + ]: 134 : if (txn == NULL)
2958 : 0 : return;
2959 : :
2960 : : /* txn must have been marked as a prepared transaction */
2961 : : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == RBTXN_IS_PREPARED);
2962 : 134 : txn->txn_flags |= RBTXN_SKIPPED_PREPARE;
2963 : : }
2964 : :
2965 : : /*
2966 : : * Prepare a two-phase transaction.
2967 : : *
2968 : : * See comments for ReorderBufferReplay().
2969 : : */
2970 : : void
2971 : 48 : ReorderBufferPrepare(ReorderBuffer *rb, TransactionId xid,
2972 : : char *gid)
2973 : : {
2974 : : ReorderBufferTXN *txn;
2975 : :
2976 : 48 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
2977 : : false);
2978 : :
2979 : : /* unknown transaction, nothing to replay */
2980 [ - + ]: 48 : if (txn == NULL)
2981 : 0 : return;
2982 : :
2983 : : /*
2984 : : * txn must have been marked as a prepared transaction and must have
2985 : : * neither been skipped nor sent a prepare. Also, the prepare info must
2986 : : * have been updated in it by now.
2987 : : */
2988 : : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) == RBTXN_IS_PREPARED);
2989 : : Assert(XLogRecPtrIsValid(txn->final_lsn));
2990 : :
2991 : 48 : txn->gid = pstrdup(gid);
2992 : :
2993 : 48 : ReorderBufferReplay(txn, rb, xid, txn->final_lsn, txn->end_lsn,
2994 : 48 : txn->prepare_time, txn->origin_id, txn->origin_lsn);
2995 : :
2996 : : /*
2997 : : * Send a prepare if not already done so. The "not already sent" case can
2998 : : * occur if we have detected a concurrent abort while replaying the
2999 : : * non-streaming transaction; we still send the prepare so that later when
3000 : : * rollback prepared is decoded and sent, the downstream should be able to
3001 : : * rollback such a xact. See comments atop DecodePrepare.
3002 : : *
3003 : : * Skip this for a transaction that made no changes to the database (i.e.
3004 : : * has no base snapshot), as we haven't sent any changes for it. Such a
3005 : : * transaction is cleaned up without invoking the commit/rollback prepared
3006 : : * callbacks in ReorderBufferFinishPrepared().
3007 : : */
3008 [ + + - + ]: 48 : if (!rbtxn_sent_prepare(txn) && txn->base_snapshot != NULL)
3009 : : {
3010 : 0 : rb->prepare(rb, txn, txn->final_lsn);
3011 : 0 : txn->txn_flags |= RBTXN_SENT_PREPARE;
3012 : : }
3013 : : }
3014 : :
3015 : : /*
3016 : : * This is used to handle COMMIT/ROLLBACK PREPARED.
3017 : : */
3018 : : void
3019 : 49 : ReorderBufferFinishPrepared(ReorderBuffer *rb, TransactionId xid,
3020 : : XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
3021 : : XLogRecPtr two_phase_at,
3022 : : TimestampTz commit_time, ReplOriginId origin_id,
3023 : : XLogRecPtr origin_lsn, char *gid, bool is_commit)
3024 : : {
3025 : : ReorderBufferTXN *txn;
3026 : : XLogRecPtr prepare_end_lsn;
3027 : : TimestampTz prepare_time;
3028 : :
3029 : 49 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, commit_lsn, false);
3030 : :
3031 : : /* unknown transaction, nothing to do */
3032 [ - + ]: 49 : if (txn == NULL)
3033 : 0 : return;
3034 : :
3035 : : /*
3036 : : * By this time the txn has the prepare record information, remember it to
3037 : : * be later used for rollback.
3038 : : */
3039 : 49 : prepare_end_lsn = txn->end_lsn;
3040 : 49 : prepare_time = txn->prepare_time;
3041 : :
3042 : : /* add the gid in the txn */
3043 : 49 : txn->gid = pstrdup(gid);
3044 : :
3045 : : /*
3046 : : * It is possible that this transaction is not decoded at prepare time
3047 : : * either because by that time we didn't have a consistent snapshot, or
3048 : : * two_phase was not enabled, or it was decoded earlier but we have
3049 : : * restarted. We only need to send the prepare if it was not decoded
3050 : : * earlier. We don't need to decode the xact for aborts if it is not done
3051 : : * already.
3052 : : */
3053 [ + + + - ]: 49 : if ((txn->final_lsn < two_phase_at) && is_commit)
3054 : : {
3055 : : /*
3056 : : * txn must have been marked as a prepared transaction and skipped but
3057 : : * not sent a prepare. Also, the prepare info must have been updated
3058 : : * in txn even if we skip prepare.
3059 : : */
3060 : : Assert((txn->txn_flags & RBTXN_PREPARE_STATUS_MASK) ==
3061 : : (RBTXN_IS_PREPARED | RBTXN_SKIPPED_PREPARE));
3062 : : Assert(XLogRecPtrIsValid(txn->final_lsn));
3063 : :
3064 : : /*
3065 : : * By this time the txn has the prepare record information and it is
3066 : : * important to use that so that downstream gets the accurate
3067 : : * information. If instead, we have passed commit information here
3068 : : * then downstream can behave as it has already replayed commit
3069 : : * prepared after the restart.
3070 : : */
3071 : 3 : ReorderBufferReplay(txn, rb, xid, txn->final_lsn, txn->end_lsn,
3072 : 3 : txn->prepare_time, txn->origin_id, txn->origin_lsn);
3073 : : }
3074 : :
3075 : : /*
3076 : : * If this transaction has no snapshot, it didn't make any changes to the
3077 : : * database, so there's nothing to decode. Note that
3078 : : * ReorderBufferCommitChild will have transferred any snapshots from
3079 : : * subtransactions if there were any.
3080 : : */
3081 [ + + ]: 49 : if (txn->base_snapshot == NULL)
3082 : : {
3083 : : Assert(txn->ninvalidations == 0);
3084 : : Assert(!rbtxn_sent_prepare(txn));
3085 : :
3086 : : /*
3087 : : * Removing this txn before a commit might result in the computation
3088 : : * of an incorrect restart_lsn. See SnapBuildProcessRunningXacts.
3089 : : */
3090 : 4 : ReorderBufferCleanupTXN(rb, txn);
3091 : 4 : return;
3092 : : }
3093 : :
3094 : 45 : txn->final_lsn = commit_lsn;
3095 : 45 : txn->end_lsn = end_lsn;
3096 : 45 : txn->commit_time = commit_time;
3097 : 45 : txn->origin_id = origin_id;
3098 : 45 : txn->origin_lsn = origin_lsn;
3099 : :
3100 [ + + ]: 45 : if (is_commit)
3101 : 34 : rb->commit_prepared(rb, txn, commit_lsn);
3102 : : else
3103 : 11 : rb->rollback_prepared(rb, txn, prepare_end_lsn, prepare_time);
3104 : :
3105 : : /* cleanup: make sure there's no cache pollution */
3106 : 45 : ReorderBufferExecuteInvalidations(txn->ninvalidations,
3107 : : txn->invalidations);
3108 : 45 : ReorderBufferCleanupTXN(rb, txn);
3109 : : }
3110 : :
3111 : : /*
3112 : : * Abort a transaction that possibly has previous changes. Needs to be first
3113 : : * called for subtransactions and then for the toplevel xid.
3114 : : *
3115 : : * NB: Transactions handled here have to have actively aborted (i.e. have
3116 : : * produced an abort record). Implicitly aborted transactions are handled via
3117 : : * ReorderBufferAbortOld(); transactions we're just not interested in, but
3118 : : * which have committed are handled in ReorderBufferForget().
3119 : : *
3120 : : * This function purges this transaction and its contents from memory and
3121 : : * disk.
3122 : : */
3123 : : void
3124 : 353 : ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
3125 : : TimestampTz abort_time)
3126 : : {
3127 : : ReorderBufferTXN *txn;
3128 : :
3129 : 353 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3130 : : false);
3131 : :
3132 : : /* unknown, nothing to remove */
3133 [ + + ]: 353 : if (txn == NULL)
3134 : 3 : return;
3135 : :
3136 : 350 : txn->abort_time = abort_time;
3137 : :
3138 : : /* For streamed transactions notify the remote node about the abort. */
3139 [ + + ]: 350 : if (rbtxn_is_streamed(txn))
3140 : : {
3141 : 30 : rb->stream_abort(rb, txn, lsn);
3142 : :
3143 : : /*
3144 : : * We might have decoded changes for this transaction that could load
3145 : : * the cache as per the current transaction's view (consider DDL's
3146 : : * happened in this transaction). We don't want the decoding of future
3147 : : * transactions to use those cache entries so execute only the inval
3148 : : * messages in this transaction.
3149 : : */
3150 [ - + ]: 30 : if (txn->ninvalidations > 0)
3151 : 0 : ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
3152 : : txn->invalidations);
3153 : : }
3154 : :
3155 : : /* cosmetic... */
3156 : 350 : txn->final_lsn = lsn;
3157 : :
3158 : : /* remove potential on-disk data, and deallocate */
3159 : 350 : ReorderBufferCleanupTXN(rb, txn);
3160 : : }
3161 : :
3162 : : /*
3163 : : * Abort all transactions that aren't actually running anymore because the
3164 : : * server restarted.
3165 : : *
3166 : : * NB: These really have to be transactions that have aborted due to a server
3167 : : * crash/immediate restart, as we don't deal with invalidations here.
3168 : : */
3169 : : void
3170 : 1867 : ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid)
3171 : : {
3172 : : dlist_mutable_iter it;
3173 : :
3174 : : /*
3175 : : * Iterate through all (potential) toplevel TXNs and abort all that are
3176 : : * older than what possibly can be running. Once we've found the first
3177 : : * that is alive we stop, there might be some that acquired an xid earlier
3178 : : * but started writing later, but it's unlikely and they will be cleaned
3179 : : * up in a later call to this function.
3180 : : */
3181 [ + - + + ]: 1875 : dlist_foreach_modify(it, &rb->toplevel_by_lsn)
3182 : : {
3183 : : ReorderBufferTXN *txn;
3184 : :
3185 : 74 : txn = dlist_container(ReorderBufferTXN, node, it.cur);
3186 : :
3187 [ + + ]: 74 : if (TransactionIdPrecedes(txn->xid, oldestRunningXid))
3188 : : {
3189 [ - + ]: 8 : elog(DEBUG2, "aborting old transaction %u", txn->xid);
3190 : :
3191 : : /* Notify the remote node about the crash/immediate restart. */
3192 [ - + ]: 8 : if (rbtxn_is_streamed(txn))
3193 : 0 : rb->stream_abort(rb, txn, InvalidXLogRecPtr);
3194 : :
3195 : : /* remove potential on-disk data, and deallocate this tx */
3196 : 8 : ReorderBufferCleanupTXN(rb, txn);
3197 : : }
3198 : : else
3199 : 66 : return;
3200 : : }
3201 : : }
3202 : :
3203 : : /*
3204 : : * Forget the contents of a transaction if we aren't interested in its
3205 : : * contents. Needs to be first called for subtransactions and then for the
3206 : : * toplevel xid.
3207 : : *
3208 : : * This is significantly different to ReorderBufferAbort() because
3209 : : * transactions that have committed need to be treated differently from aborted
3210 : : * ones since they may have modified the catalog.
3211 : : *
3212 : : * Note that this is only allowed to be called in the moment a transaction
3213 : : * commit has just been read, not earlier; otherwise later records referring
3214 : : * to this xid might re-create the transaction incompletely.
3215 : : */
3216 : : void
3217 : 3022 : ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
3218 : : {
3219 : : ReorderBufferTXN *txn;
3220 : :
3221 : 3022 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3222 : : false);
3223 : :
3224 : : /* unknown, nothing to forget */
3225 [ + + ]: 3022 : if (txn == NULL)
3226 : 641 : return;
3227 : :
3228 : : /* this transaction mustn't be streamed */
3229 : : Assert(!rbtxn_is_streamed(txn));
3230 : :
3231 : : /* cosmetic... */
3232 : 2381 : txn->final_lsn = lsn;
3233 : :
3234 : : /*
3235 : : * Process only cache invalidation messages in this transaction if there
3236 : : * are any. Even if we're not interested in the transaction's contents, it
3237 : : * could have manipulated the catalog and we need to update the caches
3238 : : * according to that.
3239 : : */
3240 [ + + + + ]: 2381 : if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
3241 : 667 : ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
3242 : : txn->invalidations);
3243 : : else
3244 : : Assert(txn->ninvalidations == 0);
3245 : :
3246 : : /* remove potential on-disk data, and deallocate */
3247 : 2381 : ReorderBufferCleanupTXN(rb, txn);
3248 : : }
3249 : :
3250 : : /*
3251 : : * Remove TUPLECID changes from a top-level transaction's tuplecid list.
3252 : : *
3253 : : * 'xid' is a subtransaction being aborted, and 'subxacts' is the list of
3254 : : * its children -- which are, obviously, also being aborted.
3255 : : *
3256 : : * Unlike other types of changes, tuplecid ones are always queued on the
3257 : : * toplevel transaction (see ReorderBufferAddNewTupleCids), so we must search
3258 : : * for these changes by subxid. Because TIDs used by a catalog tuple written
3259 : : * by a subtransaction that aborts can be reused later by a future command
3260 : : * of the same transaction, we must remove these TUPLECIDs from the array,
3261 : : * otherwise the tuplecid hash of the historical snapshot would be corrupt.
3262 : : *
3263 : : * We return without cleanup if the aborting transaction is not known to this
3264 : : * reorderbuffer to be a subxact. It may still have queued TUPLECIDs onto the
3265 : : * toplevel xact, if this snapbuild missed the WAL record(s) carrying the
3266 : : * association between the two, but that should not be a problem because in
3267 : : * that case we would "skip" the transaction at DecodeCommit.
3268 : : *
3269 : : * (This cleanup is pointless when xid is a top-level transaction. That case
3270 : : * is handled instead by ReorderBufferCleanupTXN() clearing the whole list.)
3271 : : */
3272 : : void
3273 : 345 : ReorderBufferCleanupAbortedTupleCids(ReorderBuffer *rb,
3274 : : TransactionId xid,
3275 : : int nsubxacts,
3276 : : TransactionId *subxacts)
3277 : : {
3278 : : ReorderBufferTXN *txn;
3279 : : ReorderBufferTXN *toptxn;
3280 : : dlist_mutable_iter it;
3281 : :
3282 : : /*
3283 : : * Search the passed-in xids for the first known subtransaction, and use
3284 : : * it to find the toplevel transaction.
3285 : : */
3286 : 345 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr, false);
3287 [ + + + + ]: 346 : for (int i = 0; txn == NULL && i < nsubxacts; i++)
3288 : 1 : txn = ReorderBufferTXNByXid(rb, subxacts[i], false, NULL,
3289 : : InvalidXLogRecPtr, false);
3290 : :
3291 : : /*
3292 : : * Skip when nothing usable was found. No entry at all means no NEW_CID
3293 : : * record from these xids was decoded by this snapbuild, so nothing was
3294 : : * queued. In the latter case, we won't find the TUPLECIDs, but we don't
3295 : : * care. If this is a top-level xact, this cleanup is not necessary.
3296 : : */
3297 [ + + + + ]: 345 : if (txn == NULL || !rbtxn_is_known_subxact(txn))
3298 : 275 : return;
3299 : :
3300 : : /* Get the top-level transaction whose tuplecid list we're to clean */
3301 [ + - ]: 70 : toptxn = rbtxn_get_toptxn(txn);
3302 : :
3303 [ + - + + ]: 863 : dlist_foreach_modify(it, &toptxn->tuplecids)
3304 : : {
3305 : : ReorderBufferChange *change;
3306 : :
3307 : 793 : change = dlist_container(ReorderBufferChange, node, it.cur);
3308 : :
3309 : : Assert(change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
3310 : :
3311 : : /*
3312 : : * Remove the entry if it was recorded on behalf of the aborting
3313 : : * subtransaction or one of its subcommitted children. The subxact
3314 : : * array is known sorted in logical order because it comes directly
3315 : : * from the xl_xact_abort WAL record, which has them sorted that way
3316 : : * by construction (Xid assign order.)
3317 : : */
3318 [ + + + + ]: 922 : if (change->data.tuplecid.subxid == xid ||
3319 : 129 : TransactionIdInSubxactArray(change->data.tuplecid.subxid,
3320 : : subxacts, nsubxacts))
3321 : : {
3322 : 665 : dlist_delete(&change->node);
3323 : 665 : ReorderBufferFreeChange(rb, change, false);
3324 : : Assert(toptxn->ntuplecids > 0);
3325 : 665 : toptxn->ntuplecids--;
3326 : : }
3327 : : }
3328 : : }
3329 : :
3330 : : /*
3331 : : * Check whether the given xid exists in the subxacts array, which must be
3332 : : * sorted in logical order.
3333 : : */
3334 : : static bool
3335 : 129 : TransactionIdInSubxactArray(TransactionId xid, TransactionId *subxacts,
3336 : : int nsubxacts)
3337 : : {
3338 : : /* if there are no subxacts, it's not there */
3339 [ + + ]: 129 : if (nsubxacts == 0)
3340 : 128 : return false;
3341 : : /* otherwise bsearch the (logically ordered) given subxact array */
3342 : 1 : return bsearch(&xid, subxacts, nsubxacts,
3343 : 1 : sizeof(TransactionId), xidLogicalComparator) != NULL;
3344 : : }
3345 : :
3346 : : /*
3347 : : * Invalidate cache for those transactions that need to be skipped just in case
3348 : : * catalogs were manipulated as part of the transaction.
3349 : : *
3350 : : * Note that this is a special-purpose function for prepared transactions where
3351 : : * we don't want to clean up the TXN even when we decide to skip it. See
3352 : : * DecodePrepare.
3353 : : */
3354 : : void
3355 : 131 : ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
3356 : : {
3357 : : ReorderBufferTXN *txn;
3358 : :
3359 : 131 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3360 : : false);
3361 : :
3362 : : /* unknown, nothing to do */
3363 [ - + ]: 131 : if (txn == NULL)
3364 : 0 : return;
3365 : :
3366 : : /*
3367 : : * Process cache invalidation messages if there are any. Even if we're not
3368 : : * interested in the transaction's contents, it could have manipulated the
3369 : : * catalog and we need to update the caches according to that.
3370 : : */
3371 [ + + + + ]: 131 : if (txn->base_snapshot != NULL && txn->ninvalidations > 0)
3372 : 32 : ReorderBufferImmediateInvalidation(rb, txn->ninvalidations,
3373 : : txn->invalidations);
3374 : : else
3375 : : Assert(txn->ninvalidations == 0);
3376 : : }
3377 : :
3378 : :
3379 : : /*
3380 : : * Execute invalidations happening outside the context of a decoded
3381 : : * transaction. That currently happens either for xid-less commits
3382 : : * (cf. RecordTransactionCommit()) or for invalidations in uninteresting
3383 : : * transactions (via ReorderBufferForget()).
3384 : : */
3385 : : void
3386 : 747 : ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations,
3387 : : SharedInvalidationMessage *invalidations)
3388 : : {
3389 : 747 : bool use_subtxn = IsTransactionOrTransactionBlock();
3390 : 747 : MemoryContext ccxt = CurrentMemoryContext;
3391 : 747 : ResourceOwner cowner = CurrentResourceOwner;
3392 : :
3393 [ + + ]: 747 : if (use_subtxn)
3394 : 514 : BeginInternalSubTransaction("replay");
3395 : :
3396 : : /*
3397 : : * Force invalidations to happen outside of a valid transaction - that way
3398 : : * entries will just be marked as invalid without accessing the catalog.
3399 : : * That's advantageous because we don't need to setup the full state
3400 : : * necessary for catalog access.
3401 : : */
3402 [ + + ]: 747 : if (use_subtxn)
3403 : 514 : AbortCurrentTransaction();
3404 : :
3405 [ + + ]: 29944 : for (uint32 i = 0; i < ninvalidations; i++)
3406 : 29197 : LocalExecuteInvalidationMessage(&invalidations[i]);
3407 : :
3408 [ + + ]: 747 : if (use_subtxn)
3409 : : {
3410 : 514 : RollbackAndReleaseCurrentSubTransaction();
3411 : 514 : MemoryContextSwitchTo(ccxt);
3412 : 514 : CurrentResourceOwner = cowner;
3413 : : }
3414 : 747 : }
3415 : :
3416 : : /*
3417 : : * Tell reorderbuffer about an xid seen in the WAL stream. Has to be called at
3418 : : * least once for every xid in XLogRecord->xl_xid (other places in records
3419 : : * may, but do not have to be passed through here).
3420 : : *
3421 : : * Reorderbuffer keeps some data structures about transactions in LSN order,
3422 : : * for efficiency. To do that it has to know about when transactions are seen
3423 : : * first in the WAL. As many types of records are not actually interesting for
3424 : : * logical decoding, they do not necessarily pass through here.
3425 : : */
3426 : : void
3427 : 2258692 : ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
3428 : : {
3429 : : /* many records won't have an xid assigned, centralize check here */
3430 [ + + ]: 2258692 : if (xid != InvalidTransactionId)
3431 : 2255667 : ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3432 : 2258692 : }
3433 : :
3434 : : /*
3435 : : * Add a new snapshot to this transaction that may only used after lsn 'lsn'
3436 : : * because the previous snapshot doesn't describe the catalog correctly for
3437 : : * following rows.
3438 : : */
3439 : : void
3440 : 2089 : ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
3441 : : XLogRecPtr lsn, Snapshot snap)
3442 : : {
3443 : 2089 : ReorderBufferChange *change = ReorderBufferAllocChange(rb);
3444 : :
3445 : 2089 : change->data.snapshot = snap;
3446 : 2089 : change->action = REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT;
3447 : :
3448 : 2089 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
3449 : 2089 : }
3450 : :
3451 : : /*
3452 : : * Set up the transaction's base snapshot.
3453 : : *
3454 : : * If we know that xid is a subtransaction, set the base snapshot on the
3455 : : * top-level transaction instead.
3456 : : */
3457 : : void
3458 : 4830 : ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
3459 : : XLogRecPtr lsn, Snapshot snap)
3460 : : {
3461 : : ReorderBufferTXN *txn;
3462 : : bool is_new;
3463 : :
3464 : : Assert(snap != NULL);
3465 : :
3466 : : /*
3467 : : * Fetch the transaction to operate on. If we know it's a subtransaction,
3468 : : * operate on its top-level transaction instead.
3469 : : */
3470 : 4830 : txn = ReorderBufferTXNByXid(rb, xid, true, &is_new, lsn, true);
3471 [ + + ]: 4830 : if (rbtxn_is_known_subxact(txn))
3472 : 107 : txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
3473 : : NULL, InvalidXLogRecPtr, false);
3474 : : Assert(txn->base_snapshot == NULL);
3475 : :
3476 : 4830 : txn->base_snapshot = snap;
3477 : 4830 : txn->base_snapshot_lsn = lsn;
3478 : 4830 : dlist_push_tail(&rb->txns_by_base_snapshot_lsn, &txn->base_snapshot_node);
3479 : :
3480 : 4830 : AssertTXNLsnOrder(rb);
3481 : 4830 : }
3482 : :
3483 : : /*
3484 : : * Access the catalog with this CommandId at this point in the changestream.
3485 : : *
3486 : : * May only be called for command ids > 1
3487 : : */
3488 : : void
3489 : 32450 : ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
3490 : : XLogRecPtr lsn, CommandId cid)
3491 : : {
3492 : 32450 : ReorderBufferChange *change = ReorderBufferAllocChange(rb);
3493 : :
3494 : 32450 : change->data.command_id = cid;
3495 : 32450 : change->action = REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID;
3496 : :
3497 : 32450 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
3498 : 32450 : }
3499 : :
3500 : : /*
3501 : : * Update memory counters to account for the new or removed change.
3502 : : *
3503 : : * We update two counters - in the reorder buffer, and in the transaction
3504 : : * containing the change. The reorder buffer counter allows us to quickly
3505 : : * decide if we reached the memory limit, the transaction counter allows
3506 : : * us to quickly pick the largest transaction for eviction.
3507 : : *
3508 : : * Either txn or change must be non-NULL at least. We update the memory
3509 : : * counter of txn if it's non-NULL, otherwise change->txn.
3510 : : *
3511 : : * When streaming is enabled, we need to update the toplevel transaction
3512 : : * counters instead - we don't really care about subtransactions as we
3513 : : * can't stream them individually anyway, and we only pick toplevel
3514 : : * transactions for eviction. So only toplevel transactions matter.
3515 : : */
3516 : : static void
3517 : 1827292 : ReorderBufferChangeMemoryUpdate(ReorderBuffer *rb,
3518 : : ReorderBufferChange *change,
3519 : : ReorderBufferTXN *txn,
3520 : : bool addition, Size sz)
3521 : : {
3522 : : ReorderBufferTXN *toptxn;
3523 : :
3524 : : Assert(txn || change);
3525 : :
3526 : : /*
3527 : : * Ignore tuple CID changes, because those are not evicted when reaching
3528 : : * memory limit. So we just don't count them, because it might easily
3529 : : * trigger a pointless attempt to spill.
3530 : : */
3531 [ + + + + ]: 1827292 : if (change && change->action == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID)
3532 : 31163 : return;
3533 : :
3534 [ + + ]: 1796129 : if (sz == 0)
3535 : 1170 : return;
3536 : :
3537 [ + + ]: 1794959 : if (txn == NULL)
3538 : 1785723 : txn = change->txn;
3539 : : Assert(txn != NULL);
3540 : :
3541 : : /*
3542 : : * Update the total size in top level as well. This is later used to
3543 : : * compute the decoding stats.
3544 : : */
3545 [ + + ]: 1794959 : toptxn = rbtxn_get_toptxn(txn);
3546 : :
3547 [ + + ]: 1794959 : if (addition)
3548 : : {
3549 : 1607032 : Size oldsize = txn->size;
3550 : :
3551 : 1607032 : txn->size += sz;
3552 : 1607032 : rb->size += sz;
3553 : :
3554 : : /* Update the total size in the top transaction. */
3555 : 1607032 : toptxn->total_size += sz;
3556 : :
3557 : : /* Update the max-heap */
3558 [ + + ]: 1607032 : if (oldsize != 0)
3559 : 1597710 : pairingheap_remove(rb->txn_heap, &txn->txn_node);
3560 : 1607032 : pairingheap_add(rb->txn_heap, &txn->txn_node);
3561 : : }
3562 : : else
3563 : : {
3564 : : Assert((rb->size >= sz) && (txn->size >= sz));
3565 : 187927 : txn->size -= sz;
3566 : 187927 : rb->size -= sz;
3567 : :
3568 : : /* Update the total size in the top transaction. */
3569 : 187927 : toptxn->total_size -= sz;
3570 : :
3571 : : /* Update the max-heap */
3572 : 187927 : pairingheap_remove(rb->txn_heap, &txn->txn_node);
3573 [ + + ]: 187927 : if (txn->size != 0)
3574 : 178662 : pairingheap_add(rb->txn_heap, &txn->txn_node);
3575 : : }
3576 : :
3577 : : Assert(txn->size <= rb->size);
3578 : : }
3579 : :
3580 : : /*
3581 : : * Add new (relfilelocator, tid) -> (cmin, cmax) mappings.
3582 : : *
3583 : : * The xid is always the top-level xid, for easy hash construction in
3584 : : * ReorderBufferBuildTupleCidHash. We need the subxid separately for
3585 : : * cleanup during subxact aborts; see ReorderBufferCleanupAbortedTupleCids.
3586 : : *
3587 : : * We do not include this change type in memory accounting, because we
3588 : : * keep CIDs in a separate list and do not evict them when reaching
3589 : : * the memory limit.
3590 : : */
3591 : : void
3592 : 32450 : ReorderBufferAddNewTupleCids(ReorderBuffer *rb,
3593 : : TransactionId xid, TransactionId subxid,
3594 : : XLogRecPtr lsn, RelFileLocator locator,
3595 : : ItemPointerData tid,
3596 : : CommandId cmin, CommandId cmax,
3597 : : CommandId combocid)
3598 : : {
3599 : 32450 : ReorderBufferChange *change = ReorderBufferAllocChange(rb);
3600 : : ReorderBufferTXN *txn;
3601 : :
3602 : 32450 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3603 : :
3604 : 32450 : change->data.tuplecid.locator = locator;
3605 : 32450 : change->data.tuplecid.tid = tid;
3606 : 32450 : change->data.tuplecid.cmin = cmin;
3607 : 32450 : change->data.tuplecid.cmax = cmax;
3608 : 32450 : change->data.tuplecid.combocid = combocid;
3609 : 32450 : change->data.tuplecid.subxid = subxid;
3610 : 32450 : change->lsn = lsn;
3611 : 32450 : change->txn = txn;
3612 : 32450 : change->action = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
3613 : :
3614 : 32450 : dlist_push_tail(&txn->tuplecids, &change->node);
3615 : 32450 : txn->ntuplecids++;
3616 : 32450 : }
3617 : :
3618 : : /*
3619 : : * Add new invalidation messages to the reorder buffer queue.
3620 : : */
3621 : : static void
3622 : 7046 : ReorderBufferQueueInvalidations(ReorderBuffer *rb, TransactionId xid,
3623 : : XLogRecPtr lsn, Size nmsgs,
3624 : : SharedInvalidationMessage *msgs)
3625 : : {
3626 : : ReorderBufferChange *change;
3627 : :
3628 : 7046 : change = ReorderBufferAllocChange(rb);
3629 : 7046 : change->action = REORDER_BUFFER_CHANGE_INVALIDATION;
3630 : 7046 : change->data.inval.ninvalidations = nmsgs;
3631 : 7046 : change->data.inval.invalidations = palloc_array(SharedInvalidationMessage, nmsgs);
3632 : 7046 : memcpy(change->data.inval.invalidations, msgs,
3633 : : sizeof(SharedInvalidationMessage) * nmsgs);
3634 : :
3635 : 7046 : ReorderBufferQueueChange(rb, xid, lsn, change, false);
3636 : 7046 : }
3637 : :
3638 : : /*
3639 : : * A helper function for ReorderBufferAddInvalidations() and
3640 : : * ReorderBufferAddDistributedInvalidations() to accumulate the invalidation
3641 : : * messages to the **invals_out.
3642 : : */
3643 : : static void
3644 : 7046 : ReorderBufferAccumulateInvalidations(SharedInvalidationMessage **invals_out,
3645 : : uint32 *ninvals_out,
3646 : : SharedInvalidationMessage *msgs_new,
3647 : : Size nmsgs_new)
3648 : : {
3649 [ + + ]: 7046 : if (*ninvals_out == 0)
3650 : : {
3651 : 2100 : *ninvals_out = nmsgs_new;
3652 : 2100 : *invals_out = palloc_array(SharedInvalidationMessage, nmsgs_new);
3653 : 2100 : memcpy(*invals_out, msgs_new, sizeof(SharedInvalidationMessage) * nmsgs_new);
3654 : : }
3655 : : else
3656 : : {
3657 : : /* Enlarge the array of inval messages */
3658 : 4946 : *invals_out =
3659 : 4946 : repalloc_array(*invals_out, SharedInvalidationMessage,
3660 : : (*ninvals_out + nmsgs_new));
3661 : 4946 : memcpy(*invals_out + *ninvals_out, msgs_new,
3662 : : nmsgs_new * sizeof(SharedInvalidationMessage));
3663 : 4946 : *ninvals_out += nmsgs_new;
3664 : : }
3665 : 7046 : }
3666 : :
3667 : : /*
3668 : : * Accumulate the invalidations for executing them later.
3669 : : *
3670 : : * This needs to be called for each XLOG_XACT_INVALIDATIONS message and
3671 : : * accumulates all the invalidation messages in the toplevel transaction, if
3672 : : * available, otherwise in the current transaction, as well as in the form of
3673 : : * change in reorder buffer. We require to record it in form of the change
3674 : : * so that we can execute only the required invalidations instead of executing
3675 : : * all the invalidations on each CommandId increment. We also need to
3676 : : * accumulate these in the txn buffer because in some cases where we skip
3677 : : * processing the transaction (see ReorderBufferForget), we need to execute
3678 : : * all the invalidations together.
3679 : : */
3680 : : void
3681 : 7018 : ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid,
3682 : : XLogRecPtr lsn, Size nmsgs,
3683 : : SharedInvalidationMessage *msgs)
3684 : : {
3685 : : ReorderBufferTXN *txn;
3686 : : MemoryContext oldcontext;
3687 : :
3688 : 7018 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3689 : :
3690 : 7018 : oldcontext = MemoryContextSwitchTo(rb->context);
3691 : :
3692 : : /*
3693 : : * Collect all the invalidations under the top transaction, if available,
3694 : : * so that we can execute them all together. See comments atop this
3695 : : * function.
3696 : : */
3697 [ + + ]: 7018 : txn = rbtxn_get_toptxn(txn);
3698 : :
3699 : : Assert(nmsgs > 0);
3700 : :
3701 : 7018 : ReorderBufferAccumulateInvalidations(&txn->invalidations,
3702 : : &txn->ninvalidations,
3703 : : msgs, nmsgs);
3704 : :
3705 : 7018 : ReorderBufferQueueInvalidations(rb, xid, lsn, nmsgs, msgs);
3706 : :
3707 : 7018 : MemoryContextSwitchTo(oldcontext);
3708 : 7018 : }
3709 : :
3710 : : /*
3711 : : * Accumulate the invalidations distributed by other committed transactions
3712 : : * for executing them later.
3713 : : *
3714 : : * This function is similar to ReorderBufferAddInvalidations() but stores
3715 : : * the given inval messages to the txn->invalidations_distributed with the
3716 : : * overflow check.
3717 : : *
3718 : : * This needs to be called by committed transactions to distribute their
3719 : : * inval messages to in-progress transactions.
3720 : : */
3721 : : void
3722 : 28 : ReorderBufferAddDistributedInvalidations(ReorderBuffer *rb, TransactionId xid,
3723 : : XLogRecPtr lsn, Size nmsgs,
3724 : : SharedInvalidationMessage *msgs)
3725 : : {
3726 : : ReorderBufferTXN *txn;
3727 : : MemoryContext oldcontext;
3728 : :
3729 : 28 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3730 : :
3731 : 28 : oldcontext = MemoryContextSwitchTo(rb->context);
3732 : :
3733 : : /*
3734 : : * Collect all the invalidations under the top transaction, if available,
3735 : : * so that we can execute them all together. See comments
3736 : : * ReorderBufferAddInvalidations.
3737 : : */
3738 [ - + ]: 28 : txn = rbtxn_get_toptxn(txn);
3739 : :
3740 : : Assert(nmsgs > 0);
3741 : :
3742 [ + - ]: 28 : if (!rbtxn_distr_inval_overflowed(txn))
3743 : : {
3744 : : /*
3745 : : * Check the transaction has enough space for storing distributed
3746 : : * invalidation messages.
3747 : : */
3748 [ - + ]: 28 : if (txn->ninvalidations_distributed + nmsgs >= MAX_DISTR_INVAL_MSG_PER_TXN)
3749 : : {
3750 : : /*
3751 : : * Mark the invalidation message as overflowed and free up the
3752 : : * messages accumulated so far.
3753 : : */
3754 : 0 : txn->txn_flags |= RBTXN_DISTR_INVAL_OVERFLOWED;
3755 : :
3756 [ # # ]: 0 : if (txn->invalidations_distributed)
3757 : : {
3758 : 0 : pfree(txn->invalidations_distributed);
3759 : 0 : txn->invalidations_distributed = NULL;
3760 : 0 : txn->ninvalidations_distributed = 0;
3761 : : }
3762 : : }
3763 : : else
3764 : 28 : ReorderBufferAccumulateInvalidations(&txn->invalidations_distributed,
3765 : : &txn->ninvalidations_distributed,
3766 : : msgs, nmsgs);
3767 : : }
3768 : :
3769 : : /* Queue the invalidation messages into the transaction */
3770 : 28 : ReorderBufferQueueInvalidations(rb, xid, lsn, nmsgs, msgs);
3771 : :
3772 : 28 : MemoryContextSwitchTo(oldcontext);
3773 : 28 : }
3774 : :
3775 : : /*
3776 : : * Apply all invalidations we know. Possibly we only need parts at this point
3777 : : * in the changestream but we don't know which those are.
3778 : : */
3779 : : static void
3780 : 10201 : ReorderBufferExecuteInvalidations(uint32 nmsgs, SharedInvalidationMessage *msgs)
3781 : : {
3782 [ + + ]: 68892 : for (uint32 i = 0; i < nmsgs; i++)
3783 : 58691 : LocalExecuteInvalidationMessage(&msgs[i]);
3784 : 10201 : }
3785 : :
3786 : : /*
3787 : : * Mark a transaction as containing catalog changes
3788 : : */
3789 : : void
3790 : 39543 : ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid,
3791 : : XLogRecPtr lsn)
3792 : : {
3793 : : ReorderBufferTXN *txn;
3794 : :
3795 : 39543 : txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
3796 : :
3797 [ + + ]: 39543 : if (!rbtxn_has_catalog_changes(txn))
3798 : : {
3799 : 2137 : txn->txn_flags |= RBTXN_HAS_CATALOG_CHANGES;
3800 : 2137 : dclist_push_tail(&rb->catchange_txns, &txn->catchange_node);
3801 : : }
3802 : :
3803 : : /*
3804 : : * Mark top-level transaction as having catalog changes too if one of its
3805 : : * children has so that the ReorderBufferBuildTupleCidHash can
3806 : : * conveniently check just top-level transaction and decide whether to
3807 : : * build the hash table or not.
3808 : : */
3809 [ + + ]: 39543 : if (rbtxn_is_subtxn(txn))
3810 : : {
3811 [ + - ]: 1065 : ReorderBufferTXN *toptxn = rbtxn_get_toptxn(txn);
3812 : :
3813 [ + + ]: 1065 : if (!rbtxn_has_catalog_changes(toptxn))
3814 : : {
3815 : 25 : toptxn->txn_flags |= RBTXN_HAS_CATALOG_CHANGES;
3816 : 25 : dclist_push_tail(&rb->catchange_txns, &toptxn->catchange_node);
3817 : : }
3818 : : }
3819 : 39543 : }
3820 : :
3821 : : /*
3822 : : * Return palloc'ed array of the transactions that have changed catalogs.
3823 : : * The returned array is sorted in xidComparator order.
3824 : : *
3825 : : * The caller must free the returned array when done with it.
3826 : : */
3827 : : TransactionId *
3828 : 355 : ReorderBufferGetCatalogChangesXacts(ReorderBuffer *rb)
3829 : : {
3830 : : dlist_iter iter;
3831 : 355 : TransactionId *xids = NULL;
3832 : 355 : size_t xcnt = 0;
3833 : :
3834 : : /* Quick return if the list is empty */
3835 [ + + ]: 355 : if (dclist_count(&rb->catchange_txns) == 0)
3836 : 343 : return NULL;
3837 : :
3838 : : /* Initialize XID array */
3839 : 12 : xids = palloc_array(TransactionId, dclist_count(&rb->catchange_txns));
3840 [ + - + + ]: 28 : dclist_foreach(iter, &rb->catchange_txns)
3841 : : {
3842 : 16 : ReorderBufferTXN *txn = dclist_container(ReorderBufferTXN,
3843 : : catchange_node,
3844 : : iter.cur);
3845 : :
3846 : : Assert(rbtxn_has_catalog_changes(txn));
3847 : :
3848 : 16 : xids[xcnt++] = txn->xid;
3849 : : }
3850 : :
3851 : 12 : qsort(xids, xcnt, sizeof(TransactionId), xidComparator);
3852 : :
3853 : : Assert(xcnt == dclist_count(&rb->catchange_txns));
3854 : 12 : return xids;
3855 : : }
3856 : :
3857 : : /*
3858 : : * Query whether a transaction is already *known* to contain catalog
3859 : : * changes. This can be wrong until directly before the commit!
3860 : : */
3861 : : bool
3862 : 5870 : ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
3863 : : {
3864 : : ReorderBufferTXN *txn;
3865 : :
3866 : 5870 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
3867 : : false);
3868 [ + + ]: 5870 : if (txn == NULL)
3869 : 786 : return false;
3870 : :
3871 : 5084 : return rbtxn_has_catalog_changes(txn);
3872 : : }
3873 : :
3874 : : /*
3875 : : * ReorderBufferXidHasBaseSnapshot
3876 : : * Have we already set the base snapshot for the given txn/subtxn?
3877 : : */
3878 : : bool
3879 : 1420665 : ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
3880 : : {
3881 : : ReorderBufferTXN *txn;
3882 : :
3883 : 1420665 : txn = ReorderBufferTXNByXid(rb, xid, false,
3884 : : NULL, InvalidXLogRecPtr, false);
3885 : :
3886 : : /* transaction isn't known yet, ergo no snapshot */
3887 [ + + ]: 1420665 : if (txn == NULL)
3888 : 3 : return false;
3889 : :
3890 : : /* a known subtxn? operate on top-level txn instead */
3891 [ + + ]: 1420662 : if (rbtxn_is_known_subxact(txn))
3892 : 317259 : txn = ReorderBufferTXNByXid(rb, txn->toplevel_xid, false,
3893 : : NULL, InvalidXLogRecPtr, false);
3894 : :
3895 : 1420662 : return txn->base_snapshot != NULL;
3896 : : }
3897 : :
3898 : :
3899 : : /*
3900 : : * ---------------------------------------
3901 : : * Disk serialization support
3902 : : * ---------------------------------------
3903 : : */
3904 : :
3905 : : /*
3906 : : * Ensure the IO buffer is >= sz.
3907 : : */
3908 : : static void
3909 : 2617485 : ReorderBufferSerializeReserve(ReorderBuffer *rb, Size sz)
3910 : : {
3911 [ + + ]: 2617485 : if (!rb->outbufsize)
3912 : : {
3913 : 52 : rb->outbuf = MemoryContextAlloc(rb->context, sz);
3914 : 52 : rb->outbufsize = sz;
3915 : : }
3916 [ + + ]: 2617433 : else if (rb->outbufsize < sz)
3917 : : {
3918 : 269 : rb->outbuf = repalloc(rb->outbuf, sz);
3919 : 269 : rb->outbufsize = sz;
3920 : : }
3921 : 2617485 : }
3922 : :
3923 : :
3924 : : /* Compare two transactions by size */
3925 : : static int
3926 : 271887 : ReorderBufferTXNSizeCompare(const pairingheap_node *a, const pairingheap_node *b, void *arg)
3927 : : {
3928 : 271887 : const ReorderBufferTXN *ta = pairingheap_const_container(ReorderBufferTXN, txn_node, a);
3929 : 271887 : const ReorderBufferTXN *tb = pairingheap_const_container(ReorderBufferTXN, txn_node, b);
3930 : :
3931 [ + + ]: 271887 : if (ta->size < tb->size)
3932 : 158498 : return -1;
3933 [ + + ]: 113389 : if (ta->size > tb->size)
3934 : 112620 : return 1;
3935 : 769 : return 0;
3936 : : }
3937 : :
3938 : : /*
3939 : : * Find the largest transaction (toplevel or subxact) to evict (spill to disk).
3940 : : */
3941 : : static ReorderBufferTXN *
3942 : 3689 : ReorderBufferLargestTXN(ReorderBuffer *rb)
3943 : : {
3944 : : ReorderBufferTXN *largest;
3945 : :
3946 : : /* Get the largest transaction from the max-heap */
3947 : 3689 : largest = pairingheap_container(ReorderBufferTXN, txn_node,
3948 : : pairingheap_first(rb->txn_heap));
3949 : :
3950 : : Assert(largest);
3951 : : Assert(largest->size > 0);
3952 : : Assert(largest->size <= rb->size);
3953 : :
3954 : 3689 : return largest;
3955 : : }
3956 : :
3957 : : /*
3958 : : * Find the largest streamable (and non-aborted) toplevel transaction to evict
3959 : : * (by streaming).
3960 : : *
3961 : : * This can be seen as an optimized version of ReorderBufferLargestTXN, which
3962 : : * should give us the same transaction (because we don't update memory account
3963 : : * for subtransaction with streaming, so it's always 0). But we can simply
3964 : : * iterate over the limited number of toplevel transactions that have a base
3965 : : * snapshot. There is no use of selecting a transaction that doesn't have base
3966 : : * snapshot because we don't decode such transactions. Also, we do not select
3967 : : * the transaction which doesn't have any streamable change.
3968 : : *
3969 : : * Note that, we skip transactions that contain incomplete changes. There
3970 : : * is a scope of optimization here such that we can select the largest
3971 : : * transaction which has incomplete changes. But that will make the code and
3972 : : * design quite complex and that might not be worth the benefit. If we plan to
3973 : : * stream the transactions that contain incomplete changes then we need to
3974 : : * find a way to partially stream/truncate the transaction changes in-memory
3975 : : * and build a mechanism to partially truncate the spilled files.
3976 : : * Additionally, whenever we partially stream the transaction we need to
3977 : : * maintain the last streamed lsn and next time we need to restore from that
3978 : : * segment and the offset in WAL. As we stream the changes from the top
3979 : : * transaction and restore them subtransaction wise, we need to even remember
3980 : : * the subxact from where we streamed the last change.
3981 : : */
3982 : : static ReorderBufferTXN *
3983 : 850 : ReorderBufferLargestStreamableTopTXN(ReorderBuffer *rb)
3984 : : {
3985 : : dlist_iter iter;
3986 : 850 : Size largest_size = 0;
3987 : 850 : ReorderBufferTXN *largest = NULL;
3988 : :
3989 : : /* Find the largest top-level transaction having a base snapshot. */
3990 [ + - + + ]: 1831 : dlist_foreach(iter, &rb->txns_by_base_snapshot_lsn)
3991 : : {
3992 : : ReorderBufferTXN *txn;
3993 : :
3994 : 981 : txn = dlist_container(ReorderBufferTXN, base_snapshot_node, iter.cur);
3995 : :
3996 : : /* must not be a subtxn */
3997 : : Assert(!rbtxn_is_known_subxact(txn));
3998 : : /* base_snapshot must be set */
3999 : : Assert(txn->base_snapshot != NULL);
4000 : :
4001 : : /* Don't consider these kinds of transactions for eviction. */
4002 [ + + ]: 981 : if (rbtxn_has_partial_change(txn) ||
4003 [ + + ]: 830 : !rbtxn_has_streamable_change(txn) ||
4004 [ - + ]: 735 : rbtxn_is_aborted(txn))
4005 : 246 : continue;
4006 : :
4007 : : /* Find the largest of the eviction candidates. */
4008 [ + + + + ]: 735 : if ((largest == NULL || txn->total_size > largest_size) &&
4009 [ + + ]: 734 : (txn->total_size > 0))
4010 : : {
4011 : 720 : largest = txn;
4012 : 720 : largest_size = txn->total_size;
4013 : : }
4014 : : }
4015 : :
4016 : 850 : return largest;
4017 : : }
4018 : :
4019 : : /*
4020 : : * Check whether the logical_decoding_work_mem limit was reached, and if yes
4021 : : * pick the largest (sub)transaction at-a-time to evict and spill its changes to
4022 : : * disk or send to the output plugin until we reach under the memory limit.
4023 : : *
4024 : : * If debug_logical_replication_streaming is set to "immediate", stream or
4025 : : * serialize the changes immediately.
4026 : : *
4027 : : * XXX At this point we select the transactions until we reach under the memory
4028 : : * limit, but we might also adapt a more elaborate eviction strategy - for example
4029 : : * evicting enough transactions to free certain fraction (e.g. 50%) of the memory
4030 : : * limit.
4031 : : */
4032 : : static void
4033 : 1428410 : ReorderBufferCheckMemoryLimit(ReorderBuffer *rb)
4034 : : {
4035 : : ReorderBufferTXN *txn;
4036 : 1428410 : bool update_stats = true;
4037 : :
4038 [ + + ]: 1428410 : if (rb->size >= logical_decoding_work_mem * (Size) 1024)
4039 : : {
4040 : : /*
4041 : : * Update the statistics as the memory usage has reached the limit. We
4042 : : * report the statistics update later in this function since we can
4043 : : * update the slot statistics altogether while streaming or
4044 : : * serializing transactions in most cases.
4045 : : */
4046 : 3229 : rb->memExceededCount += 1;
4047 : : }
4048 [ + + ]: 1425181 : else if (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_BUFFERED)
4049 : : {
4050 : : /*
4051 : : * Bail out if debug_logical_replication_streaming is buffered and we
4052 : : * haven't exceeded the memory limit.
4053 : : */
4054 : 1424068 : return;
4055 : : }
4056 : :
4057 : : /*
4058 : : * If debug_logical_replication_streaming is immediate, loop until there's
4059 : : * no change. Otherwise, loop until we reach under the memory limit. One
4060 : : * might think that just by evicting the largest (sub)transaction we will
4061 : : * come under the memory limit based on assumption that the selected
4062 : : * transaction is at least as large as the most recent change (which
4063 : : * caused us to go over the memory limit). However, that is not true
4064 : : * because a user can reduce the logical_decoding_work_mem to a smaller
4065 : : * value before the most recent change.
4066 : : */
4067 [ + + ]: 8681 : while (rb->size >= logical_decoding_work_mem * (Size) 1024 ||
4068 [ + + ]: 5452 : (debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE &&
4069 [ + + ]: 2223 : rb->size > 0))
4070 : : {
4071 : : /*
4072 : : * Pick the largest non-aborted transaction and evict it from memory
4073 : : * by streaming, if possible. Otherwise, spill to disk.
4074 : : */
4075 [ + + + + ]: 5189 : if (ReorderBufferCanStartStreaming(rb) &&
4076 : 850 : (txn = ReorderBufferLargestStreamableTopTXN(rb)) != NULL)
4077 : : {
4078 : : /* we know there has to be one, because the size is not zero */
4079 : : Assert(txn && rbtxn_is_toptxn(txn));
4080 : : Assert(txn->total_size > 0);
4081 : : Assert(rb->size >= txn->total_size);
4082 : :
4083 : : /* skip the transaction if aborted */
4084 [ - + ]: 650 : if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
4085 : 0 : continue;
4086 : :
4087 : 650 : ReorderBufferStreamTXN(rb, txn);
4088 : : }
4089 : : else
4090 : : {
4091 : : /*
4092 : : * Pick the largest transaction (or subtransaction) and evict it
4093 : : * from memory by serializing it to disk.
4094 : : */
4095 : 3689 : txn = ReorderBufferLargestTXN(rb);
4096 : :
4097 : : /* we know there has to be one, because the size is not zero */
4098 : : Assert(txn);
4099 : : Assert(txn->size > 0);
4100 : : Assert(rb->size >= txn->size);
4101 : :
4102 : : /* skip the transaction if aborted */
4103 [ + + ]: 3689 : if (ReorderBufferCheckAndTruncateAbortedTXN(rb, txn))
4104 : 12 : continue;
4105 : :
4106 : 3677 : ReorderBufferSerializeTXN(rb, txn);
4107 : : }
4108 : :
4109 : : /*
4110 : : * After eviction, the transaction should have no entries in memory,
4111 : : * and should use 0 bytes for changes.
4112 : : */
4113 : : Assert(txn->size == 0);
4114 : : Assert(txn->nentries_mem == 0);
4115 : :
4116 : : /*
4117 : : * We've reported the memExceededCount update while streaming or
4118 : : * serializing the transaction.
4119 : : */
4120 : 4327 : update_stats = false;
4121 : : }
4122 : :
4123 [ + + ]: 4342 : if (update_stats)
4124 : 15 : UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
4125 : :
4126 : : /* We must be under the memory limit now. */
4127 : : Assert(rb->size < logical_decoding_work_mem * (Size) 1024);
4128 : : }
4129 : :
4130 : : /*
4131 : : * Spill data of a large transaction (and its subtransactions) to disk.
4132 : : */
4133 : : static void
4134 : 3872 : ReorderBufferSerializeTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
4135 : : {
4136 : : dlist_iter subtxn_i;
4137 : : dlist_mutable_iter change_i;
4138 : 3872 : int fd = -1;
4139 : 3872 : XLogSegNo curOpenSegNo = 0;
4140 : 3872 : Size spilled = 0;
4141 : 3872 : Size size = txn->size;
4142 : :
4143 [ - + ]: 3872 : elog(DEBUG2, "spill %u changes in XID %u to disk",
4144 : : (uint32) txn->nentries_mem, txn->xid);
4145 : :
4146 : : /* do the same to all child TXs */
4147 [ + - + + ]: 4026 : dlist_foreach(subtxn_i, &txn->subtxns)
4148 : : {
4149 : : ReorderBufferTXN *subtxn;
4150 : :
4151 : 154 : subtxn = dlist_container(ReorderBufferTXN, node, subtxn_i.cur);
4152 : 154 : ReorderBufferSerializeTXN(rb, subtxn);
4153 : : }
4154 : :
4155 : : /* serialize changestream */
4156 [ + - + + ]: 1144227 : dlist_foreach_modify(change_i, &txn->changes)
4157 : : {
4158 : : ReorderBufferChange *change;
4159 : :
4160 : 1140355 : change = dlist_container(ReorderBufferChange, node, change_i.cur);
4161 : :
4162 : : /*
4163 : : * store in segment in which it belongs by start lsn, don't split over
4164 : : * multiple segments tho
4165 : : */
4166 [ + + ]: 1140355 : if (fd == -1 ||
4167 [ + + ]: 1136640 : !XLByteInSeg(change->lsn, curOpenSegNo, wal_segment_size))
4168 : : {
4169 : : char path[MAXPGPATH];
4170 : :
4171 [ + + ]: 3719 : if (fd != -1)
4172 : 4 : CloseTransientFile(fd);
4173 : :
4174 : 3719 : XLByteToSeg(change->lsn, curOpenSegNo, wal_segment_size);
4175 : :
4176 : : /*
4177 : : * No need to care about TLIs here, only used during a single run,
4178 : : * so each LSN only maps to a specific WAL record.
4179 : : */
4180 : 3719 : ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
4181 : : curOpenSegNo);
4182 : :
4183 : : /* open segment, create it if necessary */
4184 : 3719 : fd = OpenTransientFile(path,
4185 : : O_CREAT | O_WRONLY | O_APPEND | PG_BINARY);
4186 : :
4187 [ - + ]: 3719 : if (fd < 0)
4188 [ # # ]: 0 : ereport(ERROR,
4189 : : (errcode_for_file_access(),
4190 : : errmsg("could not open file \"%s\": %m", path)));
4191 : : }
4192 : :
4193 : 1140355 : ReorderBufferSerializeChange(rb, txn, fd, change);
4194 : 1140355 : dlist_delete(&change->node);
4195 : 1140355 : ReorderBufferFreeChange(rb, change, false);
4196 : :
4197 : 1140355 : spilled++;
4198 : : }
4199 : :
4200 : : /* Update the memory counter */
4201 : 3872 : ReorderBufferChangeMemoryUpdate(rb, NULL, txn, false, size);
4202 : :
4203 : : /* update the statistics iff we have spilled anything */
4204 [ + + ]: 3872 : if (spilled)
4205 : : {
4206 : 3715 : rb->spillCount += 1;
4207 : 3715 : rb->spillBytes += size;
4208 : :
4209 : : /* don't consider already serialized transactions */
4210 [ + + + - ]: 3715 : rb->spillTxns += (rbtxn_is_serialized(txn) || rbtxn_is_serialized_clear(txn)) ? 0 : 1;
4211 : :
4212 : : /* update the decoding stats */
4213 : 3715 : UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
4214 : : }
4215 : :
4216 : : Assert(spilled == txn->nentries_mem);
4217 : : Assert(dlist_is_empty(&txn->changes));
4218 : 3872 : txn->nentries_mem = 0;
4219 : 3872 : txn->txn_flags |= RBTXN_IS_SERIALIZED;
4220 : :
4221 [ + + ]: 3872 : if (fd != -1)
4222 : 3715 : CloseTransientFile(fd);
4223 : 3872 : }
4224 : :
4225 : : /*
4226 : : * Serialize individual change to disk.
4227 : : */
4228 : : static void
4229 : 1140355 : ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
4230 : : int fd, ReorderBufferChange *change)
4231 : : {
4232 : : ReorderBufferDiskChange *ondisk;
4233 : 1140355 : Size sz = sizeof(ReorderBufferDiskChange);
4234 : :
4235 : 1140355 : ReorderBufferSerializeReserve(rb, sz);
4236 : :
4237 : 1140355 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4238 : 1140355 : memcpy(&ondisk->change, change, sizeof(ReorderBufferChange));
4239 : :
4240 [ + + + + : 1140355 : switch (change->action)
+ + - ]
4241 : : {
4242 : : /* fall through these, they're all similar enough */
4243 : 1120200 : case REORDER_BUFFER_CHANGE_INSERT:
4244 : : case REORDER_BUFFER_CHANGE_UPDATE:
4245 : : case REORDER_BUFFER_CHANGE_DELETE:
4246 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
4247 : : {
4248 : : char *data;
4249 : : HeapTuple oldtup,
4250 : : newtup;
4251 : 1120200 : Size oldlen = 0;
4252 : 1120200 : Size newlen = 0;
4253 : :
4254 : 1120200 : oldtup = change->data.tp.oldtuple;
4255 : 1120200 : newtup = change->data.tp.newtuple;
4256 : :
4257 [ + + ]: 1120200 : if (oldtup)
4258 : : {
4259 : 134125 : sz += sizeof(HeapTupleData);
4260 : 134125 : oldlen = oldtup->t_len;
4261 : 134125 : sz += oldlen;
4262 : : }
4263 : :
4264 [ + + ]: 1120200 : if (newtup)
4265 : : {
4266 : 929147 : sz += sizeof(HeapTupleData);
4267 : 929147 : newlen = newtup->t_len;
4268 : 929147 : sz += newlen;
4269 : : }
4270 : :
4271 : : /* make sure we have enough space */
4272 : 1120200 : ReorderBufferSerializeReserve(rb, sz);
4273 : :
4274 : 1120200 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4275 : : /* might have been reallocated above */
4276 : 1120200 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4277 : :
4278 [ + + ]: 1120200 : if (oldlen)
4279 : : {
4280 : 134125 : memcpy(data, oldtup, sizeof(HeapTupleData));
4281 : 134125 : data += sizeof(HeapTupleData);
4282 : :
4283 : 134125 : memcpy(data, oldtup->t_data, oldlen);
4284 : 134125 : data += oldlen;
4285 : : }
4286 : :
4287 [ + + ]: 1120200 : if (newlen)
4288 : : {
4289 : 929147 : memcpy(data, newtup, sizeof(HeapTupleData));
4290 : 929147 : data += sizeof(HeapTupleData);
4291 : :
4292 : 929147 : memcpy(data, newtup->t_data, newlen);
4293 : 929147 : data += newlen;
4294 : : }
4295 : 1120200 : break;
4296 : : }
4297 : 14 : case REORDER_BUFFER_CHANGE_MESSAGE:
4298 : : {
4299 : : char *data;
4300 : 14 : Size prefix_size = strlen(change->data.msg.prefix) + 1;
4301 : :
4302 : 14 : sz += prefix_size + change->data.msg.message_size +
4303 : : sizeof(Size) + sizeof(Size);
4304 : 14 : ReorderBufferSerializeReserve(rb, sz);
4305 : :
4306 : 14 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4307 : :
4308 : : /* might have been reallocated above */
4309 : 14 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4310 : :
4311 : : /* write the prefix including the size */
4312 : 14 : memcpy(data, &prefix_size, sizeof(Size));
4313 : 14 : data += sizeof(Size);
4314 : 14 : memcpy(data, change->data.msg.prefix,
4315 : : prefix_size);
4316 : 14 : data += prefix_size;
4317 : :
4318 : : /* write the message including the size */
4319 : 14 : memcpy(data, &change->data.msg.message_size, sizeof(Size));
4320 : 14 : data += sizeof(Size);
4321 : 14 : memcpy(data, change->data.msg.message,
4322 : : change->data.msg.message_size);
4323 : 14 : data += change->data.msg.message_size;
4324 : :
4325 : 14 : break;
4326 : : }
4327 : 169 : case REORDER_BUFFER_CHANGE_INVALIDATION:
4328 : : {
4329 : : char *data;
4330 : 169 : Size inval_size = sizeof(SharedInvalidationMessage) *
4331 : 169 : change->data.inval.ninvalidations;
4332 : :
4333 : 169 : sz += inval_size;
4334 : :
4335 : 169 : ReorderBufferSerializeReserve(rb, sz);
4336 : 169 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4337 : :
4338 : : /* might have been reallocated above */
4339 : 169 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4340 : 169 : memcpy(data, change->data.inval.invalidations, inval_size);
4341 : 169 : data += inval_size;
4342 : :
4343 : 169 : break;
4344 : : }
4345 : 8 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
4346 : : {
4347 : : Snapshot snap;
4348 : : char *data;
4349 : :
4350 : 8 : snap = change->data.snapshot;
4351 : :
4352 : 8 : sz += sizeof(SnapshotData) +
4353 : 8 : sizeof(TransactionId) * snap->xcnt +
4354 : 8 : sizeof(TransactionId) * snap->subxcnt;
4355 : :
4356 : : /* make sure we have enough space */
4357 : 8 : ReorderBufferSerializeReserve(rb, sz);
4358 : 8 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4359 : : /* might have been reallocated above */
4360 : 8 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4361 : :
4362 : 8 : memcpy(data, snap, sizeof(SnapshotData));
4363 : 8 : data += sizeof(SnapshotData);
4364 : :
4365 [ + - ]: 8 : if (snap->xcnt)
4366 : : {
4367 : 8 : memcpy(data, snap->xip,
4368 : 8 : sizeof(TransactionId) * snap->xcnt);
4369 : 8 : data += sizeof(TransactionId) * snap->xcnt;
4370 : : }
4371 : :
4372 [ - + ]: 8 : if (snap->subxcnt)
4373 : : {
4374 : 0 : memcpy(data, snap->subxip,
4375 : 0 : sizeof(TransactionId) * snap->subxcnt);
4376 : 0 : data += sizeof(TransactionId) * snap->subxcnt;
4377 : : }
4378 : 8 : break;
4379 : : }
4380 : 2 : case REORDER_BUFFER_CHANGE_TRUNCATE:
4381 : : {
4382 : : Size size;
4383 : : char *data;
4384 : :
4385 : : /* account for the OIDs of truncated relations */
4386 : 2 : size = sizeof(Oid) * change->data.truncate.nrelids;
4387 : 2 : sz += size;
4388 : :
4389 : : /* make sure we have enough space */
4390 : 2 : ReorderBufferSerializeReserve(rb, sz);
4391 : :
4392 : 2 : data = ((char *) rb->outbuf) + sizeof(ReorderBufferDiskChange);
4393 : : /* might have been reallocated above */
4394 : 2 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4395 : :
4396 : 2 : memcpy(data, change->data.truncate.relids, size);
4397 : 2 : data += size;
4398 : :
4399 : 2 : break;
4400 : : }
4401 : 19962 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
4402 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
4403 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
4404 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
4405 : : /* ReorderBufferChange contains everything important */
4406 : 19962 : break;
4407 : : }
4408 : :
4409 : 1140355 : ondisk->size = sz;
4410 : :
4411 : 1140355 : errno = 0;
4412 : 1140355 : pgstat_report_wait_start(WAIT_EVENT_REORDER_BUFFER_WRITE);
4413 [ - + ]: 1140355 : if (write(fd, rb->outbuf, ondisk->size) != ondisk->size)
4414 : : {
4415 : 0 : int save_errno = errno;
4416 : :
4417 : 0 : CloseTransientFile(fd);
4418 : :
4419 : : /* if write didn't set errno, assume problem is no disk space */
4420 [ # # ]: 0 : errno = save_errno ? save_errno : ENOSPC;
4421 [ # # ]: 0 : ereport(ERROR,
4422 : : (errcode_for_file_access(),
4423 : : errmsg("could not write to data file for XID %u: %m",
4424 : : txn->xid)));
4425 : : }
4426 : 1140355 : pgstat_report_wait_end();
4427 : :
4428 : : /*
4429 : : * Keep the transaction's final_lsn up to date with each change we send to
4430 : : * disk, so that ReorderBufferRestoreCleanup works correctly. (We used to
4431 : : * only do this on commit and abort records, but that doesn't work if a
4432 : : * system crash leaves a transaction without its abort record).
4433 : : *
4434 : : * Make sure not to move it backwards.
4435 : : */
4436 [ + + ]: 1140355 : if (txn->final_lsn < change->lsn)
4437 : 1135456 : txn->final_lsn = change->lsn;
4438 : :
4439 : : Assert(ondisk->change.action == change->action);
4440 : 1140355 : }
4441 : :
4442 : : /* Returns true, if the output plugin supports streaming, false, otherwise. */
4443 : : static inline bool
4444 : 1899855 : ReorderBufferCanStream(ReorderBuffer *rb)
4445 : : {
4446 : 1899855 : LogicalDecodingContext *ctx = rb->private_data;
4447 : :
4448 : 1899855 : return ctx->streaming;
4449 : : }
4450 : :
4451 : : /* Returns true, if the streaming can be started now, false, otherwise. */
4452 : : static inline bool
4453 : 471445 : ReorderBufferCanStartStreaming(ReorderBuffer *rb)
4454 : : {
4455 : 471445 : LogicalDecodingContext *ctx = rb->private_data;
4456 : 471445 : SnapBuild *builder = ctx->snapshot_builder;
4457 : :
4458 : : /* We can't start streaming unless a consistent state is reached. */
4459 [ - + ]: 471445 : if (SnapBuildCurrentState(builder) < SNAPBUILD_CONSISTENT)
4460 : 0 : return false;
4461 : :
4462 : : /*
4463 : : * We can't start streaming immediately even if the streaming is enabled
4464 : : * because we previously decoded this transaction and now just are
4465 : : * restarting.
4466 : : */
4467 [ + + ]: 471445 : if (ReorderBufferCanStream(rb) &&
4468 [ + + ]: 469311 : !SnapBuildXactNeedsSkip(builder, ctx->reader->ReadRecPtr))
4469 : 210858 : return true;
4470 : :
4471 : 260587 : return false;
4472 : : }
4473 : :
4474 : : /*
4475 : : * Send data of a large transaction (and its subtransactions) to the
4476 : : * output plugin, but using the stream API.
4477 : : */
4478 : : static void
4479 : 725 : ReorderBufferStreamTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
4480 : : {
4481 : : Snapshot snapshot_now;
4482 : : CommandId command_id;
4483 : : Size stream_bytes;
4484 : : bool txn_is_streamed;
4485 : :
4486 : : /* We can never reach here for a subtransaction. */
4487 : : Assert(rbtxn_is_toptxn(txn));
4488 : :
4489 : : /*
4490 : : * We can't make any assumptions about base snapshot here, similar to what
4491 : : * ReorderBufferCommit() does. That relies on base_snapshot getting
4492 : : * transferred from subxact in ReorderBufferCommitChild(), but that was
4493 : : * not yet called as the transaction is in-progress.
4494 : : *
4495 : : * So just walk the subxacts and use the same logic here. But we only need
4496 : : * to do that once, when the transaction is streamed for the first time.
4497 : : * After that we need to reuse the snapshot from the previous run.
4498 : : *
4499 : : * Unlike DecodeCommit which adds xids of all the subtransactions in
4500 : : * snapshot's xip array via SnapBuildCommitTxn, we can't do that here but
4501 : : * we do add them to subxip array instead via ReorderBufferCopySnap. This
4502 : : * allows the catalog changes made in subtransactions decoded till now to
4503 : : * be visible.
4504 : : */
4505 [ + + ]: 725 : if (txn->snapshot_now == NULL)
4506 : : {
4507 : : dlist_iter subxact_i;
4508 : :
4509 : : /* make sure this transaction is streamed for the first time */
4510 : : Assert(!rbtxn_is_streamed(txn));
4511 : :
4512 : : /* at the beginning we should have invalid command ID */
4513 : : Assert(txn->command_id == InvalidCommandId);
4514 : :
4515 [ + - + + ]: 76 : dlist_foreach(subxact_i, &txn->subtxns)
4516 : : {
4517 : : ReorderBufferTXN *subtxn;
4518 : :
4519 : 4 : subtxn = dlist_container(ReorderBufferTXN, node, subxact_i.cur);
4520 : 4 : ReorderBufferTransferSnapToParent(txn, subtxn);
4521 : : }
4522 : :
4523 : : /*
4524 : : * If this transaction has no snapshot, it didn't make any changes to
4525 : : * the database till now, so there's nothing to decode.
4526 : : */
4527 [ - + ]: 72 : if (txn->base_snapshot == NULL)
4528 : : {
4529 : : Assert(txn->ninvalidations == 0);
4530 : 0 : return;
4531 : : }
4532 : :
4533 : 72 : command_id = FirstCommandId;
4534 : 72 : snapshot_now = ReorderBufferCopySnap(rb, txn->base_snapshot,
4535 : : txn, command_id);
4536 : : }
4537 : : else
4538 : : {
4539 : : /* the transaction must have been already streamed */
4540 : : Assert(rbtxn_is_streamed(txn));
4541 : :
4542 : : /*
4543 : : * Nah, we already have snapshot from the previous streaming run. We
4544 : : * assume new subxacts can't move the LSN backwards, and so can't beat
4545 : : * the LSN condition in the previous branch (so no need to walk
4546 : : * through subxacts again). In fact, we must not do that as we may be
4547 : : * using snapshot half-way through the subxact.
4548 : : */
4549 : 653 : command_id = txn->command_id;
4550 : :
4551 : : /*
4552 : : * We can't use txn->snapshot_now directly because after the last
4553 : : * streaming run, we might have got some new sub-transactions. So we
4554 : : * need to add them to the snapshot.
4555 : : */
4556 : 653 : snapshot_now = ReorderBufferCopySnap(rb, txn->snapshot_now,
4557 : : txn, command_id);
4558 : :
4559 : : /* Free the previously copied snapshot. */
4560 : : Assert(txn->snapshot_now->copied);
4561 : 653 : ReorderBufferFreeSnap(rb, txn->snapshot_now);
4562 : 653 : txn->snapshot_now = NULL;
4563 : : }
4564 : :
4565 : : /*
4566 : : * Remember this information to be used later to update stats. We can't
4567 : : * update the stats here as an error while processing the changes would
4568 : : * lead to the accumulation of stats even though we haven't streamed all
4569 : : * the changes.
4570 : : */
4571 : 725 : txn_is_streamed = rbtxn_is_streamed(txn);
4572 : 725 : stream_bytes = txn->total_size;
4573 : :
4574 : : /* Process and send the changes to output plugin. */
4575 : 725 : ReorderBufferProcessTXN(rb, txn, InvalidXLogRecPtr, snapshot_now,
4576 : : command_id, true);
4577 : :
4578 : 724 : rb->streamCount += 1;
4579 : 724 : rb->streamBytes += stream_bytes;
4580 : :
4581 : : /* Don't consider already streamed transaction. */
4582 : 724 : rb->streamTxns += (txn_is_streamed) ? 0 : 1;
4583 : :
4584 : : /* update the decoding stats */
4585 : 724 : UpdateDecodingStats((LogicalDecodingContext *) rb->private_data);
4586 : :
4587 : : Assert(dlist_is_empty(&txn->changes));
4588 : : Assert(txn->nentries == 0);
4589 : : Assert(txn->nentries_mem == 0);
4590 : : }
4591 : :
4592 : : /*
4593 : : * Size of a change in memory.
4594 : : */
4595 : : static Size
4596 : 2083790 : ReorderBufferChangeSize(ReorderBufferChange *change)
4597 : : {
4598 : 2083790 : Size sz = sizeof(ReorderBufferChange);
4599 : :
4600 [ + + + + : 2083790 : switch (change->action)
+ + - ]
4601 : : {
4602 : : /* fall through these, they're all similar enough */
4603 : 1947112 : case REORDER_BUFFER_CHANGE_INSERT:
4604 : : case REORDER_BUFFER_CHANGE_UPDATE:
4605 : : case REORDER_BUFFER_CHANGE_DELETE:
4606 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
4607 : : {
4608 : : HeapTuple oldtup,
4609 : : newtup;
4610 : 1947112 : Size oldlen = 0;
4611 : 1947112 : Size newlen = 0;
4612 : :
4613 : 1947112 : oldtup = change->data.tp.oldtuple;
4614 : 1947112 : newtup = change->data.tp.newtuple;
4615 : :
4616 [ + + ]: 1947112 : if (oldtup)
4617 : : {
4618 : 238340 : sz += sizeof(HeapTupleData);
4619 : 238340 : oldlen = oldtup->t_len;
4620 : 238340 : sz += oldlen;
4621 : : }
4622 : :
4623 [ + + ]: 1947112 : if (newtup)
4624 : : {
4625 : 1618045 : sz += sizeof(HeapTupleData);
4626 : 1618045 : newlen = newtup->t_len;
4627 : 1618045 : sz += newlen;
4628 : : }
4629 : :
4630 : 1947112 : break;
4631 : : }
4632 : 70 : case REORDER_BUFFER_CHANGE_MESSAGE:
4633 : : {
4634 : 70 : Size prefix_size = strlen(change->data.msg.prefix) + 1;
4635 : :
4636 : 70 : sz += prefix_size + change->data.msg.message_size +
4637 : : sizeof(Size) + sizeof(Size);
4638 : :
4639 : 70 : break;
4640 : : }
4641 : 13756 : case REORDER_BUFFER_CHANGE_INVALIDATION:
4642 : : {
4643 : 13756 : sz += sizeof(SharedInvalidationMessage) *
4644 : 13756 : change->data.inval.ninvalidations;
4645 : 13756 : break;
4646 : : }
4647 : 4165 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
4648 : : {
4649 : : Snapshot snap;
4650 : :
4651 : 4165 : snap = change->data.snapshot;
4652 : :
4653 : 4165 : sz += sizeof(SnapshotData) +
4654 : 4165 : sizeof(TransactionId) * snap->xcnt +
4655 : 4165 : sizeof(TransactionId) * snap->subxcnt;
4656 : :
4657 : 4165 : break;
4658 : : }
4659 : 79 : case REORDER_BUFFER_CHANGE_TRUNCATE:
4660 : : {
4661 : 79 : sz += sizeof(Oid) * change->data.truncate.nrelids;
4662 : :
4663 : 79 : break;
4664 : : }
4665 : 118608 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
4666 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
4667 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
4668 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
4669 : : /* ReorderBufferChange contains everything important */
4670 : 118608 : break;
4671 : : }
4672 : :
4673 : 2083790 : return sz;
4674 : : }
4675 : :
4676 : :
4677 : : /*
4678 : : * Restore a number of changes spilled to disk back into memory.
4679 : : */
4680 : : static Size
4681 : 106 : ReorderBufferRestoreChanges(ReorderBuffer *rb, ReorderBufferTXN *txn,
4682 : : TXNEntryFile *file, XLogSegNo *segno)
4683 : : {
4684 : 106 : Size restored = 0;
4685 : : XLogSegNo last_segno;
4686 : : dlist_mutable_iter cleanup_iter;
4687 : 106 : File *fd = &file->vfd;
4688 : :
4689 : : Assert(XLogRecPtrIsValid(txn->first_lsn));
4690 : : Assert(XLogRecPtrIsValid(txn->final_lsn));
4691 : :
4692 : : /* free current entries, so we have memory for more */
4693 [ + - + + ]: 174720 : dlist_foreach_modify(cleanup_iter, &txn->changes)
4694 : : {
4695 : 174614 : ReorderBufferChange *cleanup =
4696 : 174614 : dlist_container(ReorderBufferChange, node, cleanup_iter.cur);
4697 : :
4698 : 174614 : dlist_delete(&cleanup->node);
4699 : 174614 : ReorderBufferFreeChange(rb, cleanup, true);
4700 : : }
4701 : 106 : txn->nentries_mem = 0;
4702 : : Assert(dlist_is_empty(&txn->changes));
4703 : :
4704 : 106 : XLByteToSeg(txn->final_lsn, last_segno, wal_segment_size);
4705 : :
4706 [ + + + + ]: 178496 : while (restored < max_changes_in_memory && *segno <= last_segno)
4707 : : {
4708 : : ssize_t readBytes;
4709 : : ReorderBufferDiskChange *ondisk;
4710 : :
4711 [ - + ]: 178390 : CHECK_FOR_INTERRUPTS();
4712 : :
4713 [ + + ]: 178390 : if (*fd == -1)
4714 : : {
4715 : : char path[MAXPGPATH];
4716 : :
4717 : : /* first time in */
4718 [ + + ]: 43 : if (*segno == 0)
4719 : 41 : XLByteToSeg(txn->first_lsn, *segno, wal_segment_size);
4720 : :
4721 : : Assert(*segno != 0 || dlist_is_empty(&txn->changes));
4722 : :
4723 : : /*
4724 : : * No need to care about TLIs here, only used during a single run,
4725 : : * so each LSN only maps to a specific WAL record.
4726 : : */
4727 : 43 : ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid,
4728 : : *segno);
4729 : :
4730 : 43 : *fd = PathNameOpenFile(path, O_RDONLY | PG_BINARY);
4731 : :
4732 : : /* No harm in resetting the offset even in case of failure */
4733 : 43 : file->curOffset = 0;
4734 : :
4735 [ - + - - ]: 43 : if (*fd < 0 && errno == ENOENT)
4736 : : {
4737 : 0 : *fd = -1;
4738 : 0 : (*segno)++;
4739 : 0 : continue;
4740 : : }
4741 [ - + ]: 43 : else if (*fd < 0)
4742 [ # # ]: 0 : ereport(ERROR,
4743 : : (errcode_for_file_access(),
4744 : : errmsg("could not open file \"%s\": %m",
4745 : : path)));
4746 : : }
4747 : :
4748 : : /*
4749 : : * Read the statically sized part of a change which has information
4750 : : * about the total size. If we couldn't read a record, we're at the
4751 : : * end of this file.
4752 : : */
4753 : 178390 : ReorderBufferSerializeReserve(rb, sizeof(ReorderBufferDiskChange));
4754 : 178390 : readBytes = FileRead(file->vfd, rb->outbuf,
4755 : : sizeof(ReorderBufferDiskChange),
4756 : : file->curOffset, WAIT_EVENT_REORDER_BUFFER_READ);
4757 : :
4758 : : /* eof */
4759 [ + + ]: 178390 : if (readBytes == 0)
4760 : : {
4761 : 43 : FileClose(*fd);
4762 : 43 : *fd = -1;
4763 : 43 : (*segno)++;
4764 : 43 : continue;
4765 : : }
4766 [ - + ]: 178347 : else if (readBytes < 0)
4767 [ # # ]: 0 : ereport(ERROR,
4768 : : (errcode_for_file_access(),
4769 : : errmsg("could not read from reorderbuffer spill file: %m")));
4770 [ - + ]: 178347 : else if (readBytes != sizeof(ReorderBufferDiskChange))
4771 [ # # ]: 0 : ereport(ERROR,
4772 : : (errcode_for_file_access(),
4773 : : errmsg("could not read from reorderbuffer spill file: read %zd of %zu",
4774 : : readBytes,
4775 : : sizeof(ReorderBufferDiskChange))));
4776 : :
4777 : 178347 : file->curOffset += readBytes;
4778 : :
4779 : 178347 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4780 : :
4781 : 178347 : ReorderBufferSerializeReserve(rb,
4782 : 178347 : sizeof(ReorderBufferDiskChange) + ondisk->size);
4783 : 178347 : ondisk = (ReorderBufferDiskChange *) rb->outbuf;
4784 : :
4785 : 178347 : readBytes = FileRead(file->vfd,
4786 : 178347 : rb->outbuf + sizeof(ReorderBufferDiskChange),
4787 : 178347 : ondisk->size - sizeof(ReorderBufferDiskChange),
4788 : : file->curOffset,
4789 : : WAIT_EVENT_REORDER_BUFFER_READ);
4790 : :
4791 [ - + ]: 178347 : if (readBytes < 0)
4792 [ # # ]: 0 : ereport(ERROR,
4793 : : (errcode_for_file_access(),
4794 : : errmsg("could not read from reorderbuffer spill file: %m")));
4795 [ - + ]: 178347 : else if (readBytes != ondisk->size - sizeof(ReorderBufferDiskChange))
4796 [ # # ]: 0 : ereport(ERROR,
4797 : : (errcode_for_file_access(),
4798 : : errmsg("could not read from reorderbuffer spill file: read %zd of %zu",
4799 : : readBytes,
4800 : : (ondisk->size - sizeof(ReorderBufferDiskChange)))));
4801 : :
4802 : 178347 : file->curOffset += readBytes;
4803 : :
4804 : : /*
4805 : : * ok, read a full change from disk, now restore it into proper
4806 : : * in-memory format
4807 : : */
4808 : 178347 : ReorderBufferRestoreChange(rb, txn, rb->outbuf);
4809 : 178347 : restored++;
4810 : : }
4811 : :
4812 : 106 : return restored;
4813 : : }
4814 : :
4815 : : /*
4816 : : * Convert change from its on-disk format to in-memory format and queue it onto
4817 : : * the TXN's ->changes list.
4818 : : *
4819 : : * Note: although "data" is declared char*, at entry it points to a
4820 : : * maxalign'd buffer, making it safe in most of this function to assume
4821 : : * that the pointed-to data is suitably aligned for direct access.
4822 : : */
4823 : : static void
4824 : 178347 : ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
4825 : : char *data)
4826 : : {
4827 : : ReorderBufferDiskChange *ondisk;
4828 : : ReorderBufferChange *change;
4829 : :
4830 : 178347 : ondisk = (ReorderBufferDiskChange *) data;
4831 : :
4832 : 178347 : change = ReorderBufferAllocChange(rb);
4833 : :
4834 : : /* copy static part */
4835 : 178347 : memcpy(change, &ondisk->change, sizeof(ReorderBufferChange));
4836 : :
4837 : 178347 : data += sizeof(ReorderBufferDiskChange);
4838 : :
4839 : : /* restore individual stuff */
4840 [ + + + + : 178347 : switch (change->action)
- + - ]
4841 : : {
4842 : : /* fall through these, they're all similar enough */
4843 : 176400 : case REORDER_BUFFER_CHANGE_INSERT:
4844 : : case REORDER_BUFFER_CHANGE_UPDATE:
4845 : : case REORDER_BUFFER_CHANGE_DELETE:
4846 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT:
4847 [ + + ]: 176400 : if (change->data.tp.oldtuple)
4848 : : {
4849 : 5006 : uint32 tuplelen = ((HeapTuple) data)->t_len;
4850 : :
4851 : 5006 : change->data.tp.oldtuple =
4852 : 5006 : ReorderBufferAllocTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
4853 : :
4854 : : /* restore ->tuple */
4855 : 5006 : memcpy(change->data.tp.oldtuple, data,
4856 : : sizeof(HeapTupleData));
4857 : 5006 : data += sizeof(HeapTupleData);
4858 : :
4859 : : /* reset t_data pointer into the new tuplebuf */
4860 : 5006 : change->data.tp.oldtuple->t_data =
4861 : 5006 : (HeapTupleHeader) ((char *) change->data.tp.oldtuple + HEAPTUPLESIZE);
4862 : :
4863 : : /* restore tuple data itself */
4864 : 5006 : memcpy(change->data.tp.oldtuple->t_data, data, tuplelen);
4865 : 5006 : data += tuplelen;
4866 : : }
4867 : :
4868 [ + + ]: 176400 : if (change->data.tp.newtuple)
4869 : : {
4870 : : /* here, data might not be suitably aligned! */
4871 : : uint32 tuplelen;
4872 : :
4873 : 166183 : memcpy(&tuplelen, data + offsetof(HeapTupleData, t_len),
4874 : : sizeof(uint32));
4875 : :
4876 : 166183 : change->data.tp.newtuple =
4877 : 166183 : ReorderBufferAllocTupleBuf(rb, tuplelen - SizeofHeapTupleHeader);
4878 : :
4879 : : /* restore ->tuple */
4880 : 166183 : memcpy(change->data.tp.newtuple, data,
4881 : : sizeof(HeapTupleData));
4882 : 166183 : data += sizeof(HeapTupleData);
4883 : :
4884 : : /* reset t_data pointer into the new tuplebuf */
4885 : 166183 : change->data.tp.newtuple->t_data =
4886 : 166183 : (HeapTupleHeader) ((char *) change->data.tp.newtuple + HEAPTUPLESIZE);
4887 : :
4888 : : /* restore tuple data itself */
4889 : 166183 : memcpy(change->data.tp.newtuple->t_data, data, tuplelen);
4890 : 166183 : data += tuplelen;
4891 : : }
4892 : :
4893 : 176400 : break;
4894 : 1 : case REORDER_BUFFER_CHANGE_MESSAGE:
4895 : : {
4896 : : Size prefix_size;
4897 : :
4898 : : /* read prefix */
4899 : 1 : memcpy(&prefix_size, data, sizeof(Size));
4900 : 1 : data += sizeof(Size);
4901 : 1 : change->data.msg.prefix = MemoryContextAlloc(rb->context,
4902 : : prefix_size);
4903 : 1 : memcpy(change->data.msg.prefix, data, prefix_size);
4904 : : Assert(change->data.msg.prefix[prefix_size - 1] == '\0');
4905 : 1 : data += prefix_size;
4906 : :
4907 : : /* read the message */
4908 : 1 : memcpy(&change->data.msg.message_size, data, sizeof(Size));
4909 : 1 : data += sizeof(Size);
4910 : 1 : change->data.msg.message = MemoryContextAlloc(rb->context,
4911 : : change->data.msg.message_size);
4912 : 1 : memcpy(change->data.msg.message, data,
4913 : : change->data.msg.message_size);
4914 : 1 : data += change->data.msg.message_size;
4915 : :
4916 : 1 : break;
4917 : : }
4918 : 28 : case REORDER_BUFFER_CHANGE_INVALIDATION:
4919 : : {
4920 : 28 : Size inval_size = sizeof(SharedInvalidationMessage) *
4921 : 28 : change->data.inval.ninvalidations;
4922 : :
4923 : 28 : change->data.inval.invalidations =
4924 : 28 : MemoryContextAlloc(rb->context, inval_size);
4925 : :
4926 : : /* read the message */
4927 : 28 : memcpy(change->data.inval.invalidations, data, inval_size);
4928 : :
4929 : 28 : break;
4930 : : }
4931 : 2 : case REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT:
4932 : : {
4933 : : Snapshot oldsnap;
4934 : : Snapshot newsnap;
4935 : : Size size;
4936 : :
4937 : 2 : oldsnap = (Snapshot) data;
4938 : :
4939 : 2 : size = sizeof(SnapshotData) +
4940 : 2 : sizeof(TransactionId) * oldsnap->xcnt +
4941 : 2 : sizeof(TransactionId) * (oldsnap->subxcnt + 0);
4942 : :
4943 : 2 : change->data.snapshot = MemoryContextAllocZero(rb->context, size);
4944 : :
4945 : 2 : newsnap = change->data.snapshot;
4946 : :
4947 : 2 : memcpy(newsnap, data, size);
4948 : 2 : newsnap->xip = (TransactionId *)
4949 : : (((char *) newsnap) + sizeof(SnapshotData));
4950 : 2 : newsnap->subxip = newsnap->xip + newsnap->xcnt;
4951 : 2 : newsnap->copied = true;
4952 : 2 : break;
4953 : : }
4954 : : /* the base struct contains all the data, easy peasy */
4955 : 0 : case REORDER_BUFFER_CHANGE_TRUNCATE:
4956 : : {
4957 : : Oid *relids;
4958 : :
4959 : 0 : relids = ReorderBufferAllocRelids(rb, change->data.truncate.nrelids);
4960 : 0 : memcpy(relids, data, change->data.truncate.nrelids * sizeof(Oid));
4961 : 0 : change->data.truncate.relids = relids;
4962 : :
4963 : 0 : break;
4964 : : }
4965 : 1916 : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM:
4966 : : case REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT:
4967 : : case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
4968 : : case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
4969 : 1916 : break;
4970 : : }
4971 : :
4972 : 178347 : dlist_push_tail(&txn->changes, &change->node);
4973 : 178347 : txn->nentries_mem++;
4974 : :
4975 : : /*
4976 : : * Update memory accounting for the restored change. We need to do this
4977 : : * although we don't check the memory limit when restoring the changes in
4978 : : * this branch (we only do that when initially queueing the changes after
4979 : : * decoding), because we will release the changes later, and that will
4980 : : * update the accounting too (subtracting the size from the counters). And
4981 : : * we don't want to underflow there.
4982 : : */
4983 : 178347 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
4984 : : ReorderBufferChangeSize(change));
4985 : 178347 : }
4986 : :
4987 : : /*
4988 : : * Remove all on-disk stored for the passed in transaction.
4989 : : */
4990 : : static void
4991 : 293 : ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
4992 : : {
4993 : : XLogSegNo first;
4994 : : XLogSegNo cur;
4995 : : XLogSegNo last;
4996 : :
4997 : : Assert(XLogRecPtrIsValid(txn->first_lsn));
4998 : : Assert(XLogRecPtrIsValid(txn->final_lsn));
4999 : :
5000 : 293 : XLByteToSeg(txn->first_lsn, first, wal_segment_size);
5001 : 293 : XLByteToSeg(txn->final_lsn, last, wal_segment_size);
5002 : :
5003 : : /* iterate over all possible filenames, and delete them */
5004 [ + + ]: 590 : for (cur = first; cur <= last; cur++)
5005 : : {
5006 : : char path[MAXPGPATH];
5007 : :
5008 : 297 : ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur);
5009 [ - + - - ]: 297 : if (unlink(path) != 0 && errno != ENOENT)
5010 [ # # ]: 0 : ereport(ERROR,
5011 : : (errcode_for_file_access(),
5012 : : errmsg("could not remove file \"%s\": %m", path)));
5013 : : }
5014 : 293 : }
5015 : :
5016 : : /*
5017 : : * Remove any leftover serialized reorder buffers from a slot directory after a
5018 : : * prior crash or decoding session exit.
5019 : : */
5020 : : static void
5021 : 2454 : ReorderBufferCleanupSerializedTXNs(const char *slotname)
5022 : : {
5023 : : DIR *spill_dir;
5024 : : struct dirent *spill_de;
5025 : : struct stat statbuf;
5026 : : char path[MAXPGPATH * 2 + sizeof(PG_REPLSLOT_DIR)];
5027 : :
5028 : 2454 : sprintf(path, "%s/%s", PG_REPLSLOT_DIR, slotname);
5029 : :
5030 : : /* we're only handling directories here, skip if it's not ours */
5031 [ + - - + ]: 2454 : if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
5032 : 0 : return;
5033 : :
5034 : 2454 : spill_dir = AllocateDir(path);
5035 [ + + ]: 12270 : while ((spill_de = ReadDirExtended(spill_dir, path, INFO)) != NULL)
5036 : : {
5037 : : /* only look at names that can be ours */
5038 [ - + ]: 7362 : if (strncmp(spill_de->d_name, "xid", 3) == 0)
5039 : : {
5040 : 0 : snprintf(path, sizeof(path),
5041 : : "%s/%s/%s", PG_REPLSLOT_DIR, slotname,
5042 : 0 : spill_de->d_name);
5043 : :
5044 [ # # ]: 0 : if (unlink(path) != 0)
5045 [ # # ]: 0 : ereport(ERROR,
5046 : : (errcode_for_file_access(),
5047 : : errmsg("could not remove file \"%s\" during removal of %s/%s/xid*: %m",
5048 : : path, PG_REPLSLOT_DIR, slotname)));
5049 : : }
5050 : : }
5051 : 2454 : FreeDir(spill_dir);
5052 : : }
5053 : :
5054 : : /*
5055 : : * Given a replication slot, transaction ID and segment number, fill in the
5056 : : * corresponding spill file into 'path', which is a caller-owned buffer of size
5057 : : * at least MAXPGPATH.
5058 : : */
5059 : : static void
5060 : 4059 : ReorderBufferSerializedPath(char *path, ReplicationSlot *slot, TransactionId xid,
5061 : : XLogSegNo segno)
5062 : : {
5063 : : XLogRecPtr recptr;
5064 : :
5065 : 4059 : XLogSegNoOffsetToRecPtr(segno, 0, wal_segment_size, recptr);
5066 : :
5067 : 4059 : snprintf(path, MAXPGPATH, "%s/%s/xid-%u-lsn-%X-%X.spill",
5068 : : PG_REPLSLOT_DIR,
5069 : 4059 : NameStr(MyReplicationSlot->data.name),
5070 : 4059 : xid, LSN_FORMAT_ARGS(recptr));
5071 : 4059 : }
5072 : :
5073 : : /*
5074 : : * Delete all data spilled to disk after we've restarted/crashed. It will be
5075 : : * recreated when the respective slots are reused.
5076 : : */
5077 : : void
5078 : 1150 : StartupReorderBuffer(void)
5079 : : {
5080 : : DIR *logical_dir;
5081 : : struct dirent *logical_de;
5082 : :
5083 : 1150 : logical_dir = AllocateDir(PG_REPLSLOT_DIR);
5084 [ + + ]: 3583 : while ((logical_de = ReadDir(logical_dir, PG_REPLSLOT_DIR)) != NULL)
5085 : : {
5086 [ + + ]: 2433 : if (strcmp(logical_de->d_name, ".") == 0 ||
5087 [ + + ]: 1283 : strcmp(logical_de->d_name, "..") == 0)
5088 : 2300 : continue;
5089 : :
5090 : : /* if it cannot be a slot, skip the directory */
5091 [ - + ]: 133 : if (!ReplicationSlotValidateName(logical_de->d_name, true, DEBUG2))
5092 : 0 : continue;
5093 : :
5094 : : /*
5095 : : * ok, has to be a surviving logical slot, iterate and delete
5096 : : * everything starting with xid-*
5097 : : */
5098 : 133 : ReorderBufferCleanupSerializedTXNs(logical_de->d_name);
5099 : : }
5100 : 1150 : FreeDir(logical_dir);
5101 : 1150 : }
5102 : :
5103 : : /* ---------------------------------------
5104 : : * toast reassembly support
5105 : : * ---------------------------------------
5106 : : */
5107 : :
5108 : : /*
5109 : : * Initialize per tuple toast reconstruction support.
5110 : : */
5111 : : static void
5112 : 64 : ReorderBufferToastInitHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
5113 : : {
5114 : : HASHCTL hash_ctl;
5115 : :
5116 : : Assert(txn->toast_hash == NULL);
5117 : :
5118 : 64 : hash_ctl.keysize = sizeof(Oid8);
5119 : 64 : hash_ctl.entrysize = sizeof(ReorderBufferToastEnt);
5120 : 64 : hash_ctl.hcxt = rb->context;
5121 : 64 : txn->toast_hash = hash_create("ReorderBufferToastHash", 5, &hash_ctl,
5122 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5123 : 64 : }
5124 : :
5125 : : /*
5126 : : * Per toast-chunk handling for toast reconstruction
5127 : : *
5128 : : * Appends a toast chunk so we can reconstruct it when the tuple "owning" the
5129 : : * toasted Datum comes along.
5130 : : */
5131 : : static void
5132 : 1952 : ReorderBufferToastAppendChunk(ReorderBuffer *rb, ReorderBufferTXN *txn,
5133 : : Relation relation, ReorderBufferChange *change)
5134 : : {
5135 : : ReorderBufferToastEnt *ent;
5136 : : HeapTuple newtup;
5137 : : bool found;
5138 : : int32 chunksize;
5139 : : bool isnull;
5140 : : Pointer chunk;
5141 : 1952 : TupleDesc desc = RelationGetDescr(relation);
5142 : : Oid8 chunk_id;
5143 : : int32 chunk_seq;
5144 : : Oid valueid_type;
5145 : : Datum valueid_datum;
5146 : :
5147 [ + + ]: 1952 : if (txn->toast_hash == NULL)
5148 : 64 : ReorderBufferToastInitHash(rb, txn);
5149 : :
5150 : : Assert(IsToastRelation(relation));
5151 : :
5152 : 1952 : newtup = change->data.tp.newtuple;
5153 : 1952 : valueid_type = TupleDescAttr(desc, 0)->atttypid;
5154 : 1952 : valueid_datum = fastgetattr(newtup, 1, desc, &isnull);
5155 [ + + ]: 1952 : if (valueid_type == OID8OID)
5156 : 66 : chunk_id = DatumGetObjectId8(valueid_datum);
5157 : : else
5158 : 1886 : chunk_id = DatumGetObjectId(valueid_datum);
5159 : : Assert(!isnull);
5160 : 1952 : chunk_seq = DatumGetInt32(fastgetattr(newtup, 2, desc, &isnull));
5161 : : Assert(!isnull);
5162 : :
5163 : : ent = (ReorderBufferToastEnt *)
5164 : 1952 : hash_search(txn->toast_hash, &chunk_id, HASH_ENTER, &found);
5165 : :
5166 [ + + ]: 1952 : if (!found)
5167 : : {
5168 : : Assert(ent->chunk_id == chunk_id);
5169 : 86 : ent->num_chunks = 0;
5170 : 86 : ent->last_chunk_seq = 0;
5171 : 86 : ent->size = 0;
5172 : 86 : ent->reconstructed = NULL;
5173 : 86 : dlist_init(&ent->chunks);
5174 : :
5175 [ - + ]: 86 : if (chunk_seq != 0)
5176 [ # # ]: 0 : elog(ERROR, "got sequence entry %d for toast chunk %" PRIu64 " instead of seq 0",
5177 : : chunk_seq, chunk_id);
5178 : : }
5179 [ + - - + ]: 1866 : else if (found && chunk_seq != ent->last_chunk_seq + 1)
5180 [ # # ]: 0 : elog(ERROR, "got sequence entry %d for toast chunk %" PRIu64 " instead of seq %d",
5181 : : chunk_seq, chunk_id, ent->last_chunk_seq + 1);
5182 : :
5183 : 1952 : chunk = DatumGetPointer(fastgetattr(newtup, 3, desc, &isnull));
5184 : : Assert(!isnull);
5185 : :
5186 : : /* calculate size so we can allocate the right size at once later */
5187 [ + - ]: 1952 : if (!VARATT_IS_EXTENDED(chunk))
5188 : 1952 : chunksize = VARSIZE(chunk) - VARHDRSZ;
5189 [ # # ]: 0 : else if (VARATT_IS_SHORT(chunk))
5190 : : /* could happen due to heap_form_tuple doing its thing */
5191 : 0 : chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
5192 : : else
5193 [ # # ]: 0 : elog(ERROR, "unexpected type of toast chunk");
5194 : :
5195 : 1952 : ent->size += chunksize;
5196 : 1952 : ent->last_chunk_seq = chunk_seq;
5197 : 1952 : ent->num_chunks++;
5198 : 1952 : dlist_push_tail(&ent->chunks, &change->node);
5199 : 1952 : }
5200 : :
5201 : : /*
5202 : : * Rejigger change->newtuple to point to in-memory toast tuples instead of
5203 : : * on-disk toast tuples that may no longer exist (think DROP TABLE or VACUUM).
5204 : : *
5205 : : * We cannot replace unchanged toast tuples though, so those will still point
5206 : : * to on-disk toast data.
5207 : : *
5208 : : * While updating the existing change with detoasted tuple data, we need to
5209 : : * update the memory accounting info, because the change size will differ.
5210 : : * Otherwise the accounting may get out of sync, triggering serialization
5211 : : * at unexpected times.
5212 : : *
5213 : : * We simply subtract size of the change before rejiggering the tuple, and
5214 : : * then add the new size. This makes it look like the change was removed
5215 : : * and then added back, except it only tweaks the accounting info.
5216 : : *
5217 : : * In particular it can't trigger serialization, which would be pointless
5218 : : * anyway as it happens during commit processing right before handing
5219 : : * the change to the output plugin.
5220 : : */
5221 : : static void
5222 : 361710 : ReorderBufferToastReplace(ReorderBuffer *rb, ReorderBufferTXN *txn,
5223 : : Relation relation, ReorderBufferChange *change)
5224 : : {
5225 : : TupleDesc desc;
5226 : : int natt;
5227 : : Datum *attrs;
5228 : : bool *isnull;
5229 : : bool *free;
5230 : : HeapTuple tmphtup;
5231 : : Relation toast_rel;
5232 : : TupleDesc toast_desc;
5233 : : MemoryContext oldcontext;
5234 : : HeapTuple newtup;
5235 : : Size old_size;
5236 : :
5237 : : /* no toast tuples changed */
5238 [ + + ]: 361710 : if (txn->toast_hash == NULL)
5239 : 361435 : return;
5240 : :
5241 : : /*
5242 : : * We're going to modify the size of the change. So, to make sure the
5243 : : * accounting is correct we record the current change size and then after
5244 : : * re-computing the change we'll subtract the recorded size and then
5245 : : * re-add the new change size at the end. We don't immediately subtract
5246 : : * the old size because if there is any error before we add the new size,
5247 : : * we will release the changes and that will update the accounting info
5248 : : * (subtracting the size from the counters). And we don't want to
5249 : : * underflow there.
5250 : : */
5251 : 275 : old_size = ReorderBufferChangeSize(change);
5252 : :
5253 : 275 : oldcontext = MemoryContextSwitchTo(rb->context);
5254 : :
5255 : : /* we should only have toast tuples in an INSERT or UPDATE */
5256 : : Assert(change->data.tp.newtuple);
5257 : :
5258 : 275 : desc = RelationGetDescr(relation);
5259 : :
5260 : 275 : toast_rel = RelationIdGetRelation(relation->rd_rel->reltoastrelid);
5261 [ - + ]: 275 : if (!RelationIsValid(toast_rel))
5262 [ # # ]: 0 : elog(ERROR, "could not open toast relation with OID %u (base relation \"%s\")",
5263 : : relation->rd_rel->reltoastrelid, RelationGetRelationName(relation));
5264 : :
5265 : 275 : toast_desc = RelationGetDescr(toast_rel);
5266 : :
5267 : : /* should we allocate from stack instead? */
5268 : 275 : attrs = palloc0_array(Datum, desc->natts);
5269 : 275 : isnull = palloc0_array(bool, desc->natts);
5270 : 275 : free = palloc0_array(bool, desc->natts);
5271 : :
5272 : 275 : newtup = change->data.tp.newtuple;
5273 : :
5274 : 275 : heap_deform_tuple(newtup, desc, attrs, isnull);
5275 : :
5276 [ + + ]: 909 : for (natt = 0; natt < desc->natts; natt++)
5277 : : {
5278 : 634 : CompactAttribute *attr = TupleDescCompactAttr(desc, natt);
5279 : : ReorderBufferToastEnt *ent;
5280 : : varlena *varlena_pointer;
5281 : :
5282 : : /* va_rawsize is the size of the original datum -- including header */
5283 : : toast_external_data toast_ext_data;
5284 : : varatt_indirect redirect_pointer;
5285 : 634 : varlena *new_datum = NULL;
5286 : : varlena *reconstructed;
5287 : : dlist_iter it;
5288 : 634 : Size data_done = 0;
5289 : : Oid8 toast_valueid;
5290 : :
5291 [ + + ]: 634 : if (attr->attisdropped)
5292 : 550 : continue;
5293 : :
5294 : : /* not a varlena datatype */
5295 [ + + ]: 589 : if (attr->attlen != -1)
5296 : 269 : continue;
5297 : :
5298 : : /* no data */
5299 [ + + ]: 320 : if (isnull[natt])
5300 : 12 : continue;
5301 : :
5302 : : /* ok, we know we have a toast datum */
5303 : 308 : varlena_pointer = (varlena *) DatumGetPointer(attrs[natt]);
5304 : :
5305 : : /* no need to do anything if the tuple isn't external */
5306 [ + + ]: 308 : if (!VARATT_IS_EXTERNAL_ONDISK(varlena_pointer))
5307 : 216 : continue;
5308 : :
5309 : 92 : toast_external_info_get(varlena_pointer, &toast_ext_data);
5310 : 92 : toast_valueid = toast_ext_data.valueid;
5311 : :
5312 : : /*
5313 : : * Check whether the toast tuple changed, replace if so.
5314 : : */
5315 : : ent = (ReorderBufferToastEnt *)
5316 : 92 : hash_search(txn->toast_hash,
5317 : : &toast_valueid,
5318 : : HASH_FIND,
5319 : : NULL);
5320 [ + + ]: 92 : if (ent == NULL)
5321 : 8 : continue;
5322 : :
5323 : : new_datum =
5324 : 84 : (varlena *) palloc0(INDIRECT_POINTER_SIZE);
5325 : :
5326 : 84 : free[natt] = true;
5327 : :
5328 : 84 : reconstructed = palloc0(toast_ext_data.rawsize);
5329 : :
5330 : 84 : ent->reconstructed = reconstructed;
5331 : :
5332 : : /* stitch toast tuple back together from its parts */
5333 [ + - + + ]: 1976 : dlist_foreach(it, &ent->chunks)
5334 : : {
5335 : : bool cisnull;
5336 : : ReorderBufferChange *cchange;
5337 : : HeapTuple ctup;
5338 : : Pointer chunk;
5339 : :
5340 : 1892 : cchange = dlist_container(ReorderBufferChange, node, it.cur);
5341 : 1892 : ctup = cchange->data.tp.newtuple;
5342 : 1892 : chunk = DatumGetPointer(fastgetattr(ctup, 3, toast_desc, &cisnull));
5343 : :
5344 : : Assert(!cisnull);
5345 : : Assert(!VARATT_IS_EXTERNAL(chunk));
5346 : : Assert(!VARATT_IS_SHORT(chunk));
5347 : :
5348 : 1892 : memcpy(VARDATA(reconstructed) + data_done,
5349 : 1892 : VARDATA(chunk),
5350 : 1892 : VARSIZE(chunk) - VARHDRSZ);
5351 : 1892 : data_done += VARSIZE(chunk) - VARHDRSZ;
5352 : : }
5353 : : Assert(data_done == VARATT_EXTINFO_GET_EXTSIZE(toast_ext_data.extinfo));
5354 : :
5355 : : /* make sure its marked as compressed or not */
5356 [ + + ]: 84 : if (VARATT_EXTINFO_IS_COMPRESSED(toast_ext_data.extinfo, toast_ext_data.rawsize))
5357 : 24 : SET_VARSIZE_COMPRESSED(reconstructed, data_done + VARHDRSZ);
5358 : : else
5359 : 60 : SET_VARSIZE(reconstructed, data_done + VARHDRSZ);
5360 : :
5361 : 84 : memset(&redirect_pointer, 0, sizeof(redirect_pointer));
5362 : 84 : redirect_pointer.pointer = reconstructed;
5363 : :
5364 : 84 : SET_VARTAG_EXTERNAL(new_datum, VARTAG_INDIRECT);
5365 : 84 : memcpy(VARDATA_EXTERNAL(new_datum), &redirect_pointer,
5366 : : sizeof(redirect_pointer));
5367 : :
5368 : 84 : attrs[natt] = PointerGetDatum(new_datum);
5369 : : }
5370 : :
5371 : : /*
5372 : : * Build tuple in separate memory & copy tuple back into the tuplebuf
5373 : : * passed to the output plugin. We can't directly heap_fill_tuple() into
5374 : : * the tuplebuf because attrs[] will point back into the current content.
5375 : : */
5376 : 275 : tmphtup = heap_form_tuple(desc, attrs, isnull);
5377 : : Assert(newtup->t_len <= MaxHeapTupleSize);
5378 : : Assert(newtup->t_data == (HeapTupleHeader) ((char *) newtup + HEAPTUPLESIZE));
5379 : :
5380 : 275 : memcpy(newtup->t_data, tmphtup->t_data, tmphtup->t_len);
5381 : 275 : newtup->t_len = tmphtup->t_len;
5382 : :
5383 : : /*
5384 : : * free resources we won't further need, more persistent stuff will be
5385 : : * free'd in ReorderBufferToastReset().
5386 : : */
5387 : 275 : RelationClose(toast_rel);
5388 : 275 : pfree(tmphtup);
5389 [ + + ]: 909 : for (natt = 0; natt < desc->natts; natt++)
5390 : : {
5391 [ + + ]: 634 : if (free[natt])
5392 : 84 : pfree(DatumGetPointer(attrs[natt]));
5393 : : }
5394 : 275 : pfree(attrs);
5395 : 275 : pfree(free);
5396 : 275 : pfree(isnull);
5397 : :
5398 : 275 : MemoryContextSwitchTo(oldcontext);
5399 : :
5400 : : /* subtract the old change size */
5401 : 275 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, false, old_size);
5402 : : /* now add the change back, with the correct size */
5403 : 275 : ReorderBufferChangeMemoryUpdate(rb, change, NULL, true,
5404 : : ReorderBufferChangeSize(change));
5405 : : }
5406 : :
5407 : : /*
5408 : : * Free all resources allocated for toast reconstruction.
5409 : : */
5410 : : static void
5411 : 366965 : ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
5412 : : {
5413 : : HASH_SEQ_STATUS hstat;
5414 : : ReorderBufferToastEnt *ent;
5415 : :
5416 [ + + ]: 366965 : if (txn->toast_hash == NULL)
5417 : 366901 : return;
5418 : :
5419 : : /* sequentially walk over the hash and free everything */
5420 : 64 : hash_seq_init(&hstat, txn->toast_hash);
5421 [ + + ]: 150 : while ((ent = (ReorderBufferToastEnt *) hash_seq_search(&hstat)) != NULL)
5422 : : {
5423 : : dlist_mutable_iter it;
5424 : :
5425 [ + + ]: 86 : if (ent->reconstructed != NULL)
5426 : 84 : pfree(ent->reconstructed);
5427 : :
5428 [ + - + + ]: 2038 : dlist_foreach_modify(it, &ent->chunks)
5429 : : {
5430 : 1952 : ReorderBufferChange *change =
5431 : 1952 : dlist_container(ReorderBufferChange, node, it.cur);
5432 : :
5433 : 1952 : dlist_delete(&change->node);
5434 : 1952 : ReorderBufferFreeChange(rb, change, true);
5435 : : }
5436 : : }
5437 : :
5438 : 64 : hash_destroy(txn->toast_hash);
5439 : 64 : txn->toast_hash = NULL;
5440 : : }
5441 : :
5442 : :
5443 : : /* ---------------------------------------
5444 : : * Visibility support for logical decoding
5445 : : *
5446 : : *
5447 : : * Lookup actual cmin/cmax values when using decoding snapshot. We can't
5448 : : * always rely on stored cmin/cmax values because of two scenarios:
5449 : : *
5450 : : * * A tuple got changed multiple times during a single transaction and thus
5451 : : * has got a combo CID. Combo CIDs are only valid for the duration of a
5452 : : * single transaction.
5453 : : * * A tuple with a cmin but no cmax (and thus no combo CID) got
5454 : : * deleted/updated in another transaction than the one which created it
5455 : : * which we are looking at right now. As only one of cmin, cmax or combo CID
5456 : : * is actually stored in the heap we don't have access to the value we
5457 : : * need anymore.
5458 : : *
5459 : : * To resolve those problems we have a per-transaction hash of (cmin,
5460 : : * cmax) tuples keyed by (relfilelocator, ctid) which contains the actual
5461 : : * (cmin, cmax) values. That also takes care of combo CIDs by simply
5462 : : * not caring about them at all. As we have the real cmin/cmax values
5463 : : * combo CIDs aren't interesting.
5464 : : *
5465 : : * As we only care about catalog tuples here the overhead of this
5466 : : * hashtable should be acceptable.
5467 : : *
5468 : : * Heap rewrites complicate this a bit, check rewriteheap.c for
5469 : : * details.
5470 : : * -------------------------------------------------------------------------
5471 : : */
5472 : :
5473 : : /* struct for sorting mapping files by LSN efficiently */
5474 : : typedef struct RewriteMappingFile
5475 : : {
5476 : : XLogRecPtr lsn;
5477 : : char fname[MAXPGPATH];
5478 : : } RewriteMappingFile;
5479 : :
5480 : : #ifdef NOT_USED
5481 : : static void
5482 : : DisplayMapping(HTAB *tuplecid_data)
5483 : : {
5484 : : HASH_SEQ_STATUS hstat;
5485 : : ReorderBufferTupleCidEnt *ent;
5486 : :
5487 : : hash_seq_init(&hstat, tuplecid_data);
5488 : : while ((ent = (ReorderBufferTupleCidEnt *) hash_seq_search(&hstat)) != NULL)
5489 : : {
5490 : : elog(DEBUG3, "mapping: node: %u/%u/%u tid: %u/%u cmin: %u, cmax: %u",
5491 : : ent->key.rlocator.dbOid,
5492 : : ent->key.rlocator.spcOid,
5493 : : ent->key.rlocator.relNumber,
5494 : : ItemPointerGetBlockNumber(&ent->key.tid),
5495 : : ItemPointerGetOffsetNumber(&ent->key.tid),
5496 : : ent->cmin,
5497 : : ent->cmax
5498 : : );
5499 : : }
5500 : : }
5501 : : #endif
5502 : :
5503 : : /*
5504 : : * Apply a single mapping file to tuplecid_data.
5505 : : *
5506 : : * The mapping file has to have been verified to be a) committed b) for our
5507 : : * transaction c) applied in LSN order.
5508 : : */
5509 : : static void
5510 : 27 : ApplyLogicalMappingFile(HTAB *tuplecid_data, const char *fname)
5511 : : {
5512 : : char path[MAXPGPATH];
5513 : : int fd;
5514 : : ssize_t readBytes;
5515 : : LogicalRewriteMappingData map;
5516 : :
5517 : 27 : sprintf(path, "%s/%s", PG_LOGICAL_MAPPINGS_DIR, fname);
5518 : 27 : fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
5519 [ - + ]: 27 : if (fd < 0)
5520 [ # # ]: 0 : ereport(ERROR,
5521 : : (errcode_for_file_access(),
5522 : : errmsg("could not open file \"%s\": %m", path)));
5523 : :
5524 : : while (true)
5525 : 209 : {
5526 : : ReorderBufferTupleCidKey key;
5527 : : ReorderBufferTupleCidEnt *ent;
5528 : : ReorderBufferTupleCidEnt *new_ent;
5529 : : bool found;
5530 : :
5531 : : /* be careful about padding */
5532 : 236 : memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
5533 : :
5534 : : /* read all mappings till the end of the file */
5535 : 236 : pgstat_report_wait_start(WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ);
5536 : 236 : readBytes = read(fd, &map, sizeof(LogicalRewriteMappingData));
5537 : 236 : pgstat_report_wait_end();
5538 : :
5539 [ - + ]: 236 : if (readBytes < 0)
5540 [ # # ]: 0 : ereport(ERROR,
5541 : : (errcode_for_file_access(),
5542 : : errmsg("could not read file \"%s\": %m",
5543 : : path)));
5544 [ + + ]: 236 : else if (readBytes == 0) /* EOF */
5545 : 27 : break;
5546 [ - + ]: 209 : else if (readBytes != sizeof(LogicalRewriteMappingData))
5547 [ # # ]: 0 : ereport(ERROR,
5548 : : (errcode_for_file_access(),
5549 : : errmsg("could not read from file \"%s\": read %zd of %zu",
5550 : : path, readBytes,
5551 : : sizeof(LogicalRewriteMappingData))));
5552 : :
5553 : 209 : key.rlocator = map.old_locator;
5554 : 209 : ItemPointerCopy(&map.old_tid,
5555 : : &key.tid);
5556 : :
5557 : :
5558 : : ent = (ReorderBufferTupleCidEnt *)
5559 : 209 : hash_search(tuplecid_data, &key, HASH_FIND, NULL);
5560 : :
5561 : : /* no existing mapping, no need to update */
5562 [ - + ]: 209 : if (!ent)
5563 : 0 : continue;
5564 : :
5565 : 209 : key.rlocator = map.new_locator;
5566 : 209 : ItemPointerCopy(&map.new_tid,
5567 : : &key.tid);
5568 : :
5569 : : new_ent = (ReorderBufferTupleCidEnt *)
5570 : 209 : hash_search(tuplecid_data, &key, HASH_ENTER, &found);
5571 : :
5572 [ + + ]: 209 : if (found)
5573 : : {
5574 : : /*
5575 : : * Make sure the existing mapping makes sense. We sometime update
5576 : : * old records that did not yet have a cmax (e.g. pg_class' own
5577 : : * entry while rewriting it) during rewrites, so allow that.
5578 : : */
5579 : : Assert(ent->cmin == InvalidCommandId || ent->cmin == new_ent->cmin);
5580 : : Assert(ent->cmax == InvalidCommandId || ent->cmax == new_ent->cmax);
5581 : : }
5582 : : else
5583 : : {
5584 : : /* update mapping */
5585 : 203 : new_ent->cmin = ent->cmin;
5586 : 203 : new_ent->cmax = ent->cmax;
5587 : 203 : new_ent->combocid = ent->combocid;
5588 : : }
5589 : : }
5590 : :
5591 [ - + ]: 27 : if (CloseTransientFile(fd) != 0)
5592 [ # # ]: 0 : ereport(ERROR,
5593 : : (errcode_for_file_access(),
5594 : : errmsg("could not close file \"%s\": %m", path)));
5595 : 27 : }
5596 : :
5597 : :
5598 : : /*
5599 : : * Check whether the TransactionId 'xid' is in the pre-sorted array 'xip'.
5600 : : */
5601 : : static bool
5602 : 348 : TransactionIdInArray(TransactionId xid, TransactionId *xip, Size num)
5603 : : {
5604 : 348 : return bsearch(&xid, xip, num,
5605 : 348 : sizeof(TransactionId), xidComparator) != NULL;
5606 : : }
5607 : :
5608 : : /*
5609 : : * list_sort() comparator for sorting RewriteMappingFiles in LSN order.
5610 : : */
5611 : : static int
5612 : 36 : file_sort_by_lsn(const ListCell *a_p, const ListCell *b_p)
5613 : : {
5614 : 36 : RewriteMappingFile *a = (RewriteMappingFile *) lfirst(a_p);
5615 : 36 : RewriteMappingFile *b = (RewriteMappingFile *) lfirst(b_p);
5616 : :
5617 : 36 : return pg_cmp_u64(a->lsn, b->lsn);
5618 : : }
5619 : :
5620 : : /*
5621 : : * Apply any existing logical remapping files if there are any targeted at our
5622 : : * transaction for relid.
5623 : : */
5624 : : static void
5625 : 6 : UpdateLogicalMappings(HTAB *tuplecid_data, Oid relid, Snapshot snapshot)
5626 : : {
5627 : : DIR *mapping_dir;
5628 : : struct dirent *mapping_de;
5629 : 6 : List *files = NIL;
5630 : : ListCell *file;
5631 [ + - ]: 6 : Oid dboid = IsSharedRelation(relid) ? InvalidOid : MyDatabaseId;
5632 : :
5633 : 6 : mapping_dir = AllocateDir(PG_LOGICAL_MAPPINGS_DIR);
5634 [ + + ]: 558 : while ((mapping_de = ReadDir(mapping_dir, PG_LOGICAL_MAPPINGS_DIR)) != NULL)
5635 : : {
5636 : : Oid f_dboid;
5637 : : Oid f_relid;
5638 : : TransactionId f_mapped_xid;
5639 : : TransactionId f_create_xid;
5640 : : XLogRecPtr f_lsn;
5641 : : uint32 f_hi,
5642 : : f_lo;
5643 : : RewriteMappingFile *f;
5644 : :
5645 [ + + ]: 552 : if (strcmp(mapping_de->d_name, ".") == 0 ||
5646 [ + + ]: 546 : strcmp(mapping_de->d_name, "..") == 0)
5647 : 525 : continue;
5648 : :
5649 : : /* Ignore files that aren't ours */
5650 [ - + ]: 540 : if (strncmp(mapping_de->d_name, "map-", 4) != 0)
5651 : 0 : continue;
5652 : :
5653 [ - + ]: 540 : if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
5654 : : &f_dboid, &f_relid, &f_hi, &f_lo,
5655 : : &f_mapped_xid, &f_create_xid) != 6)
5656 [ # # ]: 0 : elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
5657 : :
5658 : 540 : f_lsn = ((uint64) f_hi) << 32 | f_lo;
5659 : :
5660 : : /* mapping for another database */
5661 [ - + ]: 540 : if (f_dboid != dboid)
5662 : 0 : continue;
5663 : :
5664 : : /* mapping for another relation */
5665 [ + + ]: 540 : if (f_relid != relid)
5666 : 60 : continue;
5667 : :
5668 : : /* did the creating transaction abort? */
5669 [ + + ]: 480 : if (!TransactionIdDidCommit(f_create_xid))
5670 : 132 : continue;
5671 : :
5672 : : /* not for our transaction */
5673 [ + + ]: 348 : if (!TransactionIdInArray(f_mapped_xid, snapshot->subxip, snapshot->subxcnt))
5674 : 321 : continue;
5675 : :
5676 : : /* ok, relevant, queue for apply */
5677 : 27 : f = palloc_object(RewriteMappingFile);
5678 : 27 : f->lsn = f_lsn;
5679 : 27 : strcpy(f->fname, mapping_de->d_name);
5680 : 27 : files = lappend(files, f);
5681 : : }
5682 : 6 : FreeDir(mapping_dir);
5683 : :
5684 : : /* sort files so we apply them in LSN order */
5685 : 6 : list_sort(files, file_sort_by_lsn);
5686 : :
5687 [ + - + + : 33 : foreach(file, files)
+ + ]
5688 : : {
5689 : 27 : RewriteMappingFile *f = (RewriteMappingFile *) lfirst(file);
5690 : :
5691 [ - + ]: 27 : elog(DEBUG1, "applying mapping: \"%s\" in %u", f->fname,
5692 : : snapshot->subxip[0]);
5693 : 27 : ApplyLogicalMappingFile(tuplecid_data, f->fname);
5694 : 27 : pfree(f);
5695 : : }
5696 : 6 : }
5697 : :
5698 : : /*
5699 : : * Lookup cmin/cmax of a tuple, during logical decoding where we can't rely on
5700 : : * combo CIDs.
5701 : : */
5702 : : bool
5703 : 815 : ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
5704 : : Snapshot snapshot,
5705 : : HeapTuple htup, Buffer buffer,
5706 : : CommandId *cmin, CommandId *cmax)
5707 : : {
5708 : : ReorderBufferTupleCidKey key;
5709 : : ReorderBufferTupleCidEnt *ent;
5710 : : ForkNumber forkno;
5711 : : BlockNumber blockno;
5712 : 815 : bool updated_mapping = false;
5713 : :
5714 : : /*
5715 : : * Return unresolved if tuplecid_data is not valid. That's because when
5716 : : * streaming in-progress transactions we may run into tuples with the CID
5717 : : * before actually decoding them. Think e.g. about INSERT followed by
5718 : : * TRUNCATE, where the TRUNCATE may not be decoded yet when applying the
5719 : : * INSERT. So in such cases, we assume the CID is from the future
5720 : : * command.
5721 : : */
5722 [ + + ]: 815 : if (tuplecid_data == NULL)
5723 : 14 : return false;
5724 : :
5725 : : /* be careful about padding */
5726 : 801 : memset(&key, 0, sizeof(key));
5727 : :
5728 : : Assert(!BufferIsLocal(buffer));
5729 : :
5730 : : /*
5731 : : * get relfilelocator from the buffer, no convenient way to access it
5732 : : * other than that.
5733 : : */
5734 : 801 : BufferGetTag(buffer, &key.rlocator, &forkno, &blockno);
5735 : :
5736 : : /* tuples can only be in the main fork */
5737 : : Assert(forkno == MAIN_FORKNUM);
5738 : : Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
5739 : :
5740 : 801 : ItemPointerCopy(&htup->t_self,
5741 : : &key.tid);
5742 : :
5743 : 807 : restart:
5744 : : ent = (ReorderBufferTupleCidEnt *)
5745 : 807 : hash_search(tuplecid_data, &key, HASH_FIND, NULL);
5746 : :
5747 : : /*
5748 : : * failed to find a mapping, check whether the table was rewritten and
5749 : : * apply mapping if so, but only do that once - there can be no new
5750 : : * mappings while we are in here since we have to hold a lock on the
5751 : : * relation.
5752 : : */
5753 [ + + + - ]: 807 : if (ent == NULL && !updated_mapping)
5754 : : {
5755 : 6 : UpdateLogicalMappings(tuplecid_data, htup->t_tableOid, snapshot);
5756 : : /* now check but don't update for a mapping again */
5757 : 6 : updated_mapping = true;
5758 : 6 : goto restart;
5759 : : }
5760 [ - + ]: 801 : else if (ent == NULL)
5761 : 0 : return false;
5762 : :
5763 [ + - ]: 801 : if (cmin)
5764 : 801 : *cmin = ent->cmin;
5765 [ + - ]: 801 : if (cmax)
5766 : 801 : *cmax = ent->cmax;
5767 : 801 : return true;
5768 : : }
5769 : :
5770 : : /*
5771 : : * Count invalidation messages of specified transaction.
5772 : : *
5773 : : * Returns number of messages, and msgs is set to the pointer of the linked
5774 : : * list for the messages.
5775 : : */
5776 : : uint32
5777 : 32 : ReorderBufferGetInvalidations(ReorderBuffer *rb, TransactionId xid,
5778 : : SharedInvalidationMessage **msgs)
5779 : : {
5780 : : ReorderBufferTXN *txn;
5781 : :
5782 : 32 : txn = ReorderBufferTXNByXid(rb, xid, false, NULL, InvalidXLogRecPtr,
5783 : : false);
5784 : :
5785 [ - + ]: 32 : if (txn == NULL)
5786 : 0 : return 0;
5787 : :
5788 : 32 : *msgs = txn->invalidations;
5789 : :
5790 : 32 : return txn->ninvalidations;
5791 : : }
|