From 720465b22e815f2738e5a942a822c5e88644cf38 Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Sat, 21 Nov 2026 11:04:57 +0000
Subject: [PATCH v1 4/4] Handle n_dead_tup in prepared transactions

The existing pgstat 2PC record cannot preserve dead-tuple deltas on both sides
of a transactional TRUNCATE. PREPARE can flush a delta for the wrong relfilenode,
leaving COMMIT PREPARED or ROLLBACK PREPARED unable to restore the correct value.

Extend the record with the current and pre-truncate dead-tuple deltas, and
restore the appropriate values when the prepared transaction is committed or
rolled back.

Keep the old released record as a prefix and distinguish the layouts by length,
so prepared transactions survive a minor-version update. Add isolation test
coverage for both outcomes.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reviewed-by:
Discussion: https://postgr.es/m/
Backpatch-through: 15
---
 src/backend/utils/activity/pgstat_relation.c | 38 +++++++++++++-------
 src/test/isolation/expected/stats.out        | 24 +++++++++++--
 src/test/isolation/expected/stats_1.out      | 24 +++++++++++--
 src/test/isolation/specs/stats.spec          |  7 ++++
 4 files changed, 76 insertions(+), 17 deletions(-)
  62.4% src/backend/utils/activity/
  31.2% src/test/isolation/expected/
   6.3% src/test/isolation/specs/

diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c
index 3c5c41be68f..8e9e95bb6b5 100644
--- a/src/backend/utils/activity/pgstat_relation.c
+++ b/src/backend/utils/activity/pgstat_relation.c
@@ -42,15 +42,17 @@ typedef struct TwoPhasePgStatRecord
 } TwoPhasePgStatRecord;
 
 /*
- * Extended 2PC state for n_ins_since_vacuum. Keep the existing record as
- * the prefix so that prepared transactions created by an older binary remain
- * readable after a minor-version update.
+ * Extended 2PC state for n_ins_since_vacuum and the dead-tuple delta. Keep
+ * the existing record as the prefix so that prepared transactions created in
+ * an earlier minor release remain readable after an update.
  */
 typedef struct TwoPhasePgStatRecordV2
 {
 	TwoPhasePgStatRecord base;
 	PgStat_Counter ins_since_vacuum;
 	PgStat_Counter ins_since_vacuum_pre_truncdrop;
+	PgStat_Counter delta_dead_tuples;
+	PgStat_Counter delta_dead_tuples_pre_truncdrop;
 } TwoPhasePgStatRecordV2;
 
 
@@ -849,6 +851,8 @@ AtPrepare_PgStat_Relations(PgStat_SubXactStatus *xact_state)
 		record.ins_since_vacuum = relstat->tab.counts_xact.ins_since_vacuum;
 		record.ins_since_vacuum_pre_truncdrop = trans->ins_since_vacuum_pre_truncdrop +
 			trans->inserted_pre_truncdrop;
+		record.delta_dead_tuples = relstat->tab.counts_xact.delta_dead_tuples;
+		record.delta_dead_tuples_pre_truncdrop = trans->delta_dead_tuples_pre_truncdrop;
 
 		RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
 							   &record, sizeof(TwoPhasePgStatRecordV2));
@@ -874,7 +878,10 @@ PostPrepare_PgStat_Relations(PgStat_SubXactStatus *xact_state)
 
 		relstat = trans->parent;
 		if (trans->truncdropped)
+		{
 			relstat->tab.counts_xact.ins_since_vacuum = 0;
+			relstat->tab.counts_xact.delta_dead_tuples = 0;
+		}
 		relstat->tab.trans = NULL;
 	}
 }
