From 8284d22491a35649e84a142bdde9761ecfd33cd7 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Mon, 21 Oct 2013 18:57:40 +0200
Subject: [PATCH] wal_decoding: Rewrite CommandId handling

CommandId's in postgres are compressed into one storage field using
the combocid mechanism. This is problematic for changeset extraction
of mixed DDL/DML transaction since we have to look at intermediate
catalog states.

We used to handle that by logging (relfilenode, ctid, cmin, cmax) for
every modified catalog tuple and then looking up the correct cmin,
cmax in an hash over the physical location. That doesn't suffice to
handle VACUUM FREEZE/CLUSTER which change the physical location of a
tuple.
Instead store both cmax, cmin for catalog tuples by increasing t_hoff
of HeapTupleHeaders and storing cmax there. Cmin is stored at the
current location.
We detect such tuples by having HEAP_MOVED_OFF | HEAP_MOVED_IN
set. That combination could not exist yet.
---
 src/backend/access/common/heaptuple.c           |  46 +++
 src/backend/access/common/tupdesc.c             |   9 +-
 src/backend/access/heap/heapam.c                | 443 +++++++++++++++---------
 src/backend/access/heap/rewriteheap.c           |   6 +
 src/backend/access/heap/tuptoaster.c            |  24 ++
 src/backend/access/rmgrdesc/heapdesc.c          |   9 -
 src/backend/access/rmgrdesc/xactdesc.c          |   7 +
 src/backend/access/transam/xact.c               |  47 +++
 src/backend/commands/cluster.c                  |   7 +
 src/backend/replication/logical/decode.c        |  43 ++-
 src/backend/replication/logical/reorderbuffer.c | 227 +-----------
 src/backend/replication/logical/snapbuild.c     |  41 +--
 src/backend/utils/cache/inval.c                 |  21 +-
 src/backend/utils/cache/relcache.c              |  21 ++
 src/backend/utils/time/combocid.c               |  49 ++-
 src/backend/utils/time/tqual.c                  |  74 ++--
 src/include/access/heapam_xlog.h                |  25 +-
 src/include/access/htup_details.h               |  42 ++-
 src/include/access/tupdesc.h                    |   1 +
 src/include/access/xact.h                       |   8 +
 src/include/replication/reorderbuffer.h         |   3 -
 src/include/replication/snapbuild.h             |   4 +-
 src/include/utils/tqual.h                       |  11 +-
 src/tools/pgindent/typedefs.list                |   2 +-
 24 files changed, 601 insertions(+), 569 deletions(-)

diff --git a/src/backend/access/common/heaptuple.c b/src/backend/access/common/heaptuple.c
index e39b977..9e4297a 100644
--- a/src/backend/access/common/heaptuple.c
+++ b/src/backend/access/common/heaptuple.c
@@ -679,6 +679,9 @@ heap_form_tuple(TupleDesc tupleDescriptor,
 	if (hasnull)
 		len += BITMAPLEN(numberOfAttributes);
 
+	if (tupleDescriptor->tdhaswidecid)
+		len += sizeof(CommandId);
+
 	if (tupleDescriptor->tdhasoid)
 		len += sizeof(Oid);
 
@@ -712,6 +715,8 @@ heap_form_tuple(TupleDesc tupleDescriptor,
 
 	if (tupleDescriptor->tdhasoid)		/* else leave infomask = 0 */
 		td->t_infomask = HEAP_HASOID;
+	if (tupleDescriptor->tdhaswidecid)
+		td->t_infomask |= HEAP_HAS_WIDE_CID;
 
 	heap_fill_tuple(tupleDescriptor,
 					values,
@@ -1537,3 +1542,44 @@ minimal_tuple_from_heap_tuple(HeapTuple htup)
 	result->t_len = len;
 	return result;
 }
+
+/*
+ * HeapTupleHeaderSetCmax
+ * 		Set Cmax of a HeapTupleHeader, regardless wether it's a wide
+ *		(storing cmin and cmax simultanously) tuple or not.
+ */
+extern void
+HeapTupleHeaderSetCmax(HeapTupleHeader tup, CommandId cid, bool iscombo)
+{
+	Assert(!HeapTupleHeaderHasMoved(tup));
+
+	if (tup->t_infomask & HEAP_HAS_WIDE_CID)
+	{
+		CommandId *l;
+
+		/* HeapTupleHeaderAdjustCmax should have set it to false */
+		Assert(!iscombo);
+
+		if (tup->t_infomask & HEAP_HASOID)
+			l = (CommandId *) ((char *)tup +
+								tup->t_hoff -
+								sizeof(Oid) -
+								sizeof(CommandId));
+		else
+			l = (CommandId *) ((char *)tup +
+								tup->t_hoff -
+								sizeof(CommandId));
+		*l = cid;
+		tup->t_infomask &= ~HEAP_COMBOCID;
+	}
+	else if (iscombo)
+	{
+		tup->t_choice.t_heap.t_field3.t_cid = cid;
+		tup->t_infomask |= HEAP_COMBOCID;
+	}
+	else
+	{
+		tup->t_choice.t_heap.t_field3.t_cid = cid;
+		tup->t_infomask &= ~HEAP_COMBOCID;
+	}
+}
diff --git a/src/backend/access/common/tupdesc.c b/src/backend/access/common/tupdesc.c
index 11c31d8..0bbc337 100644
--- a/src/backend/access/common/tupdesc.c
+++ b/src/backend/access/common/tupdesc.c
@@ -91,6 +91,7 @@ CreateTemplateTupleDesc(int natts, bool hasoid)
 	desc->tdtypeid = RECORDOID;
 	desc->tdtypmod = -1;
 	desc->tdhasoid = hasoid;
+	desc->tdhaswidecid = false;
 	desc->tdrefcount = -1;		/* assume not reference-counted */
 
 	return desc;
@@ -124,6 +125,7 @@ CreateTupleDesc(int natts, bool hasoid, Form_pg_attribute *attrs)
 	desc->tdtypeid = RECORDOID;
 	desc->tdtypmod = -1;
 	desc->tdhasoid = hasoid;
+	desc->tdhaswidecid = false;
 	desc->tdrefcount = -1;		/* assume not reference-counted */
 
 	return desc;
@@ -143,6 +145,7 @@ CreateTupleDescCopy(TupleDesc tupdesc)
 	int			i;
 
 	desc = CreateTemplateTupleDesc(tupdesc->natts, tupdesc->tdhasoid);
+	desc->tdhaswidecid = tupdesc->tdhaswidecid;
 
 	for (i = 0; i < desc->natts; i++)
 	{
@@ -150,9 +153,9 @@ CreateTupleDescCopy(TupleDesc tupdesc)
 		desc->attrs[i]->attnotnull = false;
 		desc->attrs[i]->atthasdef = false;
 	}
-
 	desc->tdtypeid = tupdesc->tdtypeid;
 	desc->tdtypmod = tupdesc->tdtypmod;
+	desc->tdhaswidecid = tupdesc->tdhaswidecid;
 
 	return desc;
 }
@@ -180,6 +183,7 @@ CreateTupleDescCopyExtend(TupleDesc tupdesc, int moreatts)
 	Assert(moreatts >= 0);
 
 	desc = CreateTemplateTupleDesc(src_natts + moreatts, tupdesc->tdhasoid);
+	desc->tdhaswidecid = tupdesc->tdhaswidecid;
 
 	for (i = 0; i < src_natts; i++)
 	{
@@ -204,6 +208,7 @@ CreateTupleDescCopyConstr(TupleDesc tupdesc)
 	int			i;
 
 	desc = CreateTemplateTupleDesc(tupdesc->natts, tupdesc->tdhasoid);
+	desc->tdhaswidecid = tupdesc->tdhaswidecid;
 
 	for (i = 0; i < desc->natts; i++)
 	{
@@ -352,6 +357,8 @@ equalTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
 		return false;
 	if (tupdesc1->tdhasoid != tupdesc2->tdhasoid)
 		return false;
+	if (tupdesc1->tdhaswidecid != tupdesc2->tdhaswidecid)
+		return false;
 
 	for (i = 0; i < tupdesc1->natts; i++)
 	{
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 87a752c..e08a122 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -85,7 +85,8 @@ static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
 					TransactionId xid, CommandId cid, int options);
 static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
 				Buffer newbuf, HeapTuple oldtup,
-				HeapTuple newtup, HeapTuple old_idx_tup,
+				HeapTuple newtup, CommandId cid,
+				HeapTuple old_idx_tup,
 				bool all_visible_cleared, bool new_all_visible_cleared);
 static void HeapSatisfiesHOTandKeyUpdate(Relation relation,
 						  Bitmapset *hot_attrs,
@@ -110,7 +111,6 @@ static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
 static bool ConditionalMultiXactIdWait(MultiXactId multi,
 						   MultiXactStatus status, int *remaining,
 						   uint16 infomask);
-static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
 static HeapTuple ExtractKeyTuple(Relation rel, HeapTuple tup);
 
 
@@ -2116,11 +2116,11 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 		xl_heap_insert xlrec;
 		xl_heap_header xlhdr;
 		XLogRecPtr	recptr;
-		XLogRecData rdata[4];
+		XLogRecData	rdata[5];
 		Page		page = BufferGetPage(buffer);
 		uint8		info = XLOG_HEAP_INSERT;
 		bool		need_tuple_data;
-
+		int			last_rdata;
 		/*
 		 * For logical replication, we need the tuple even if we're doing a
 		 * full page write, so make sure to log it separately. (XXX We could
@@ -2130,8 +2130,6 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 		 * properly decode, so log that as well.
 		 */
 		need_tuple_data = RelationIsLogicallyLogged(relation);
-		if (RelationIsAccessibleInLogicalDecoding(relation))
-			log_heap_new_cid(relation, heaptup);
 
 		xlrec.flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
 		xlrec.target.node = relation->rd_node;
@@ -2163,6 +2161,8 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 		rdata[2].buffer_std = true;
 		rdata[2].next = NULL;
 
+		last_rdata = 2;
+
 		/*
 		 * Make a separate rdata entry for the tuple's buffer if we're
 		 * doing logical decoding, so that an eventual FPW doesn't
@@ -2170,18 +2170,36 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 		 */
 		if (need_tuple_data)
 		{
-			rdata[2].next = &(rdata[3]);
+			rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+			last_rdata += 1;
 
-			rdata[3].data = NULL;
-			rdata[3].len = 0;
-			rdata[3].buffer = buffer;
-			rdata[3].buffer_std = true;
-			rdata[3].next = NULL;
+			rdata[last_rdata].data = NULL;
+			rdata[last_rdata].len = 0;
+			rdata[last_rdata].buffer = buffer;
+			rdata[last_rdata].buffer_std = true;
+			rdata[last_rdata].next = NULL;
 
 			xlrec.flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
 		}
 
 		/*
+		 * Log the current commandid for catalog tuples when logical
+		 * decoding is enabled.
+		 */
+		if (RelationIsAccessibleInLogicalDecoding(relation))
+		{
+			rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+			last_rdata += 1;
+
+			rdata[last_rdata].data = (void *) &cid;
+			rdata[last_rdata].len = sizeof(CommandId);
+			rdata[last_rdata].buffer = InvalidBuffer;
+			rdata[last_rdata].next = NULL;
+
+			xlrec.flags |= XLOG_HEAP_CONTAINS_CID;
+		}
+
+		/*
 		 * If this is the single and first tuple on page, we can reinit the
 		 * page instead of restoring the whole thing.  Set flag, and hide
 		 * buffer references from XLogInsert.
@@ -2190,7 +2208,8 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 			PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
 		{
 			info |= XLOG_HEAP_INIT_PAGE;
-			rdata[1].buffer = rdata[2].buffer = rdata[3].buffer = InvalidBuffer;
+			rdata[1].buffer = rdata[2].buffer = rdata[3].buffer =
+				rdata[4].buffer = InvalidBuffer;
 		}
 
 		recptr = XLogInsert(RM_HEAP_ID, info, rdata);
@@ -2228,6 +2247,47 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 }
 
 /*
+ * Convert a normal HeapTuple storing only either cmin, cmax or a
+ * combocid (c.f. combocid.c) into one storing both, cmin and
+ * cmax. That's required for decoding mixed DDL/DML transactions.
+ */
+static HeapTuple
+heap_prepare_system_tuple(Relation relation, HeapTuple tup)
+{
+	TupleDesc	tupleDesc;
+	bool		isnull[MaxHeapAttributeNumber];
+	Datum		values[MaxHeapAttributeNumber];
+	HeapTuple	newtup;
+	size_t		hoff;
+
+	Assert(!HeapTupleHeaderHasWideCid(tup->t_data));
+
+	tupleDesc = RelationGetDescr(relation);
+
+	Assert(tupleDesc->tdhaswidecid);
+
+	heap_deform_tuple(tup, tupleDesc, values, isnull);
+	newtup = heap_form_tuple(tupleDesc, values, isnull);
+
+	Assert(HeapTupleHeaderHasWideCid(newtup->t_data));
+
+	hoff = newtup->t_data->t_hoff;
+	memcpy(newtup->t_data, tup->t_data, offsetof(HeapTupleHeaderData, t_bits));
+	newtup->t_data->t_hoff = hoff;
+
+	newtup->t_data->t_infomask |= HEAP_HAS_WIDE_CID;
+
+	if (tup->t_data->t_infomask & HEAP_HASOID)
+		HeapTupleHeaderSetOid(newtup->t_data, HeapTupleHeaderGetOid(tup->t_data));
+
+	HeapTupleHeaderSetCmin(newtup->t_data, HeapTupleHeaderGetRawCommandId(tup->t_data));
+
+	newtup->t_tableOid = tup->t_tableOid;
+
+	return newtup;
+}
+
+/*
  * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
  * tuple header fields, assigns an OID, and toasts the tuple if necessary.
  * Returns a toasted version of the tuple if it was toasted, or the original
@@ -2262,8 +2322,16 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
 		Assert(!(tup->t_data->t_infomask & HEAP_HASOID));
 	}
 
-	tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
-	tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
+	if (RelationIsAccessibleInLogicalDecoding(relation) &&
+	    !HeapTupleHeaderHasWideCid(tup->t_data))
+	{
+		if (IsSystemRelation(relation))
+			elog(WARNING, "to be inserted system tuple does not have wide cids");
+		tup = heap_prepare_system_tuple(relation, tup);
+	}
+
+	tup->t_data->t_infomask &= ~HEAP_XACT_MASK;
+	tup->t_data->t_infomask2 &= ~HEAP2_XACT_MASK;
 	tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
 	if (options & HEAP_INSERT_FROZEN)
 	{
@@ -2272,6 +2340,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
 	}
 	else
 		HeapTupleHeaderSetXmin(tup->t_data, xid);
+	HeapTupleHeaderSetCmax(tup->t_data, InvalidCommandId, false);
 	HeapTupleHeaderSetCmin(tup->t_data, cid);
 	HeapTupleHeaderSetXmax(tup->t_data, 0);		/* for cleanliness */
 	tup->t_tableOid = RelationGetRelid(relation);
@@ -2317,7 +2386,6 @@ heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples,
 	bool		needwal;
 	Size		saveFreeSpace;
 	bool		need_tuple_data = RelationIsLogicallyLogged(relation);
-	bool		need_cids = RelationIsAccessibleInLogicalDecoding(relation);
 
 	needwal = !(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation);
 	saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
@@ -2404,12 +2472,13 @@ heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples,
 		{
 			XLogRecPtr	recptr;
 			xl_heap_multi_insert *xlrec;
-			XLogRecData rdata[3];
+			XLogRecData	rdata[4];
 			uint8		info = XLOG_HEAP2_MULTI_INSERT;
 			char	   *tupledata;
 			int			totaldatalen;
 			char	   *scratchptr = scratch;
 			bool		init;
+			int			last_rdata;
 
 			/*
 			 * If the page was previously empty, we can reinit the page
@@ -2466,13 +2535,6 @@ heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples,
 					   datalen);
 				tuphdr->datalen = datalen;
 				scratchptr += datalen;
-
-				/*
-				 * We don't use heap_multi_insert for catalog tuples yet, but
-				 * better be prepared...
-				 */
-				if (need_cids)
-					log_heap_new_cid(relation, heaptup);
 			}
 			totaldatalen = scratchptr - tupledata;
 			Assert((scratchptr - scratch) < BLCKSZ);
@@ -2488,6 +2550,8 @@ heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples,
 			rdata[1].buffer_std = true;
 			rdata[1].next = NULL;
 
+			last_rdata = 1;
+
 			/*
 			 * Make a separate rdata entry for the tuple's buffer if
 			 * we're doing logical decoding, so that an eventual FPW
@@ -2495,23 +2559,42 @@ heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples,
 			 */
 			if (need_tuple_data)
 			{
-				rdata[1].next = &(rdata[2]);
-
-				rdata[2].data = NULL;
-				rdata[2].len = 0;
-				rdata[2].buffer = buffer;
-				rdata[2].buffer_std = true;
-				rdata[2].next = NULL;
+				rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+				last_rdata++;
+
+				rdata[last_rdata].data = NULL;
+				rdata[last_rdata].len = 0;
+				rdata[last_rdata].buffer = buffer;
+				rdata[last_rdata].buffer_std = true;
+				rdata[last_rdata].next = NULL;
 				xlrec->flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
 			}
 
 			/*
+			 * Log the current CommandId for catalog tuples when
+			 * logical decoding is enabled.
+			 */
+			if (RelationIsAccessibleInLogicalDecoding(relation))
+			{
+				rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+				last_rdata += 1;
+
+				rdata[last_rdata].data = (void *) &cid;
+				rdata[last_rdata].len = sizeof(CommandId);
+				rdata[last_rdata].buffer = InvalidBuffer;
+				rdata[last_rdata].next = NULL;
+
+				xlrec->flags |= XLOG_HEAP_CONTAINS_CID;
+			}
+
+			/*
 			 * If we're going to reinitialize the whole page using the WAL
 			 * record, hide buffer reference from XLogInsert.
 			 */
 			if (init)
 			{
-				rdata[1].buffer = rdata[2].buffer = InvalidBuffer;
+				rdata[1].buffer = rdata[2].buffer = rdata[3].buffer
+					= InvalidBuffer;
 				info |= XLOG_HEAP_INIT_PAGE;
 			}
 
@@ -2672,6 +2755,13 @@ heap_delete(Relation relation, ItemPointer tid,
 	tp.t_len = ItemIdGetLength(lp);
 	tp.t_self = *tid;
 
+	if (RelationIsAccessibleInLogicalDecoding(relation) &&
+	    !HeapTupleHeaderHasWideCid(tp.t_data) &&
+	    TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tp.t_data)))
+	{
+		elog(ERROR, "to be delete tuple does not have wide cids");
+	}
+
 l1:
 	result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
 
@@ -2848,7 +2938,8 @@ l1:
 							  &new_xmax, &new_infomask, &new_infomask2);
 
 	/* store transaction information of xact deleting the tuple */
-	tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
+	tp.t_data->t_infomask &= ~HEAP_XMAX_BITS;
+	HeapTupleHeaderClearMoved(tp.t_data);
 	tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 	tp.t_data->t_infomask |= new_infomask;
 	tp.t_data->t_infomask2 |= new_infomask2;
@@ -2865,11 +2956,8 @@ l1:
 	{
 		xl_heap_delete xlrec;
 		XLogRecPtr	recptr;
-		XLogRecData rdata[4];
-
-		/* For logical decode we need combocids to properly decode the catalog */
-		if (RelationIsAccessibleInLogicalDecoding(relation))
-			log_heap_new_cid(relation, &tp);
+		XLogRecData	rdata[5];
+		int			last_rdata;
 
 		xlrec.flags = all_visible_cleared ? XLOG_HEAP_ALL_VISIBLE_CLEARED : 0;
 		xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
@@ -2888,6 +2976,8 @@ l1:
 		rdata[1].buffer_std = true;
 		rdata[1].next = NULL;
 
+		last_rdata = 1;
+
 		/*
 		 * Log primary key of the deleted tuple
 		 */
@@ -2914,6 +3004,24 @@ l1:
 			rdata[3].next = NULL;
 
 			xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_KEY;
+			last_rdata = 3;
+		}
+
+		/*
+		 * Log the current commandid for catalog tuples when logical
+		 * decoding is enabled.
+		 */
+		if (RelationIsAccessibleInLogicalDecoding(relation))
+		{
+			rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+			last_rdata += 1;
+
+			rdata[last_rdata].data = (void *) &cid;
+			rdata[last_rdata].len = sizeof(CommandId);
+			rdata[last_rdata].buffer = InvalidBuffer;
+			rdata[last_rdata].next = NULL;
+
+			xlrec.flags |= XLOG_HEAP_CONTAINS_CID;
 		}
 
 		recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE, rdata);
@@ -3143,6 +3251,13 @@ heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
 		Assert(!(newtup->t_data->t_infomask & HEAP_HASOID));
 	}
 
+	if (RelationIsAccessibleInLogicalDecoding(relation) &&
+	    !HeapTupleHeaderHasWideCid(oldtup.t_data) &&
+	    TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(oldtup.t_data)))
+	{
+		elog(ERROR, "to be updated tuple does not have wide cids");
+	}
+
 	/*
 	 * If we're not updating any "key" column, we can grab a weaker lock type.
 	 * This allows for more concurrency when we are running simultaneously
@@ -3182,6 +3297,17 @@ heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
 	}
 
 	/*
+	 * Note: below this point, heaptup is the data we actually intend
+	 * to store into the relation; newtup is the caller's original
+	 * untoasted data.
+	 */
+	if (RelationIsAccessibleInLogicalDecoding(relation) &&
+	    !HeapTupleHeaderHasWideCid(newtup->t_data))
+		heaptup = heap_prepare_system_tuple(relation, newtup);
+	else
+		heaptup = newtup;
+
+	/*
 	 * Note: beyond this point, use oldtup not otid to refer to old tuple.
 	 * otid may very well point at newtup->t_self, which we will overwrite
 	 * with the new tuple's location, so there's great risk of confusion if we
@@ -3462,13 +3588,15 @@ l2:
 	 * Prepare the new tuple with the appropriate initial values of Xmin and
 	 * Xmax, as well as initial infomask bits as computed above.
 	 */
-	newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
-	newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
-	HeapTupleHeaderSetXmin(newtup->t_data, xid);
-	HeapTupleHeaderSetCmin(newtup->t_data, cid);
-	newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
-	newtup->t_data->t_infomask2 |= infomask2_new_tuple;
-	HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
+	heaptup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
+	heaptup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
+	HeapTupleHeaderSetXmin(heaptup->t_data, xid);
+	/* overwrite if we're not using wide cids */
+	HeapTupleHeaderSetCmax(heaptup->t_data, InvalidCommandId, false);
+	HeapTupleHeaderSetCmin(heaptup->t_data, cid);
+	heaptup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
+	heaptup->t_data->t_infomask2 |= infomask2_new_tuple;
+	HeapTupleHeaderSetXmax(heaptup->t_data, xmax_new_tuple);
 
 	/*
 	 * Replace cid with a combo cid if necessary.  Note that we already put
@@ -3492,22 +3620,24 @@ l2:
 	{
 		/* toast table entries should never be recursively toasted */
 		Assert(!HeapTupleHasExternal(&oldtup));
-		Assert(!HeapTupleHasExternal(newtup));
+		Assert(!HeapTupleHasExternal(heaptup));
 		need_toast = false;
 	}
 	else
 		need_toast = (HeapTupleHasExternal(&oldtup) ||
-					  HeapTupleHasExternal(newtup) ||
-					  newtup->t_len > TOAST_TUPLE_THRESHOLD);
+					  HeapTupleHasExternal(heaptup) ||
+					  heaptup->t_len > TOAST_TUPLE_THRESHOLD);
 
 	pagefree = PageGetHeapFreeSpace(page);
 