@@ -891,9 +898,9 @@ pgstat_twophase_postcommit(FullTransactionId fxid, uint16 info,
 	TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
 	TwoPhasePgStatRecordV2 *rec_v2 = (TwoPhasePgStatRecordV2 *) recdata;
 	PgStat_RelationStatus *pgstat_info;
-	bool		has_ins_since_vacuum = len >= sizeof(TwoPhasePgStatRecordV2);
+	bool		has_v2_fields = len >= sizeof(TwoPhasePgStatRecordV2);
 
-	Assert(len == sizeof(TwoPhasePgStatRecord) || has_ins_since_vacuum);
+	Assert(len == sizeof(TwoPhasePgStatRecord) || has_v2_fields);
 
 	/* Find or create a relstat entry for the rel */
 	pgstat_info = pgstat_prep_relation_pending(PGSTAT_KIND_RELATION, rec->id, rec->shared);
@@ -905,11 +912,12 @@ pgstat_twophase_postcommit(FullTransactionId fxid, uint16 info,
 	pgstat_info->tab.truncdropped = rec->truncdropped;
 	if (rec->truncdropped)
 	{
-		/* forget live/dead stats seen by backend thus far */
+		/* forget live stats seen by backend thus far */
 		pgstat_info->tab.counts_xact.delta_live_tuples = 0;
-		pgstat_info->tab.counts_xact.delta_dead_tuples = 0;
+		pgstat_info->tab.counts_xact.delta_dead_tuples =
+			has_v2_fields ? rec_v2->delta_dead_tuples : 0;
 		pgstat_info->tab.counts_xact.ins_since_vacuum =
-			has_ins_since_vacuum ? rec_v2->ins_since_vacuum : 0;
+			has_v2_fields ? rec_v2->ins_since_vacuum : 0;
 	}
 	pgstat_info->tab.counts_xact.delta_live_tuples +=
 		rec->tuples_inserted - rec->tuples_deleted;
@@ -935,9 +943,9 @@ pgstat_twophase_postabort(FullTransactionId fxid, uint16 info,
 	TwoPhasePgStatRecordV2 *rec_v2 = (TwoPhasePgStatRecordV2 *) recdata;
 	PgStat_RelationStatus *pgstat_info;
 	PgStat_Counter ins_since_vacuum = rec->tuples_inserted;
-	bool		has_ins_since_vacuum = len >= sizeof(TwoPhasePgStatRecordV2);
+	bool		has_v2_fields = len >= sizeof(TwoPhasePgStatRecordV2);
 
-	Assert(len == sizeof(TwoPhasePgStatRecord) || has_ins_since_vacuum);
+	Assert(len == sizeof(TwoPhasePgStatRecord) || has_v2_fields);
 
 	/* Find or create a relstat entry for the rel */
 	pgstat_info = pgstat_prep_relation_pending(PGSTAT_KIND_RELATION, rec->id, rec->shared);
@@ -948,16 +956,20 @@ pgstat_twophase_postabort(FullTransactionId fxid, uint16 info,
 		rec->tuples_inserted = rec->inserted_pre_truncdrop;
 		rec->tuples_updated = rec->updated_pre_truncdrop;
 		rec->tuples_deleted = rec->deleted_pre_truncdrop;
-		if (has_ins_since_vacuum)
+		if (has_v2_fields)
+		{
+			pgstat_info->tab.counts_xact.delta_dead_tuples += rec_v2->delta_dead_tuples_pre_truncdrop;
 			ins_since_vacuum += rec_v2->ins_since_vacuum + rec_v2->ins_since_vacuum_pre_truncdrop;
+		}
 		else
 			ins_since_vacuum = rec->tuples_inserted;
 	}
 	pgstat_info->tab.counts_xact.tuples_inserted += rec->tuples_inserted;
 	pgstat_info->tab.counts_xact.tuples_updated += rec->tuples_updated;
 	pgstat_info->tab.counts_xact.tuples_deleted += rec->tuples_deleted;
-	pgstat_info->tab.counts_xact.delta_dead_tuples +=
-		rec->tuples_inserted + rec->tuples_updated;
+	if (!rec->truncdropped || !has_v2_fields)
+		pgstat_info->tab.counts_xact.delta_dead_tuples +=
+			rec->tuples_inserted + rec->tuples_updated;
 	pgstat_info->tab.counts_xact.ins_since_vacuum += ins_since_vacuum;
 }
 
diff --git a/src/test/isolation/expected/stats.out b/src/test/isolation/expected/stats.out
index 56b489d5495..1bc3f04d960 100644
--- a/src/test/isolation/expected/stats.out
+++ b/src/test/isolation/expected/stats.out
@@ -2830,7 +2830,7 @@ seq_scan|seq_tup_read|n_tup_ins|n_tup_upd|n_tup_del|n_live_tup|n_dead_tup|vacuum
 (1 row)
 
 
-starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s1_ff s2_commit_prepared_a s2_ff s1_table_stats s1_trunc_ins_since_vacuum
+starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s1_ff s2_commit_prepared_a s2_ff s1_table_stats s1_trunc_ins_since_vacuum s1_trunc_dead_tuples
 pg_stat_force_next_flush
 ------------------------
                         
@@ -2894,6 +2894,16 @@ n_ins_since_vacuum
                 10
 (1 row)
 
+step s1_trunc_dead_tuples: 
+    SELECT pg_stat_get_dead_tuples(tso.oid) AS n_dead_tup
+    FROM test_stat_oid AS tso
+    WHERE tso.name = 'test_stat_trunc'
+
+n_dead_tup
+----------
+         5
+(1 row)
+
 
 starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_table_truncate s1_table_insert_k1 s1_table_update_k1 s1_prepare_a s1_rollback_prepared_a s1_ff s1_table_stats
 pg_stat_force_next_flush
@@ -2935,7 +2945,7 @@ seq_scan|seq_tup_read|n_tup_ins|n_tup_upd|n_tup_del|n_live_tup|n_dead_tup|vacuum
 (1 row)
 
 
-starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s2_rollback_prepared_a s1_ff s2_ff s1_table_stats s1_trunc_ins_since_vacuum
+starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s2_rollback_prepared_a s1_ff s2_ff s1_table_stats s1_trunc_ins_since_vacuum s1_trunc_dead_tuples
 pg_stat_force_next_flush
 ------------------------
                         
@@ -2999,6 +3009,16 @@ n_ins_since_vacuum
                 20
 (1 row)
 
+step s1_trunc_dead_tuples: 
+    SELECT pg_stat_get_dead_tuples(tso.oid) AS n_dead_tup
+    FROM test_stat_oid AS tso
+    WHERE tso.name = 'test_stat_trunc'
+
+n_dead_tup
+----------
+        10
+(1 row)
+
 
 starting permutation: s1_table_insert s1_table_update_k1 s1_begin s1_table_delete_k1 s1_table_insert_k1 s1_table_update_k1 s1_table_update_k1 s1_table_drop s1_prepare_a s1_rollback_prepared_a s1_ff s1_table_stats
 pg_stat_force_next_flush
diff --git a/src/test/isolation/expected/stats_1.out b/src/test/isolation/expected/stats_1.out
index 9560f3a4d51..dd1bb370220 100644
--- a/src/test/isolation/expected/stats_1.out
+++ b/src/test/isolation/expected/stats_1.out
@@ -2844,7 +2844,7 @@ seq_scan|seq_tup_read|n_tup_ins|n_tup_upd|n_tup_del|n_live_tup|n_dead_tup|vacuum
 (1 row)
 
 
-starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s1_ff s2_commit_prepared_a s2_ff s1_table_stats s1_trunc_ins_since_vacuum
+starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s1_ff s2_commit_prepared_a s2_ff s1_table_stats s1_trunc_ins_since_vacuum s1_trunc_dead_tuples
 pg_stat_force_next_flush
 ------------------------
                         
@@ -2910,6 +2910,16 @@ n_ins_since_vacuum
                 20
 (1 row)
 
+step s1_trunc_dead_tuples: 
+    SELECT pg_stat_get_dead_tuples(tso.oid) AS n_dead_tup
+    FROM test_stat_oid AS tso
+    WHERE tso.name = 'test_stat_trunc'
+
+n_dead_tup
+----------
+        10
+(1 row)
+
 
 starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_table_truncate s1_table_insert_k1 s1_table_update_k1 s1_prepare_a s1_rollback_prepared_a s1_ff s1_table_stats
 pg_stat_force_next_flush
@@ -2953,7 +2963,7 @@ seq_scan|seq_tup_read|n_tup_ins|n_tup_upd|n_tup_del|n_live_tup|n_dead_tup|vacuum
 (1 row)
 
 
-starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s2_rollback_prepared_a s1_ff s2_ff s1_table_stats s1_trunc_ins_since_vacuum
+starting permutation: s1_table_insert s1_begin s1_table_update_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p1 s1_trunc_insert_five s1_rollback_to_p1 s1_table_truncate s1_trunc_truncate s1_table_insert_k1 s1_table_update_k1 s1_trunc_insert_five s1_savepoint_p2 s1_trunc_insert_five s1_rollback_to_p2 s1_prepare_a s2_rollback_prepared_a s1_ff s2_ff s1_table_stats s1_trunc_ins_since_vacuum s1_trunc_dead_tuples
 pg_stat_force_next_flush
 ------------------------
                         
@@ -3019,6 +3029,16 @@ n_ins_since_vacuum
                 20
 (1 row)
 
+step s1_trunc_dead_tuples: 
+    SELECT pg_stat_get_dead_tuples(tso.oid) AS n_dead_tup
+    FROM test_stat_oid AS tso
+    WHERE tso.name = 'test_stat_trunc'
+
+n_dead_tup
+----------
+        10
+(1 row)
+
 
 starting permutation: s1_table_insert s1_table_update_k1 s1_begin s1_table_delete_k1 s1_table_insert_k1 s1_table_update_k1 s1_table_update_k1 s1_table_drop s1_prepare_a s1_rollback_prepared_a s1_ff s1_table_stats
 pg_stat_force_next_flush
diff --git a/src/test/isolation/specs/stats.spec b/src/test/isolation/specs/stats.spec
index 72c7b993a65..a33fed26e9a 100644
--- a/src/test/isolation/specs/stats.spec
+++ b/src/test/isolation/specs/stats.spec
@@ -127,6 +127,11 @@ step s1_trunc_ins_since_vacuum {
     FROM test_stat_oid AS tso
     WHERE tso.name = 'test_stat_trunc'
 }
+step s1_trunc_dead_tuples {
+    SELECT pg_stat_get_dead_tuples(tso.oid) AS n_dead_tup
+    FROM test_stat_oid AS tso
+    WHERE tso.name = 'test_stat_trunc'
+}
 
 # SLRU stats steps
 step s1_slru_save_stats {
@@ -599,6 +604,7 @@ permutation
   s2_ff
   s1_table_stats
   s1_trunc_ins_since_vacuum
+  s1_trunc_dead_tuples
 
 # S1 prepares, S1 aborts prepared
 permutation
@@ -637,6 +643,7 @@ permutation
   s1_ff s2_ff
   s1_table_stats
   s1_trunc_ins_since_vacuum
+  s1_trunc_dead_tuples
 
 
 ### 2PC: rolled back drop maintains live / dead counters
-- 
2.34.1