-	newtupsize = MAXALIGN(newtup->t_len);
+	newtupsize = MAXALIGN(heaptup->t_len);
 
 	if (need_toast || newtupsize > pagefree)
 	{
 		/* Clear obsolete visibility flags ... */
-		oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
+		oldtup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
+		HeapTupleHeaderClearMoved(oldtup.t_data);
+
 		oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 		HeapTupleClearHotUpdated(&oldtup);
 		/* ... and store info about transaction updating this tuple */
@@ -3523,19 +3653,13 @@ l2:
 
 		/*
 		 * Let the toaster do its thing, if needed.
-		 *
-		 * Note: below this point, heaptup is the data we actually intend to
-		 * store into the relation; newtup is the caller's original untoasted
-		 * data.
 		 */
 		if (need_toast)
 		{
 			/* Note we always use WAL and FSM during updates */
-			heaptup = toast_insert_or_update(relation, newtup, &oldtup, 0);
+			heaptup = toast_insert_or_update(relation, heaptup, &oldtup, 0);
 			newtupsize = MAXALIGN(heaptup->t_len);
 		}
-		else
-			heaptup = newtup;
 
 		/*
 		 * Now, do we need a new page for the tuple, or not?  This is a bit
@@ -3591,7 +3715,6 @@ l2:
 		/* No TOAST work needed, and it'll fit on same page */
 		already_marked = false;
 		newbuf = buffer;
-		heaptup = newtup;
 	}
 
 	/*
@@ -3669,7 +3792,9 @@ l2:
 	if (!already_marked)
 	{
 		/* Clear obsolete visibility flags ... */
-		oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
+		oldtup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
+		HeapTupleHeaderClearMoved(oldtup.t_data);
+
 		oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 		/* ... and store info about transaction updating this tuple */
 		Assert(TransactionIdIsValid(xmax_old_tuple));
@@ -3707,16 +3832,9 @@ l2:
 	{
 		XLogRecPtr	recptr;
 
-		/* For logical decode we need combocids to properly decode the catalog */
-		if (RelationIsAccessibleInLogicalDecoding(relation))
-		{
-			log_heap_new_cid(relation, &oldtup);
-			log_heap_new_cid(relation, heaptup);
-		}
-
 		recptr = log_heap_update(relation, buffer,
 								 newbuf, &oldtup, heaptup,
-								 old_idx_tuple,
+								 cid, old_idx_tuple,
 								 all_visible_cleared,
 								 all_visible_cleared_new);
 		if (newbuf != buffer)
@@ -5306,7 +5424,7 @@ heap_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
 	 * Old-style VACUUM FULL is gone, but we have to keep this code as long as
 	 * we support having MOVED_OFF/MOVED_IN tuples in the database.
 	 */
-	if (tuple->t_infomask & HEAP_MOVED)
+	if (HeapTupleHeaderHasMoved(tuple))
 	{
 		xid = HeapTupleHeaderGetXvac(tuple);
 		if (TransactionIdIsNormal(xid) &&
@@ -5317,7 +5435,7 @@ heap_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
 			 * have failed; whereas a non-dead MOVED_IN tuple must mean the
 			 * xvac transaction succeeded.
 			 */
-			if (tuple->t_infomask & HEAP_MOVED_OFF)
+			if (HeapTupleHeaderHasMovedOff(tuple))
 				HeapTupleHeaderSetXvac(tuple, InvalidTransactionId);
 			else
 				HeapTupleHeaderSetXvac(tuple, FrozenTransactionId);
@@ -5642,7 +5760,7 @@ heap_tuple_needs_freeze(HeapTupleHeader tuple, TransactionId cutoff_xid,
 		}
 	}
 
-	if (tuple->t_infomask & HEAP_MOVED)
+	if (HeapTupleHeaderHasMoved(tuple))
 	{
 		xid = HeapTupleHeaderGetXvac(tuple);
 		if (TransactionIdIsNormal(xid) &&
@@ -5733,7 +5851,7 @@ HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple,
 	TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
 	TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
-	if (tuple->t_infomask & HEAP_MOVED)
+	if (HeapTupleHeaderHasMoved(tuple))
 	{
 		if (TransactionIdPrecedes(*latestRemovedXid, xvac))
 			*latestRemovedXid = xvac;
@@ -5982,7 +6100,7 @@ log_heap_visible(RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer,
 static XLogRecPtr
 log_heap_update(Relation reln, Buffer oldbuf,
 				Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
-				HeapTuple idx_tuple,
+				CommandId cid, HeapTuple idx_tuple,
 				bool all_visible_cleared, bool new_all_visible_cleared)
 {
 	xl_heap_update xlrec;
@@ -5990,9 +6108,10 @@ log_heap_update(Relation reln, Buffer oldbuf,
 	xl_heap_header_len xlhdr_idx;
 	uint8		info;
 	XLogRecPtr	recptr;
-	XLogRecData rdata[7];
+	XLogRecData	rdata[8];
 	Page		page = BufferGetPage(newbuf);
 	bool		need_tuple_data = RelationIsLogicallyLogged(reln);
+	int			last_rdata;
 
 	/* Caller should not call me on a non-WAL-logged relation */
 	Assert(RelationNeedsWAL(reln));
@@ -6050,19 +6169,22 @@ log_heap_update(Relation reln, Buffer oldbuf,
 	rdata[3].buffer_std = true;
 	rdata[3].next = NULL;
 
+	last_rdata = 3;
+
 	/*
 	 * separate storage for the buffer reference of the new page in the
 	 * wal_level >= logical case
 	*/
 	if(need_tuple_data)
 	{
-		rdata[3].next = &(rdata[4]);
+		rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+		last_rdata++;
 
-		rdata[4].data = NULL,
-		rdata[4].len = 0;
-		rdata[4].buffer = newbuf;
-		rdata[4].buffer_std = true;
-		rdata[4].next = NULL;
+		rdata[last_rdata].data = NULL,
+		rdata[last_rdata].len = 0;
+		rdata[last_rdata].buffer = newbuf;
+		rdata[last_rdata].buffer_std = true;
+		rdata[last_rdata].next = NULL;
 		xlrec.flags |= XLOG_HEAP_CONTAINS_NEW_TUPLE;
 
 		/* candidate key changed and we have a candidate key */
@@ -6074,24 +6196,45 @@ log_heap_update(Relation reln, Buffer oldbuf,
 			xlhdr_idx.header.t_hoff = idx_tuple->t_data->t_hoff;
 			xlhdr_idx.t_len = idx_tuple->t_len;
 
-			rdata[4].next = &(rdata[5]);
-			rdata[5].data = (char *) &xlhdr_idx;
-			rdata[5].len = SizeOfHeapHeaderLen;
-			rdata[5].buffer = InvalidBuffer;
-			rdata[5].next = &(rdata[6]);
+			rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+			last_rdata++;
+
+			rdata[last_rdata].data = (char *) &xlhdr_idx;
+			rdata[last_rdata].len = SizeOfHeapHeaderLen;
+			rdata[last_rdata].buffer = InvalidBuffer;
+
+			rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+			last_rdata++;
 
 			/* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
-			rdata[6].data = (char *) idx_tuple->t_data
+			rdata[last_rdata].data = (char *) idx_tuple->t_data
 				+ offsetof(HeapTupleHeaderData, t_bits);
-			rdata[6].len = idx_tuple->t_len
+			rdata[last_rdata].len = idx_tuple->t_len
 				- offsetof(HeapTupleHeaderData, t_bits);
-			rdata[6].buffer = InvalidBuffer;
-			rdata[6].next = NULL;
+			rdata[last_rdata].buffer = InvalidBuffer;
+			rdata[last_rdata].next = NULL;
 
 			xlrec.flags |= XLOG_HEAP_CONTAINS_OLD_KEY;
 		}
 	}
 
+	/*
+	 * Log the current commandid for catalog tuples when logical
+	 * decoding is enabled.
+	 */
+	if (RelationIsAccessibleInLogicalDecoding(reln))
+	{
+		rdata[last_rdata].next = &(rdata[last_rdata + 1]);
+		last_rdata += 1;
+
+		rdata[last_rdata].data = (void *) &cid;
+		rdata[last_rdata].len = sizeof(CommandId);
+		rdata[last_rdata].buffer = InvalidBuffer;
+		rdata[last_rdata].next = NULL;
+
+		xlrec.flags |= XLOG_HEAP_CONTAINS_CID;
+	}
+
 	/* If new tuple is the single and first tuple on page... */
 	if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
 		PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
@@ -6209,75 +6352,6 @@ log_newpage_buffer(Buffer buffer)
 }
 
 /*
- * Perform XLogInsert of a XLOG_HEAP2_NEW_CID record
- *
- * This is only used in wal_level >= WAL_LEVEL_LOGICAL
- */
-static XLogRecPtr
-log_heap_new_cid(Relation relation, HeapTuple tup)
-{
-	xl_heap_new_cid xlrec;
-
-	XLogRecPtr	recptr;
-	XLogRecData rdata[1];
-	HeapTupleHeader hdr = tup->t_data;
-
-	Assert(ItemPointerIsValid(&tup->t_self));
-	Assert(tup->t_tableOid != InvalidOid);
-
-	xlrec.top_xid = GetTopTransactionId();
-	xlrec.target.node = relation->rd_node;
-	xlrec.target.tid = tup->t_self;
-
-	/*
-	 * if the tuple got inserted & deleted in the same TX we definitely have a
-	 * combocid, set cmin and cmax.
-	 */
-	if (hdr->t_infomask & HEAP_COMBOCID)
-	{
-		Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
-		Assert(!(hdr->t_infomask & HEAP_XMIN_INVALID));
-		xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
-		xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
-		xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
-	}
-	/* No combocid, so only cmin or cmax can be set by this TX */
-	else
-	{
-		/*
-		 * tuple inserted.
-		 *
-		 * We need to check for LOCK ONLY because multixacts might be
-		 * transferred to the new tuple in case of FOR KEY SHARE
-		 * updates.
-		 */
-		if (hdr->t_infomask & HEAP_XMAX_INVALID ||
-		    hdr->t_infomask & HEAP_XMAX_LOCK_ONLY)
-		{
-			xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
-			xlrec.cmax = InvalidCommandId;
-		}
-		/* tuple from a different tx updated or deleted */
-		else
-		{
-			xlrec.cmin = InvalidCommandId;
-			xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
-
-		}
-		xlrec.combocid = InvalidCommandId;
-	}
-
-	rdata[0].data = (char *) &xlrec;
-	rdata[0].len = SizeOfHeapNewCid;
-	rdata[0].buffer = InvalidBuffer;
-	rdata[0].next = NULL;
-
-	recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID, rdata);
-
-	return recptr;
-}
-
-/*
  * Build a heap tuple representing the primary or candidate key of the
  * the passed in tuple tp.
  *
@@ -6683,6 +6757,7 @@ heap_xlog_delete(XLogRecPtr lsn, XLogRecord *record)
 	ItemId		lp = NULL;
 	HeapTupleHeader htup;
 	BlockNumber blkno;
+	CommandId	cid = FirstCommandId;
 
 	blkno = ItemPointerGetBlockNumber(&(xlrec->target.tid));
 
@@ -6711,6 +6786,13 @@ heap_xlog_delete(XLogRecPtr lsn, XLogRecord *record)
 	buffer = XLogReadBuffer(xlrec->target.node, blkno, false);
 	if (!BufferIsValid(buffer))
 		return;
+
+	/* CommandId is stored at the end of record data */
+	if (xlrec->flags & XLOG_HEAP_CONTAINS_CID)
+		memcpy(&cid,
+		       (char *) xlrec + record->xl_len - sizeof(CommandId),
+		       sizeof(CommandId));
+
 	page = (Page) BufferGetPage(buffer);
 
 	if (lsn <= PageGetLSN(page))	/* changes are applied */
@@ -6728,13 +6810,15 @@ heap_xlog_delete(XLogRecPtr lsn, XLogRecord *record)
 
 	htup = (HeapTupleHeader) PageGetItem(page, lp);
 
-	htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
+	htup->t_infomask &= ~HEAP_XMAX_BITS;
+	HeapTupleHeaderClearMoved(htup);
+
 	htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 	HeapTupleHeaderClearHotUpdated(htup);
 	fix_infomask_from_infobits(xlrec->infobits_set,
 							   &htup->t_infomask, &htup->t_infomask2);
 	HeapTupleHeaderSetXmax(htup, xlrec->xmax);
-	HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
+	HeapTupleHeaderSetCmax(htup, cid, false);
 
 	/* Mark the page as a candidate for pruning */
 	PageSetPrunable(page, record->xl_xid);
@@ -6766,6 +6850,7 @@ heap_xlog_insert(XLogRecPtr lsn, XLogRecord *record)
 	uint32		newlen;
 	Size		freespace;
 	BlockNumber blkno;
+	CommandId	cid = FirstCommandId;
 
 	blkno = ItemPointerGetBlockNumber(&(xlrec->target.tid));
 
@@ -6818,6 +6903,17 @@ heap_xlog_insert(XLogRecPtr lsn, XLogRecord *record)
 		elog(PANIC, "heap_insert_redo: invalid max offset number");
 
 	newlen = record->xl_len - SizeOfHeapInsert - SizeOfHeapHeader;
+
+	/* CommandId is stored at the end of record data */
+	if (xlrec->flags & XLOG_HEAP_CONTAINS_CID)
+	{
+		memcpy(&cid,
+		       (char *) xlrec + record->xl_len - sizeof(CommandId),
+		       sizeof(CommandId));
+		/* adjust length of the tuple by the space used for the cid */
+		newlen -= sizeof(CommandId);
+	}
+
 	Assert(newlen <= MaxHeapTupleSize);
 	memcpy((char *) &xlhdr,
 		   (char *) xlrec + SizeOfHeapInsert,
@@ -6833,7 +6929,7 @@ heap_xlog_insert(XLogRecPtr lsn, XLogRecord *record)
 	htup->t_infomask = xlhdr.t_infomask;
 	htup->t_hoff = xlhdr.t_hoff;
 	HeapTupleHeaderSetXmin(htup, record->xl_xid);
-	HeapTupleHeaderSetCmin(htup, FirstCommandId);
+	HeapTupleHeaderSetCmin(htup, cid);
 	htup->t_ctid = xlrec->target.tid;
 
 	offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
@@ -6884,6 +6980,7 @@ heap_xlog_multi_insert(XLogRecPtr lsn, XLogRecord *record)
 	BlockNumber blkno;
 	int			i;
 	bool		isinit = (record->xl_info & XLOG_HEAP_INIT_PAGE) != 0;
+	CommandId	cid = FirstCommandId;
 
 	/*
 	 * Insertion doesn't overwrite MVCC data, so no conflict processing is
@@ -6925,6 +7022,12 @@ heap_xlog_multi_insert(XLogRecPtr lsn, XLogRecord *record)
 		return;
 	}
 
+	/* CommandId is stored at the end of record data */
+	if (xlrec->flags & XLOG_HEAP_CONTAINS_CID)
+		memcpy(&cid,
+		       (char *) xlrec + record->xl_len - sizeof(CommandId),
+		       sizeof(CommandId));
+
 	if (isinit)
 	{
 		buffer = XLogReadBuffer(xlrec->node, blkno, true);
@@ -6977,7 +7080,7 @@ heap_xlog_multi_insert(XLogRecPtr lsn, XLogRecord *record)
 		htup->t_infomask = xlhdr->t_infomask;
 		htup->t_hoff = xlhdr->t_hoff;
 		HeapTupleHeaderSetXmin(htup, record->xl_xid);
-		HeapTupleHeaderSetCmin(htup, FirstCommandId);
+		HeapTupleHeaderSetCmin(htup, cid);
 		ItemPointerSetBlockNumber(&htup->t_ctid, blkno);
 		ItemPointerSetOffsetNumber(&htup->t_ctid, offnum);
 
@@ -7033,6 +7136,7 @@ heap_xlog_update(XLogRecPtr lsn, XLogRecord *record, bool hot_update)
 	int			hsize;
 	uint32		newlen;
 	Size		freespace;
+	CommandId	cid = FirstCommandId;
 
 	/*
 	 * The visibility map may need to be fixed even if the heap page is
@@ -7072,6 +7176,12 @@ heap_xlog_update(XLogRecPtr lsn, XLogRecord *record, bool hot_update)
 		goto newt;
 	}
 
+	/* CommandId is stored at the end of record data */
+	if (xlrec->flags & XLOG_HEAP_CONTAINS_CID)
+		memcpy(&cid,
+		       (char *) xlrec + record->xl_len - sizeof(CommandId),
+		       sizeof(CommandId));
+
 	/* Deal with old tuple version */
 
 	obuffer = XLogReadBuffer(xlrec->target.node,
@@ -7100,7 +7210,8 @@ heap_xlog_update(XLogRecPtr lsn, XLogRecord *record, bool hot_update)
 
 	htup = (HeapTupleHeader) PageGetItem(page, lp);
 
-	htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
+	htup->t_infomask &= ~HEAP_XMAX_BITS;
+	HeapTupleHeaderClearMoved(htup);
 	htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 	if (hot_update)
 		HeapTupleHeaderSetHotUpdated(htup);
@@ -7109,7 +7220,7 @@ heap_xlog_update(XLogRecPtr lsn, XLogRecord *record, bool hot_update)
 	fix_infomask_from_infobits(xlrec->old_infobits_set, &htup->t_infomask,
 							   &htup->t_infomask2);
 	HeapTupleHeaderSetXmax(htup, xlrec->old_xmax);
-	HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
+	HeapTupleHeaderSetCmax(htup, cid, false);
 	/* Set forward chain link in t_ctid */
 	htup->t_ctid = xlrec->newtid;
 
@@ -7217,7 +7328,8 @@ newsame:;
 	htup->t_hoff = xlhdr.header.t_hoff;
 
 	HeapTupleHeaderSetXmin(htup, record->xl_xid);
-	HeapTupleHeaderSetCmin(htup, FirstCommandId);
+	HeapTupleHeaderSetCmin(htup, cid);
+	HeapTupleHeaderSetCmax(htup, InvalidCommandId, false);
 	HeapTupleHeaderSetXmax(htup, xlrec->new_xmax);
 	/* Make sure there is no forward chain link in t_ctid */
 	htup->t_ctid = xlrec->newtid;
@@ -7477,9 +7589,6 @@ heap2_redo(XLogRecPtr lsn, XLogRecord *record)
 		case XLOG_HEAP2_LOCK_UPDATED:
 			heap_xlog_lock_updated(lsn, record);
 			break;
-		case XLOG_HEAP2_NEW_CID:
-			/* nothing to do on a real replay, only during logical decoding */
-			break;
 		default:
 			elog(PANIC, "heap2_redo: unknown op code %u", info);
 	}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 951894c..7a43030 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -342,6 +342,12 @@ rewrite_heap_tuple(RewriteState state,
 	new_tuple->t_data->t_infomask |=
 		old_tuple->t_data->t_infomask & HEAP_XACT_MASK;
 
+	if (HeapTupleHeaderHasWideCid(old_tuple->t_data) && HeapTupleHeaderHasWideCid(new_tuple->t_data))
+	{
+		HeapTupleHeaderSetCmin(new_tuple->t_data, HeapTupleHeaderGetCmin(old_tuple->t_data));
+		HeapTupleHeaderSetCmax(new_tuple->t_data, HeapTupleHeaderGetCmax(old_tuple->t_data), false);
+	}
+
 	/*
 	 * While we have our hands on the tuple, we may as well freeze any
 	 * very-old xmin or xmax, so that future VACUUM effort can be saved.
diff --git a/src/backend/access/heap/tuptoaster.c b/src/backend/access/heap/tuptoaster.c
index 6728469..20d329d 100644
--- a/src/backend/access/heap/tuptoaster.c
+++ b/src/backend/access/heap/tuptoaster.c
@@ -668,6 +668,8 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
 	hoff = offsetof(HeapTupleHeaderData, t_bits);
 	if (has_nulls)
 		hoff += BITMAPLEN(numAttrs);
+	if (HeapTupleHeaderHasWideCid(newtup->t_data))
+		hoff += sizeof(CommandId);
 	if (newtup->t_data->t_infomask & HEAP_HASOID)
 		hoff += sizeof(Oid);
 	hoff = MAXALIGN(hoff);
@@ -954,6 +956,8 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
 		new_header_len = offsetof(HeapTupleHeaderData, t_bits);
 		if (has_nulls)
 			new_header_len += BITMAPLEN(numAttrs);
+		if (HeapTupleHeaderHasWideCid(olddata))
+			new_header_len += sizeof(CommandId);
 		if (olddata->t_infomask & HEAP_HASOID)
 			new_header_len += sizeof(Oid);
 		new_header_len = MAXALIGN(new_header_len);
@@ -977,6 +981,12 @@ toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
 		memcpy(new_data, olddata, offsetof(HeapTupleHeaderData, t_bits));
 		HeapTupleHeaderSetNatts(new_data, numAttrs);
 		new_data->t_hoff = new_header_len;
+		if (HeapTupleHeaderHasWideCid(olddata))
+		{
+			new_data->t_infomask |= HEAP_HAS_WIDE_CID;
+			HeapTupleHeaderSetCmin(new_data, HeapTupleHeaderGetCmin(olddata));
+			HeapTupleHeaderSetCmax(new_data, HeapTupleHeaderGetCmax(olddata), false);
+		}
 		if (olddata->t_infomask & HEAP_HASOID)
 			HeapTupleHeaderSetOid(new_data, HeapTupleHeaderGetOid(olddata));
 
@@ -1067,6 +1077,12 @@ toast_flatten_tuple(HeapTuple tup, TupleDesc tupleDesc)
 	 * point of copying visibility info, just in case anybody looks at those
 	 * fields in a syscache entry.
 	 */
+	if (tupleDesc->tdhaswidecid && HeapTupleHeaderHasWideCid(tup->t_data))
+	{
+		new_tuple->t_data->t_infomask |= HEAP_HAS_WIDE_CID;
+		HeapTupleHeaderSetCmin(new_tuple->t_data, HeapTupleHeaderGetCmin(tup->t_data));
+		HeapTupleHeaderSetCmax(new_tuple->t_data, HeapTupleHeaderGetCmax(tup->t_data), false);
+	}
 	if (tupleDesc->tdhasoid)
 		HeapTupleSetOid(new_tuple, HeapTupleGetOid(tup));
 
@@ -1192,6 +1208,8 @@ toast_flatten_tuple_attribute(Datum value,
 	new_header_len = offsetof(HeapTupleHeaderData, t_bits);
 	if (has_nulls)
 		new_header_len += BITMAPLEN(numAttrs);
+	if (HeapTupleHeaderHasWideCid(olddata))
+		new_header_len += sizeof(CommandId);
 	if (olddata->t_infomask & HEAP_HASOID)
 		new_header_len += sizeof(Oid);
 	new_header_len = MAXALIGN(new_header_len);
@@ -1207,6 +1225,12 @@ toast_flatten_tuple_attribute(Datum value,
 	memcpy(new_data, olddata, offsetof(HeapTupleHeaderData, t_bits));
 	HeapTupleHeaderSetNatts(new_data, numAttrs);
 	new_data->t_hoff = new_header_len;
+	if (HeapTupleHeaderHasWideCid(olddata))
+	{
+		new_data->t_infomask |= HEAP_HAS_WIDE_CID;
+		HeapTupleHeaderSetCmin(new_data, HeapTupleHeaderGetCmin(olddata));
+		HeapTupleHeaderSetCmax(new_data, HeapTupleHeaderGetCmax(olddata), false);
+	}
 	if (olddata->t_infomask & HEAP_HASOID)
 		HeapTupleHeaderSetOid(new_data, HeapTupleHeaderGetOid(olddata));
 
diff --git a/src/backend/access/rmgrdesc/heapdesc.c b/src/backend/access/rmgrdesc/heapdesc.c
index c750fef..bc8b985 100644
--- a/src/backend/access/rmgrdesc/heapdesc.c
+++ b/src/backend/access/rmgrdesc/heapdesc.c
@@ -184,15 +184,6 @@ heap2_desc(StringInfo buf, uint8 xl_info, char *rec)
 						 xlrec->infobits_set);
 		out_target(buf, &(xlrec->target));
 	}
-	else if (info == XLOG_HEAP2_NEW_CID)
-	{
-		xl_heap_new_cid *xlrec = (xl_heap_new_cid *) rec;
-
-		appendStringInfo(buf, "new_cid: ");
-		out_target(buf, &(xlrec->target));
-		appendStringInfo(buf, "; cmin: %u, cmax: %u, combo: %u",
-						 xlrec->cmin, xlrec->cmax, xlrec->combocid);
-	}
 	else
 		appendStringInfo(buf, "UNKNOWN");
 }
diff --git a/src/backend/access/rmgrdesc/xactdesc.c b/src/backend/access/rmgrdesc/xactdesc.c
index 7670b60..4c510ab 100644
--- a/src/backend/access/rmgrdesc/xactdesc.c
+++ b/src/backend/access/rmgrdesc/xactdesc.c
@@ -193,6 +193,13 @@ xact_desc(StringInfo buf, uint8 xl_info, char *rec)
 		appendStringInfo(buf, "xid assignment xtop %u: ", xlrec->xtop);
 		xact_desc_assignment(buf, xlrec);
 	}
+	else if (info == XLOG_XACT_CCI)
+	{
+		xl_xact_cci *xlrec = (xl_xact_cci *) rec;
+
+		appendStringInfo(buf, "catalog cci: %u, xtop: %u",
+		                 xlrec->command_id, xlrec->top_xid);
+	}
 	else
 		appendStringInfo(buf, "UNKNOWN");
 }
diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index 0942dbb..2281dd7 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -196,6 +196,7 @@ static TransactionState CurrentTransactionState = &TopTransactionStateData;
 static SubTransactionId currentSubTransactionId;
 static CommandId currentCommandId;
 static bool currentCommandIdUsed;
+static bool currentCommandModifiedCatalog;
 
 /*
  * xactStartTimestamp is the value of transaction_timestamp().
@@ -258,6 +259,7 @@ static void AtAbort_Memory(void);
 static void AtCleanup_Memory(void);
 static void AtAbort_ResourceOwner(void);
 static void AtCCI_LocalCache(void);
+static void AtCCI_Logical(void);
 static void AtCommit_Memory(void);
 static void AtStart_Cache(void);
 static void AtStart_Memory(void);
@@ -643,6 +645,12 @@ GetCurrentCommandId(bool used)
 	return currentCommandId;
 }
 
+void
+CommandModifiedCatalog(void)
+{
+	currentCommandModifiedCatalog = true;
+}
+
 /*
  *	GetCurrentTransactionStartTimestamp
  */
@@ -819,6 +827,12 @@ CommandCounterIncrement(void)
 		 * don't think a command that queued inval messages was read-only.)
 		 */
 		AtCCI_LocalCache();
+
+		/*
+		 * Tell logical decoding about potential DDL in this
+		 * command.
+		 */
+		AtCCI_Logical();
 	}
 }
 
@@ -1263,6 +1277,34 @@ AtCCI_LocalCache(void)
 }
 
 /*
+ *	AtCCI_Logical
+ */
+static void
+AtCCI_Logical(void)
+{
+	XLogRecData rdata;
+	xl_xact_cci	xlrec;
+
+	if (!currentCommandModifiedCatalog)
+		return;
+
+	if (!XLogLogicalInfoActive())
+		return;
+
+	currentCommandModifiedCatalog = false;
+
+	xlrec.top_xid = GetTopTransactionIdIfAny();
+	xlrec.command_id = currentCommandId;
+
+	rdata.data = (char *) (&xlrec);
+	rdata.len = sizeof(xlrec);
+	rdata.buffer = InvalidBuffer;
+	rdata.next = NULL;
+
+	(void) XLogInsert(RM_XACT_ID, XLOG_XACT_CCI, &rdata);
+}
+
+/*
  *	AtCommit_Memory
  */
 static void
@@ -1762,6 +1804,7 @@ StartTransaction(void)
 	currentSubTransactionId = TopSubTransactionId;
 	currentCommandId = FirstCommandId;
 	currentCommandIdUsed = false;
+	currentCommandModifiedCatalog = false;
 
 	/*
 	 * initialize reported xid accounting
@@ -4906,6 +4949,10 @@ xact_redo(XLogRecPtr lsn, XLogRecord *record)
 			ProcArrayApplyXidAssignment(xlrec->xtop,
 										xlrec->nsubxacts, xlrec->xsub);
 	}
+	else if (info == XLOG_XACT_CCI)
+	{
+		/* nothing to do during normal replay, only logical decoding needs this */
+	}
 	else
 		elog(PANIC, "xact_redo: unknown op code %u", info);
 }
diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c
index f3b4409..c560f66 100644
--- a/src/backend/commands/cluster.c
+++ b/src/backend/commands/cluster.c
@@ -786,6 +786,13 @@ copy_heap_data(Oid OIDNewHeap, Oid OIDOldHeap, Oid OIDOldIndex,
 	 */
 	oldTupDesc = RelationGetDescr(OldHeap);
 	newTupDesc = RelationGetDescr(NewHeap);
+
+	/*
+	 * tupdesc for temporary relation doesn't get the right value
+	 * assigned, fix temporarily
+	 */
+	newTupDesc->tdhaswidecid = oldTupDesc->tdhaswidecid;
+
 	Assert(newTupDesc->natts == oldTupDesc->natts);
 
 	/* Preallocate values/isnull arrays */
diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c
index 033b07d..10d61ee 100644
--- a/src/backend/replication/logical/decode.c
+++ b/src/backend/replication/logical/decode.c
@@ -282,6 +282,18 @@ DecodeXactOp(LogicalDecodingContext *ctx, XLogRecordBuffer *buf)
 			 * as well.
 			 */
 			break;
+		case XLOG_XACT_CCI:
+			{
+				xl_xact_cci *xlrec;
+				xlrec = (xl_xact_cci *) buf->record_data;
+
+				/* boring */
+				if (TransactionIdIsValid(xlrec->top_xid))
+					SnapBuildProcessNewCid(builder, r->xl_xid, buf->origptr, xlrec);
+
+				break;
+			}
+			break;
 		default:
 			break;
 	}
@@ -338,15 +350,6 @@ DecodeHeap2Op(LogicalDecodingContext *ctx, XLogRecordBuffer *buf)
 			if (SnapBuildProcessChange(builder, xid, buf->origptr))
 				DecodeMultiInsert(ctx, buf);
 			break;
-		case XLOG_HEAP2_NEW_CID:
-			{
-				xl_heap_new_cid *xlrec;
-				xlrec = (xl_heap_new_cid *) buf->record_data;
-				SnapBuildProcessNewCid(builder, xid, buf->origptr, xlrec);
-
-				break;
-			}
-
 		/*
 		 * Everything else here is just low level physical stuff we're
 		 * not interested in.
@@ -529,12 +532,16 @@ DecodeInsert(LogicalDecodingContext *ctx, XLogRecordBuffer *buf)
 
 	if (xlrec->flags & XLOG_HEAP_CONTAINS_NEW_TUPLE)
 	{
-		Assert(r->xl_len > (SizeOfHeapInsert + SizeOfHeapHeader));
+		Size len = r->xl_len - SizeOfHeapInsert;
+
+		/* adjust length of the tuple by the space used for the cid */
+		if (xlrec->flags & XLOG_HEAP_CONTAINS_CID)
+			len -= sizeof(CommandId);
 
 		change->tp.newtuple = ReorderBufferGetTupleBuf(ctx->reorder);
 
 		DecodeXLogTuple((char *) xlrec + SizeOfHeapInsert,
-						r->xl_len - SizeOfHeapInsert,
+						len,
 						change->tp.newtuple);
 	}
 
@@ -571,10 +578,12 @@ DecodeUpdate(LogicalDecodingContext *ctx, XLogRecordBuffer *buf)
 
 	if (xlrec->flags & XLOG_HEAP_CONTAINS_NEW_TUPLE)
 	{
-		Assert(r->xl_len > (SizeOfHeapUpdate + SizeOfHeapHeaderLen));
-
 		change->tp.newtuple = ReorderBufferGetTupleBuf(ctx->reorder);
 
+		/*
+		 * no need to adjust length as in DecodeInsert here,
+		 * xl_heap_header_len contains the length explicitly.
+		 */
 		DecodeXLogTuple(data,
 						xlhdr->t_len + SizeOfHeapHeader,
 						change->tp.newtuple);
@@ -625,12 +634,16 @@ DecodeDelete(LogicalDecodingContext *ctx, XLogRecordBuffer *buf)
 	/* old primary key stored */
 	if (xlrec->flags & XLOG_HEAP_CONTAINS_OLD_KEY)
 	{
-		Assert(r->xl_len > (SizeOfHeapDelete + SizeOfHeapHeader));
+		Size len = r->xl_len - SizeOfHeapDelete;
 
 		change->tp.oldtuple = ReorderBufferGetTupleBuf(ctx->reorder);
 
+		/* adjust length of the tuple by the space used for the cid */
+		if (xlrec->flags & XLOG_HEAP_CONTAINS_CID)
+			len -= sizeof(CommandId);
+
 		DecodeXLogTuple((char *) xlrec + SizeOfHeapDelete,
-						r->xl_len - SizeOfHeapDelete,
+						len,
 						change->tp.oldtuple);
 	}
 	ReorderBufferQueueChange(ctx->reorder, r->xl_xid, buf->origptr, change);
diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
index b613d3d..0142742 100644
--- a/src/backend/replication/logical/reorderbuffer.c
+++ b/src/backend/replication/logical/reorderbuffer.c
@@ -92,8 +92,7 @@ typedef enum
 	REORDER_BUFFER_CHANGE_INTERNAL_UPDATE,
 	REORDER_BUFFER_CHANGE_INTERNAL_DELETE,
 	REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT,
-	REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID,
-	REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID
+	REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID
 } ReorderBufferChangeTypeInternal;
 
 /* entry for a hash table we use to map from xid to our transaction state */
@@ -103,21 +102,6 @@ typedef struct ReorderBufferTXNByIdEnt
 	ReorderBufferTXN *txn;
 } ReorderBufferTXNByIdEnt;
 
-/* data structures for (relfilenode, ctid) => (cmin, cmax) mapping */
-typedef struct ReorderBufferTupleCidKey
-{
-	RelFileNode relnode;
-	ItemPointerData tid;
-} ReorderBufferTupleCidKey;
-
-typedef struct ReorderBufferTupleCidEnt
-{
-	ReorderBufferTupleCidKey key;
-	CommandId	cmin;
-	CommandId	cmax;
-	CommandId	combocid;		/* just for debugging */
-} ReorderBufferTupleCidEnt;
-
 /* k-way in-order change iteration support structures */
 typedef struct ReorderBufferIterTXNEntry
 {
@@ -316,7 +300,6 @@ ReorderBufferGetTXN(ReorderBuffer *rb)
 	memset(txn, 0, sizeof(ReorderBufferTXN));
 
 	dlist_init(&txn->changes);
-	dlist_init(&txn->tuplecids);
 	dlist_init(&txn->subtxns);
 
 	return txn;
@@ -336,12 +319,6 @@ ReorderBufferReturnTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
 		rb->by_txn_last_txn = NULL;
 	}
 
-	if (txn->tuplecid_hash != NULL)
-	{
-		hash_destroy(txn->tuplecid_hash);
-		txn->tuplecid_hash = NULL;
-	}
-
 	if (txn->invalidations)
 	{
 		pfree(txn->invalidations);
@@ -419,8 +396,6 @@ ReorderBufferReturnChange(ReorderBuffer *rb, ReorderBufferChange *change)
 			break;
 		case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
 			break;
-		case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
-			break;
 	}
 
 	if (rb->nr_cached_changes < max_cached_changes)
@@ -1050,19 +1025,6 @@ ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
 		ReorderBufferReturnChange(rb, change);
 	}
 
-	/*
-	 * cleanup the tuplecids we stored timetravel access. They are always
-	 * stored in the toplevel transaction.
-	 */
-	dlist_foreach_modify(iter, &txn->tuplecids)
-	{
-		ReorderBufferChange *change;
-
-		change = dlist_container(ReorderBufferChange, node, iter.cur);
-		Assert(change->action_internal == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
-		ReorderBufferReturnChange(rb, change);
-	}
-
 	if (txn->base_snapshot != NULL)
 	{
 		SnapBuildSnapDecRefcount(txn->base_snapshot);
@@ -1097,80 +1059,6 @@ ReorderBufferCleanupTXN(ReorderBuffer *rb, ReorderBufferTXN *txn)
 }
 
 /*
- * Build a hash with a (relfilenode, ctid) -> (cmin, cmax) mapping for use by
- * tqual.c's HeapTupleSatisfiesMVCCDuringDecoding.
- */
-static void
-ReorderBufferBuildTupleCidHash(ReorderBuffer *rb, ReorderBufferTXN *txn)
-{
-	dlist_iter	iter;
-	HASHCTL		hash_ctl;
-
-	if (!txn->has_catalog_changes || dlist_is_empty(&txn->tuplecids))
-		return;
-
-	memset(&hash_ctl, 0, sizeof(hash_ctl));
-
-	hash_ctl.keysize = sizeof(ReorderBufferTupleCidKey);
-	hash_ctl.entrysize = sizeof(ReorderBufferTupleCidEnt);
-	hash_ctl.hash = tag_hash;
-	hash_ctl.hcxt = rb->context;
-
-	/*
-	 * create the hash with the exact number of to-be-stored tuplecids from
-	 * the start
-	 */
-	txn->tuplecid_hash =
-		hash_create("ReorderBufferTupleCid", txn->ntuplecids, &hash_ctl,
-					HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
-
-	dlist_foreach(iter, &txn->tuplecids)
-	{
-		ReorderBufferTupleCidKey key;
-		ReorderBufferTupleCidEnt *ent;
-		bool		found;
-		ReorderBufferChange *change;
-
-		change = dlist_container(ReorderBufferChange, node, iter.cur);
-
-		Assert(change->action_internal == REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID);
-
-		/* be careful about padding */
-		memset(&key, 0, sizeof(ReorderBufferTupleCidKey));
-
-		key.relnode = change->tuplecid.node;
-
-		ItemPointerCopy(&change->tuplecid.tid,
-						&key.tid);
-
-		ent = (ReorderBufferTupleCidEnt *)
-			hash_search(txn->tuplecid_hash,
-						(void *) &key,
-						HASH_ENTER | HASH_FIND,
-						&found);
-		if (!found)
-		{
-			ent->cmin = change->tuplecid.cmin;
-			ent->cmax = change->tuplecid.cmax;
-			ent->combocid = change->tuplecid.combocid;
-		}
-		else
-		{
-			Assert(ent->cmin == change->tuplecid.cmin);
-			Assert(ent->cmax == InvalidCommandId ||
-				   ent->cmax == change->tuplecid.cmax);
-
-			/*
-			 * if the tuple got valid in this transaction and now got deleted
-			 * we already have a valid cmin stored. The cmax will be
-			 * InvalidCommandId though.
-			 */
-			ent->cmax = change->tuplecid.cmax;
-		}
-	}
-}
-
-/*
  * Copy a provided snapshot so we can modify it privately. This is needed so
  * that catalog modifying transactions can look into intermediate catalog
  * states.
@@ -1278,10 +1166,8 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid, XLogRecPtr commit_lsn,
 
 	snapshot_now = txn->base_snapshot;
 
-	ReorderBufferBuildTupleCidHash(rb, txn);
-
 	/* setup initial snapshot */
-	SetupDecodingSnapshots(snapshot_now, txn->tuplecid_hash);
+	SetupDecodingSnapshots(snapshot_now);
 
 	PG_TRY();
 	{
@@ -1391,7 +1277,7 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid, XLogRecPtr commit_lsn,
 
 
 					/* and start with the new one */
-					SetupDecodingSnapshots(snapshot_now, txn->tuplecid_hash);
+					SetupDecodingSnapshots(snapshot_now);
 					break;
 
 				case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
@@ -1409,7 +1295,7 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid, XLogRecPtr commit_lsn,
 						snapshot_now->curcid = command_id;
 
 						RevertFromDecodingSnapshots();
-						SetupDecodingSnapshots(snapshot_now, txn->tuplecid_hash);
+						SetupDecodingSnapshots(snapshot_now);
 					}
 
 					/*
@@ -1419,10 +1305,6 @@ ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid, XLogRecPtr commit_lsn,
 					ReorderBufferExecuteInvalidations(rb, txn);
 
 					break;
-
-				case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
-					elog(ERROR, "tuplecid value in normal queue");
-					break;
 			}
 		}
 
@@ -1568,33 +1450,6 @@ ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
 	ReorderBufferQueueChange(rb, xid, lsn, change);
 }
 
-
-/*
- * Add new (relfilenode, tid) -> (cmin, cmax) mappings.
- */
-void
-ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
-							 XLogRecPtr lsn, RelFileNode node,
-							 ItemPointerData tid, CommandId cmin,
-							 CommandId cmax, CommandId combocid)
-{
-	ReorderBufferChange *change = ReorderBufferGetChange(rb);
-	ReorderBufferTXN *txn;
-
-	txn = ReorderBufferTXNByXid(rb, xid, true, NULL, lsn, true);
-
-	change->tuplecid.node = node;
-	change->tuplecid.tid = tid;
-	change->tuplecid.cmin = cmin;
-	change->tuplecid.cmax = cmax;
-	change->tuplecid.combocid = combocid;
-	change->lsn = lsn;
-	change->action_internal = REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID;
-
-	dlist_push_tail(&txn->tuplecids, &change->node);
-	txn->ntuplecids++;
-}
-
 /*
  * Setup the invalidation of the toplevel transaction.
  *
@@ -1803,9 +1658,6 @@ ReorderBufferSerializeChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
 		case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
 			/* ReorderBufferChange contains everything important */
 			break;
-		case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
-			/* ReorderBufferChange contains everything important */
-			break;
 	}
 
 	ondisk->size = sz;
@@ -2093,7 +1945,6 @@ ReorderBufferRestoreChange(ReorderBuffer *rb, ReorderBufferTXN *txn,
 			}
 			/* nothing needs to be done */
 		case REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID:
-		case REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID:
 			break;
 	}
 
@@ -2468,73 +2319,3 @@ ReorderBufferToastReset(ReorderBuffer *rb, ReorderBufferTXN *txn)
 	hash_destroy(txn->toast_hash);
 	txn->toast_hash = NULL;
 }
-
-
-/*
- * Visibility support routines
- */
-
-/*-------------------------------------------------------------------------
- * Lookup actual cmin/cmax values during timetravel access. We can't always
- * rely on stored cmin/cmax values because of two scenarios:
- *
- * * A tuple got changed multiple times during a single transaction and thus
- *	 has got a combocid. Combocid's are only valid for the duration of a single
- *	 transaction.
- * * A tuple with a cmin but no cmax (and thus no combocid) got deleted/updated
- *	 in another transaction than the one which created it which we are looking
- *	 at right now. As only one of cmin, cmax or combocid is actually stored in
- *	 the heap we don't have access to the the value we need anymore.
- *
- * To resolve those problems we have a per-transaction hash of (cmin, cmax)
- * tuples keyed by (relfilenode, ctid) which contains the actual (cmin, cmax)
- * values. That also takes care of combocids by simply not caring about them at
- * all. As we have the real cmin/cmax values thats enough.
- *
- * As we only care about catalog tuples here the overhead of this hashtable
- * should be acceptable.
- * -------------------------------------------------------------------------
- */
-extern bool
-ResolveCminCmaxDuringDecoding(HTAB *tuplecid_data,
-							  HeapTuple htup, Buffer buffer,
-							  CommandId *cmin, CommandId *cmax)
-{
-	ReorderBufferTupleCidKey key;
-	ReorderBufferTupleCidEnt *ent;
-	ForkNumber	forkno;
-	BlockNumber blockno;
-
-	/* be careful about padding */
-	memset(&key, 0, sizeof(key));
-
-	Assert(!BufferIsLocal(buffer));
-
-	/*
-	 * get relfilenode from the buffer, no convenient way to access it other
-	 * than that.
-	 */
-	BufferGetTag(buffer, &key.relnode, &forkno, &blockno);
-
-	/* tuples can only be in the main fork */
-	Assert(forkno == MAIN_FORKNUM);
-	Assert(blockno == ItemPointerGetBlockNumber(&htup->t_self));
-
-	ItemPointerCopy(&htup->t_self,
-					&key.tid);
-
-	ent = (ReorderBufferTupleCidEnt *)
-		hash_search(tuplecid_data,
-					(void *) &key,
-					HASH_FIND,
-					NULL);
-
-	if (ent == NULL)
-		return false;
-
-	if (cmin)
-		*cmin = ent->cmin;
-	if (cmax)
-		*cmax = ent->cmax;
-	return true;
-}
diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index 6c44614..b9ead6b 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -623,46 +623,27 @@ SnapBuildProcessChange(SnapBuild *builder, TransactionId xid, XLogRecPtr lsn)
 }
 
 /*
- * Do CommandId/ComboCid handling after reading a xl_heap_new_cid record. This
- * implies that a transaction has done some for of write to system catalogs.
+ * Do CommandId handling after reading a xl_xactcco record. This
+ * implies that a transaction has done some for of write to system
+ * catalogs.
  */
 void
 SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
-					   XLogRecPtr lsn, xl_heap_new_cid *xlrec)
+					   XLogRecPtr lsn, xl_xact_cci *xlrec)
 {
-	CommandId	cid;
 
 	/*
-	 * we only log new_cid's if a catalog tuple was modified, so mark
-	 * the transaction as containing catalog modifications
+	 * we only log CCIs if a catalog tuple was modified, so mark the
+	 * transaction as containing catalog modifications
 	 */
-	ReorderBufferXidSetCatalogChanges(builder->reorder, xid,lsn);
-
-	ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
-								 xlrec->target.node, xlrec->target.tid,
-								 xlrec->cmin, xlrec->cmax,
-								 xlrec->combocid);
-
-	/* figure out new command id */
-	if (xlrec->cmin != InvalidCommandId &&
-		xlrec->cmax != InvalidCommandId)
-		cid = Max(xlrec->cmin, xlrec->cmax);
-	else if (xlrec->cmax != InvalidCommandId)
-		cid = xlrec->cmax;
-	else if (xlrec->cmin != InvalidCommandId)
-		cid = xlrec->cmin;
-	else
-	{
-		cid = InvalidCommandId;		/* silence compiler */
-		elog(ERROR, "broken arrow, no cid?");
-	}
+	ReorderBufferXidSetCatalogChanges(builder->reorder, xid, lsn);
 
 	/*
-	 * FIXME: potential race condition here: if multiple snapshots were running
-	 * & generating changes in the same transaction on the source side this
-	 * could be problematic. But this cannot happen for system catalogs, right?
+	 * Add note to the toplevel TX that we should use a new CommandId
+	 * to decode henceforth.
 	 */
-	ReorderBufferAddNewCommandId(builder->reorder, xid, lsn, cid + 1);
+	ReorderBufferAddNewCommandId(builder->reorder, xlrec->top_xid,
+	                             lsn, xlrec->command_id);
 }
 
 /*
diff --git a/src/backend/utils/cache/inval.c b/src/backend/utils/cache/inval.c
index 015970a..9125616 100644
--- a/src/backend/utils/cache/inval.c
+++ b/src/backend/utils/cache/inval.c
@@ -1039,18 +1039,25 @@ CacheInvalidateHeapTuple(Relation relation,
 		return;
 
 	/*
-	 * We only need to worry about invalidation for tuples that are in system
-	 * relations; user-relation tuples are never in catcaches and can't affect
-	 * the relcache either.
+	 * TOAST tuples can be ignored here. Note that TOAST tables are
+	 * considered system relations so they are not filtered by the
+	 * below test for system relations.
 	 */
-	if (!IsSystemRelation(relation))
+	if (IsToastRelation(relation))
 		return;
 
 	/*
-	 * TOAST tuples can likewise be ignored here. Note that TOAST tables are
-	 * considered system relations so they are not filtered by the above test.
+	 * Remember whether our transaction has modified the catalog.
 	 */
-	if (IsToastRelation(relation))
+	if (IsSystemRelation(relation) || RelationIsUsedAsCatalogTable(relation))
+		CommandModifiedCatalog();
+
+	/*
+	 * We only need to worry about invalidation for tuples that are in system
+	 * relations; user-relation tuples are never in catcaches and can't affect
+	 * the relcache either.
+	 */
+	if (!IsSystemRelation(relation))
 		return;
 
 	/*
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 50c2a7b..f73d51c 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -455,6 +455,13 @@ RelationBuildTupleDesc(Relation relation)
 	relation->rd_att->tdtypmod = -1;	/* unnecessary, but... */
 	relation->rd_att->tdhasoid = relation->rd_rel->relhasoids;
 
+	/*
+	 * Updated for user defined tables in RelationBuildDesc, we
+	 * haven't parsed reloptions yet, so we cannot do it here.
+	 */
+	relation->rd_att->tdhaswidecid =
+		 XLogLogicalInfoActive() && IsSystemRelation(relation);
+
 	constr = (TupleConstr *) MemoryContextAlloc(CacheMemoryContext,
 												sizeof(TupleConstr));
 	constr->has_not_null = false;
@@ -942,6 +949,13 @@ RelationBuildDesc(Oid targetRelId, bool insertIt)
 	RelationParseRelOptions(relation, pg_class_tuple);
 
 	/*
+	 * Now we have parsed reloptions, can check whether we are a
+	 * catalog table.
+	 */
+	if (RelationIsUsedAsCatalogTable(relation))
+		relation->rd_att->tdhaswidecid = true;
+
+	/*
 	 * initialize the relation lock manager information
 	 */
 	RelationInitLockInfo(relation);		/* see lmgr.c */
@@ -1502,6 +1516,9 @@ formrdesc(const char *relationName, Oid relationReltype,
 	relation->rd_att->tdtypeid = relationReltype;
 	relation->rd_att->tdtypmod = -1;	/* unnecessary, but... */
 
+	/* has to be a system relation, otherwise formrdesc isn't used */
+	relation->rd_att->tdhaswidecid = XLogLogicalInfoActive();
+
 	/*
 	 * initialize tuple desc info
 	 */
@@ -3168,6 +3185,10 @@ RelationCacheInitializePhase3(void)
 			restart = true;
 		}
 
+		/* only system relations need to be fixed here */
+		if (XLogLogicalInfoActive() && IsSystemRelation(relation))
+			relation->rd_att->tdhaswidecid = true;
+
 		/*
 		 * Fix data that isn't saved in relcache cache file.
 		 *
diff --git a/src/backend/utils/time/combocid.c b/src/backend/utils/time/combocid.c
index 923355d..1575e96 100644
--- a/src/backend/utils/time/combocid.c
+++ b/src/backend/utils/time/combocid.c
@@ -104,27 +104,52 @@ HeapTupleHeaderGetCmin(HeapTupleHeader tup)
 {
 	CommandId	cid = HeapTupleHeaderGetRawCommandId(tup);
 
-	Assert(!(tup->t_infomask & HEAP_MOVED));
-	Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tup)));
+	Assert(!HeapTupleHeaderHasMoved(tup));
 
-	if (tup->t_infomask & HEAP_COMBOCID)
+	if (HeapTupleHeaderHasWideCid(tup))
+	{
+		return cid;
+	}
+	else if (tup->t_infomask & HEAP_COMBOCID)
+	{
+		Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tup)));
 		return GetRealCmin(cid);
+	}
 	else
+	{
+		Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tup)));
 		return cid;
+	}
 }
 
 CommandId
 HeapTupleHeaderGetCmax(HeapTupleHeader tup)
 {
-	CommandId	cid = HeapTupleHeaderGetRawCommandId(tup);
+	Assert(!HeapTupleHeaderHasMoved(tup));
 
-	Assert(!(tup->t_infomask & HEAP_MOVED));
-	Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(tup)));
+	if (HeapTupleHeaderHasWideCid(tup))
+	{
+		if (tup->t_infomask & HEAP_HASOID)
+			return  *(CommandId *) ((char *)tup +
+								tup->t_hoff -
+								sizeof(Oid) -
+								sizeof(CommandId));
+		else
+			return *(CommandId *) ((char *)tup +
+								tup->t_hoff -
+								sizeof(Oid));
 
-	if (tup->t_infomask & HEAP_COMBOCID)
-		return GetRealCmax(cid);
+	}
+	else if (tup->t_infomask & HEAP_COMBOCID)
+	{
+		Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(tup)));
+		return GetRealCmax(HeapTupleHeaderGetRawCommandId(tup));
+	}
 	else
-		return cid;
+	{
+		Assert(TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(tup)));
+		return HeapTupleHeaderGetRawCommandId(tup);
+	}
 }
 
 /*
@@ -151,7 +176,11 @@ HeapTupleHeaderAdjustCmax(HeapTupleHeader tup,
 	 * Test for HEAP_XMIN_COMMITTED first, because it's cheaper than a
 	 * TransactionIdIsCurrentTransactionId call.
 	 */
-	if (!(tup->t_infomask & HEAP_XMIN_COMMITTED) &&
+	if (HeapTupleHeaderHasWideCid(tup))
+	{
+		*iscombo = false;
+	}
+	else if (!(tup->t_infomask & HEAP_XMIN_COMMITTED) &&
 		TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(tup)))
 	{
 		CommandId	cmin = HeapTupleHeaderGetCmin(tup);
diff --git a/src/backend/utils/time/tqual.c b/src/backend/utils/time/tqual.c
index bfc9bd7..ce70760 100644
--- a/src/backend/utils/time/tqual.c
+++ b/src/backend/utils/time/tqual.c
@@ -73,8 +73,6 @@ SnapshotData SnapshotAnyData = {HeapTupleSatisfiesAny};
 SnapshotData SnapshotToastData = {HeapTupleSatisfiesToast};
 
 static Snapshot TimetravelSnapshot;
-/* (table, ctid) => (cmin, cmax) mapping during timetravel */
-static HTAB *tuplecid_data = NULL;
 static int timetravel_suspended = 0;
 
 
@@ -182,7 +180,7 @@ HeapTupleSatisfiesSelf(HeapTuple htup, Snapshot snapshot, Buffer buffer)
 			return false;
 
 		/* Used by pre-9.0 binary upgrades */
-		if (tuple->t_infomask & HEAP_MOVED_OFF)
+		if (HeapTupleHeaderHasMovedOff(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -201,7 +199,7 @@ HeapTupleSatisfiesSelf(HeapTuple htup, Snapshot snapshot, Buffer buffer)
 			}
 		}
 		/* Used by pre-9.0 binary upgrades */
-		else if (tuple->t_infomask & HEAP_MOVED_IN)
+		else if (HeapTupleHeaderHasMovedIn(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -368,7 +366,7 @@ HeapTupleSatisfiesToast(HeapTuple htup, Snapshot snapshot,
 			return false;
 
 		/* Used by pre-9.0 binary upgrades */
-		if (tuple->t_infomask & HEAP_MOVED_OFF)
+		if (HeapTupleHeaderHasMovedOff(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -387,7 +385,7 @@ HeapTupleSatisfiesToast(HeapTuple htup, Snapshot snapshot,
 			}
 		}
 		/* Used by pre-9.0 binary upgrades */
-		else if (tuple->t_infomask & HEAP_MOVED_IN)
+		else if (HeapTupleHeaderHasMovedIn(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -453,7 +451,7 @@ HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid,
 			return HeapTupleInvisible;
 
 		/* Used by pre-9.0 binary upgrades */
-		if (tuple->t_infomask & HEAP_MOVED_OFF)
+		if (HeapTupleHeaderHasMovedOff(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -472,7 +470,7 @@ HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid,
 			}
 		}
 		/* Used by pre-9.0 binary upgrades */
-		else if (tuple->t_infomask & HEAP_MOVED_IN)
+		else if (HeapTupleHeaderHasMovedIn(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -681,7 +679,7 @@ HeapTupleSatisfiesDirty(HeapTuple htup, Snapshot snapshot,
 			return false;
 
 		/* Used by pre-9.0 binary upgrades */
-		if (tuple->t_infomask & HEAP_MOVED_OFF)
+		if (HeapTupleHeaderHasMovedOff(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -700,7 +698,7 @@ HeapTupleSatisfiesDirty(HeapTuple htup, Snapshot snapshot,
 			}
 		}
 		/* Used by pre-9.0 binary upgrades */
-		else if (tuple->t_infomask & HEAP_MOVED_IN)
+		else if (HeapTupleHeaderHasMovedIn(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -871,7 +869,7 @@ HeapTupleSatisfiesMVCC(HeapTuple htup, Snapshot snapshot,
 			return false;
 
 		/* Used by pre-9.0 binary upgrades */
-		if (tuple->t_infomask & HEAP_MOVED_OFF)
+		if (HeapTupleHeaderHasMovedOff(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -890,7 +888,7 @@ HeapTupleSatisfiesMVCC(HeapTuple htup, Snapshot snapshot,
 			}
 		}
 		/* Used by pre-9.0 binary upgrades */
-		else if (tuple->t_infomask & HEAP_MOVED_IN)
+		else if (HeapTupleHeaderHasMovedIn(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -1073,7 +1071,7 @@ HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin,
 		if (tuple->t_infomask & HEAP_XMIN_INVALID)
 			return HEAPTUPLE_DEAD;
 		/* Used by pre-9.0 binary upgrades */
-		else if (tuple->t_infomask & HEAP_MOVED_OFF)
+		else if (HeapTupleHeaderHasMovedOff(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -1091,7 +1089,7 @@ HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin,
 						InvalidTransactionId);
 		}
 		/* Used by pre-9.0 binary upgrades */
-		else if (tuple->t_infomask & HEAP_MOVED_IN)
+		else if (HeapTupleHeaderHasMovedIn(tuple))
 		{
 			TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
 
@@ -1545,28 +1543,7 @@ HeapTupleSatisfiesMVCCDuringDecoding(HeapTuple htup, Snapshot snapshot,
     /* check if its one of our txids, toplevel is also in there */
 	else if (TransactionIdInArray(xmin, snapshot->subxip, snapshot->subxcnt))
 	{
-		CommandId cmin = HeapTupleHeaderGetRawCommandId(tuple);
-		CommandId cmax = InvalidCommandId;
-
-		/*
-		 * If another transaction deleted this tuple or if cmin/cmax is stored
-		 * in a combocid we need to to lookup the actual values externally. We
-		 * need to do so in the deleted case because the deletion will have
-		 * overwritten the cmin value when setting cmax (c.f. combocid.c).
-		 */
-		if ((!(tuple->t_infomask & HEAP_XMAX_INVALID) &&
-			 !TransactionIdInArray(xmax, snapshot->subxip, snapshot->subxcnt)) ||
-			tuple->t_infomask & HEAP_COMBOCID
-			)
-		{
-			bool resolved;
-
-			resolved = ResolveCminCmaxDuringDecoding(tuplecid_data, htup,
-													 buffer, &cmin, &cmax);
-
-			if (!resolved)
-				elog(ERROR, "could not resolve cmin/cmax of catalog tuple");
-		}
+		CommandId cmin = HeapTupleHeaderGetCmin(tuple);
 
 		Assert(cmin != InvalidCommandId);
 
@@ -1622,21 +1599,16 @@ HeapTupleSatisfiesMVCCDuringDecoding(HeapTuple htup, Snapshot snapshot,
     /* check if its one of our txids, toplevel is also in there */
 	if (TransactionIdInArray(xmax, snapshot->subxip, snapshot->subxcnt))
 	{
-		CommandId cmin;
-		CommandId cmax = HeapTupleHeaderGetRawCommandId(tuple);
+		CommandId cmax;
 
-		/* Lookup actual cmin/cmax values */
-		if (tuple->t_infomask & HEAP_COMBOCID)
+		if (HeapTupleHeaderHasWideCid(tuple))
+			cmax = HeapTupleHeaderGetCmax(tuple);
+		else
 		{
-			bool resolved;
-
-			resolved = ResolveCminCmaxDuringDecoding(tuplecid_data, htup,
-													 buffer, &cmin, &cmax);
-
-			if (!resolved)
-				elog(ERROR, "could not resolve combocid to cmax");
+			Assert(!TransactionIdInArray(xmin, snapshot->subxip, snapshot->subxcnt));
+			Assert(TransactionIdPrecedes(xmin, snapshot->xmin));
+			cmax = HeapTupleHeaderGetRawCommandId(tuple);
 		}
-
 		Assert(cmax != InvalidCommandId);
 
 		if (cmax >= snapshot->curcid)
@@ -1675,7 +1647,7 @@ HeapTupleSatisfiesMVCCDuringDecoding(HeapTuple htup, Snapshot snapshot,
  * Needed for after-the-fact WAL decoding.
  */
 void
-SetupDecodingSnapshots(Snapshot timetravel_snapshot, HTAB *tuplecids)
+SetupDecodingSnapshots(Snapshot timetravel_snapshot)
 {
 	/* prevent recursively setting up decoding snapshots */
 	Assert(CatalogSnapshotData.satisfies != RedirectSatisfiesMVCC);
@@ -1690,9 +1662,6 @@ SetupDecodingSnapshots(Snapshot timetravel_snapshot, HTAB *tuplecids)
 	/* setup the timetravel snapshot */
 	TimetravelSnapshot = timetravel_snapshot;
 
-	/* setup (cmin, cmax) lookup hash */
-	tuplecid_data = tuplecids;
-
 	timetravel_suspended = 0;
 }
 
@@ -1706,7 +1675,6 @@ RevertFromDecodingSnapshots(void)
 	Assert(timetravel_suspended == 0);
 
 	TimetravelSnapshot = NULL;
-	tuplecid_data = NULL;
 
 	/* rally to restore sanity and/or boredom */
 	CatalogSnapshotData.satisfies = HeapTupleSatisfiesMVCC;
diff --git a/src/include/access/heapam_xlog.h b/src/include/access/heapam_xlog.h
index ba4bc3d..a76d63c 100644
--- a/src/include/access/heapam_xlog.h
+++ b/src/include/access/heapam_xlog.h
@@ -55,7 +55,6 @@
 #define XLOG_HEAP2_VISIBLE		0x40
 #define XLOG_HEAP2_MULTI_INSERT 0x50
 #define XLOG_HEAP2_LOCK_UPDATED 0x60
-#define XLOG_HEAP2_NEW_CID		0x70
 
 /*
  * xl_heap_* ->flag values
@@ -67,6 +66,7 @@
 #define XLOG_HEAP_CONTAINS_OLD_TUPLE		(1<<2)
 #define XLOG_HEAP_CONTAINS_OLD_KEY			(1<<3)
 #define XLOG_HEAP_CONTAINS_NEW_TUPLE		(1<<4)
+#define XLOG_HEAP_CONTAINS_CID			(1<<5)
 
 /*
  * All what we need to find changed tuple
@@ -280,29 +280,6 @@ typedef struct xl_heap_visible
 
 #define SizeOfHeapVisible (offsetof(xl_heap_visible, cutoff_xid) + sizeof(TransactionId))
 
-typedef struct xl_heap_new_cid
-{
-	/*
-	 * store toplevel xid so we don't have to merge cids from different
-	 * transactions
-	 */
-	TransactionId top_xid;
-	CommandId cmin;
-	CommandId cmax;
-	/*
-	 * don't really need the combocid since we have the actual values
-	 * right in this struct, but the padding makes it free and its
-	 * useful for debugging.
-	 */
-	CommandId combocid;
-	/*
-	 * Store the relfilenode/ctid pair to facilitate lookups.
-	 */
-	xl_heaptid target;
-} xl_heap_new_cid;
-
-#define SizeOfHeapNewCid (offsetof(xl_heap_new_cid, target) + SizeOfHeapTid)
-
 extern void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple,
 									   TransactionId *latestRemovedXid);
 
diff --git a/src/include/access/htup_details.h b/src/include/access/htup_details.h
index 0a832e9..e46238c 100644
--- a/src/include/access/htup_details.h
+++ b/src/include/access/htup_details.h
@@ -186,8 +186,12 @@ struct HeapTupleHeaderData
 										 * VACUUM FULL; kept for binary
 										 * upgrade support */
 #define HEAP_MOVED (HEAP_MOVED_OFF | HEAP_MOVED_IN)
+/*
+ * both bits set, use HeapTupleHeaderHasWideCid to test.
+ */
+#define HEAP_HAS_WIDE_CID		HEAP_MOVED
 
-#define HEAP_XACT_MASK			0xFFF0	/* visibility-related bits */
+#define HEAP_XACT_MASK			(0xFFF0 & ~HEAP_MOVED)	/* visibility-related bits */
 
 /*
  * A tuple is only locked (i.e. not updated by its Xmax) if the
@@ -295,25 +299,14 @@ struct HeapTupleHeaderData
 /* SetCmin is reasonably simple since we never need a combo CID */
 #define HeapTupleHeaderSetCmin(tup, cid) \
 do { \
-	Assert(!((tup)->t_infomask & HEAP_MOVED)); \
+	Assert(!HeapTupleHeaderHasMoved(tup)); \
 	(tup)->t_choice.t_heap.t_field3.t_cid = (cid); \
 	(tup)->t_infomask &= ~HEAP_COMBOCID; \
 } while (0)
 
-/* SetCmax must be used after HeapTupleHeaderAdjustCmax; see combocid.c */
-#define HeapTupleHeaderSetCmax(tup, cid, iscombo) \
-do { \
-	Assert(!((tup)->t_infomask & HEAP_MOVED)); \
-	(tup)->t_choice.t_heap.t_field3.t_cid = (cid); \
-	if (iscombo) \
-		(tup)->t_infomask |= HEAP_COMBOCID; \
-	else \
-		(tup)->t_infomask &= ~HEAP_COMBOCID; \
-} while (0)
-
 #define HeapTupleHeaderGetXvac(tup) \
 ( \
-	((tup)->t_infomask & HEAP_MOVED) ? \
+	HeapTupleHeaderHasMoved(tup) ? \
 		(tup)->t_choice.t_heap.t_field3.t_xvac \
 	: \
 		InvalidTransactionId \
@@ -425,6 +418,25 @@ do { \
 	(tup)->t_infomask2 = ((tup)->t_infomask2 & ~HEAP_NATTS_MASK) | (natts) \
 )
 
+#define HeapTupleHeaderHasWideCid(tup) \
+	(((tup)->t_infomask & HEAP_HAS_WIDE_CID) == HEAP_HAS_WIDE_CID)
+
+#define HeapTupleHeaderHasMoved(tup) \
+	(!HeapTupleHeaderHasWideCid(tup) && ((tup)->t_infomask & HEAP_MOVED))
+
+#define HeapTupleHeaderHasMovedOff(tup) \
+	(((tup)->t_infomask & HEAP_MOVED_OFF) && \
+	 !((tup)->t_infomask & HEAP_MOVED_IN))
+
+#define HeapTupleHeaderHasMovedIn(tup) \
+	(((tup)->t_infomask & HEAP_MOVED_IN) && \
+	 !((tup)->t_infomask & HEAP_MOVED_OFF))
+
+#define HeapTupleHeaderClearMoved(tup) \
+do { \
+	if (HeapTupleHeaderHasMoved(tup)) \
+		(tup)->t_infomask &= ~HEAP_MOVED; \
+} while (0)
 
 /*
  * BITMAPLEN(NATTS) -
@@ -707,4 +719,6 @@ extern MinimalTuple heap_copy_minimal_tuple(MinimalTuple mtup);
 extern HeapTuple heap_tuple_from_minimal_tuple(MinimalTuple mtup);
 extern MinimalTuple minimal_tuple_from_heap_tuple(HeapTuple htup);
 
+extern void HeapTupleHeaderSetCmax(HeapTupleHeader tup, CommandId cid, bool iscombo);
+
 #endif   /* HTUP_DETAILS_H */
diff --git a/src/include/access/tupdesc.h b/src/include/access/tupdesc.h
index 49226b7..80eab88 100644
--- a/src/include/access/tupdesc.h
+++ b/src/include/access/tupdesc.h
@@ -77,6 +77,7 @@ typedef struct tupleDesc
 	Oid			tdtypeid;		/* composite type ID for tuple type */
 	int32		tdtypmod;		/* typmod for tuple type */
 	bool		tdhasoid;		/* tuple has oid attribute in its header */
+	bool		tdhaswidecid;	/* stores both cmin and cmax */
 	int			tdrefcount;		/* reference count, or -1 if not counting */
 }	*TupleDesc;
 
diff --git a/src/include/access/xact.h b/src/include/access/xact.h
index 96502ce..cb7916d 100644
--- a/src/include/access/xact.h
+++ b/src/include/access/xact.h
@@ -111,6 +111,7 @@ typedef void (*SubXactCallback) (SubXactEvent event, SubTransactionId mySubid,
 #define XLOG_XACT_ABORT_PREPARED	0x40
 #define XLOG_XACT_ASSIGNMENT		0x50
 #define XLOG_XACT_COMMIT_COMPACT	0x60
+#define XLOG_XACT_CCI				0x70
 
 typedef struct xl_xact_assignment
 {
@@ -148,6 +149,12 @@ typedef struct xl_xact_commit
 
 #define MinSizeOfXactCommit offsetof(xl_xact_commit, xnodes)
 
+typedef struct xl_xact_cci
+{
+	TransactionId top_xid;
+	CommandId	command_id;
+} xl_xact_cci;
+
 /*
  * These flags are set in the xinfo fields of WAL commit records,
  * indicating a variety of additional actions that need to occur
@@ -225,6 +232,7 @@ extern void SetCurrentStatementStartTimestamp(void);
 extern int	GetCurrentTransactionNestLevel(void);
 extern bool TransactionIdIsCurrentTransactionId(TransactionId xid);
 extern void CommandCounterIncrement(void);
+extern void CommandModifiedCatalog(void);
 extern void ForceSyncCommit(void);
 extern void StartTransactionCommand(void);
 extern void CommitTransactionCommand(void);
diff --git a/src/include/replication/reorderbuffer.h b/src/include/replication/reorderbuffer.h
index 39fd25b..84e282b 100644
--- a/src/include/replication/reorderbuffer.h
+++ b/src/include/replication/reorderbuffer.h
@@ -330,9 +330,6 @@ void		ReorderBufferSetBaseSnapshot(ReorderBuffer *, TransactionId, XLogRecPtr ls
 void		ReorderBufferAddSnapshot(ReorderBuffer *, TransactionId, XLogRecPtr lsn, struct SnapshotData *snap);
 void ReorderBufferAddNewCommandId(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
 							 CommandId cid);
-void ReorderBufferAddNewTupleCids(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
-							 RelFileNode node, ItemPointerData pt,
-						 CommandId cmin, CommandId cmax, CommandId combocid);
 void ReorderBufferAddInvalidations(ReorderBuffer *, TransactionId, XLogRecPtr lsn,
 							  Size nmsgs, SharedInvalidationMessage *msgs);
 bool		ReorderBufferIsXidKnown(ReorderBuffer *, TransactionId xid);
diff --git a/src/include/replication/snapbuild.h b/src/include/replication/snapbuild.h
index bd72973..a69d794 100644
--- a/src/include/replication/snapbuild.h
+++ b/src/include/replication/snapbuild.h
@@ -64,7 +64,7 @@ extern SnapBuildState SnapBuildCurrentState(SnapBuild *snapstate);
 extern bool SnapBuildXactNeedsSkip(SnapBuild *snapstate, XLogRecPtr ptr);
 
 /* don't want to include heapam_xlog.h */
-struct xl_heap_new_cid;
+struct xl_xact_cci;
 struct xl_running_xacts;
 
 extern void SnapBuildCommitTxn(SnapBuild *builder, XLogRecPtr lsn,
@@ -76,7 +76,7 @@ extern void SnapBuildAbortTxn(SnapBuild *builder, XLogRecPtr lsn,
 extern bool SnapBuildProcessChange(SnapBuild *builder, TransactionId xid,
 								   XLogRecPtr lsn);
 extern void SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
-								   XLogRecPtr lsn, struct xl_heap_new_cid *cid);
+								   XLogRecPtr lsn, struct xl_xact_cci *cid);
 extern void SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn,
 										 struct xl_running_xacts *running);
 extern void SnapBuildSerializationPoint(SnapBuild *builder, XLogRecPtr lsn);
diff --git a/src/include/utils/tqual.h b/src/include/utils/tqual.h
index dfb190b..f1175fa 100644
--- a/src/include/utils/tqual.h
+++ b/src/include/utils/tqual.h
@@ -89,20 +89,11 @@ extern void HeapTupleSetHintBits(HeapTupleHeader tuple, Buffer buffer,
 extern bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple);
 
 /* Support for catalog timetravel */
-struct HTAB;
 extern bool HeapTupleSatisfiesMVCCDuringDecoding(HeapTuple htup,
                                                  Snapshot snapshot, Buffer buffer);
-extern void SetupDecodingSnapshots(Snapshot snapshot_now, struct HTAB *tuplecids);
+extern void SetupDecodingSnapshots(Snapshot snapshot_now);
 extern void RevertFromDecodingSnapshots(void);
 extern void SuspendDecodingSnapshots(void);
 extern void UnSuspendDecodingSnapshots(void);
 extern bool DecodingSnapshotsActive(void);
-
-/*
- * To avoid leaking to much knowledge about reorderbuffer implementation
- * details this is implemented in reorderbuffer.c not tqual.c.
- */
-extern bool ResolveCminCmaxDuringDecoding(struct HTAB *tuplecid_data, HeapTuple htup,
-										  Buffer buffer,
-										  CommandId *cmin, CommandId *cmax);
 #endif   /* TQUAL_H */
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 648caa0..04a91ff 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2463,7 +2463,6 @@ xl_heap_insert
 xl_heap_lock
 xl_heap_lock_updated
 xl_heap_multi_insert
-xl_heap_new_cid
 xl_heap_newpage
 xl_heap_update
 xl_heap_visible
@@ -2486,6 +2485,7 @@ xl_tblspc_drop_rec
 xl_xact_abort
 xl_xact_abort_prepared
 xl_xact_assignment
+xl_xact_cci
 xl_xact_commit
 xl_xact_commit_compact
 xl_xact_commit_prepared
-- 
1.8.4.21.g992c386.dirty

