Hi,

On Wed, Jul29, 2026 at 04:32 PM Boyu Yang wrote:

While studying how limit_block is handled during incremental backup, I
found a scenario that leads to data inconsistency: a table is
truncated by vacuum and then regrown by a bulk insert (COPY). After
combining the incremental backup with the full backup, deleted rows
reappear. Here is a POC:
...

Analyze
=======
Here is a view for blocks layout where only "id" is shown here.

(1) In full backup [1, 2, 3, 4, .... , 20, 21, 22, .... , 39 , 40]

(2) After truncate [1] limit_block = 1

(3) After bulk insert [1, 1000, 1001, 1002, ... , 1019 , NULL, NULL,
NULL, ... , NULL] 33 blocks totally

(4) In the incremental Backup, the INCREMENTAL.relfilenode
blocks changed = [1000, 1001, .... , 1019]
truncation_block_length = 33

(5) combine backup [1, 1000, 1001, .... , 1018 ,1019, 22, 23 , ...39 ,
40]
     |___   From incremental  ___|   |___ From full ____|


While investigating incremental backups after VACUUM truncation, I
also faced this issue.

Fix
===
My proposed fix is admittedly brute-force: if a truncation happened
anywhere within a segment, we cannot tell how many of the blocks that
were later added back are all-zero and never WAL-logged, so the safest
option is to back up that entire segment fully.

So: instead of comparing limit_block with segno * RELSEG_SIZE, we can
compare it with (segno + 1) * RELSEG_SIZE

Rather than backing up the entire affected segment, I am thinking shall change the following comparison to '>' so that *truncation_block_length is clamped to relative_limit, matching the comment (the per-existing codes appears to be inverted relative to the comment already):

/*
 * We can't set a truncation_block_length in excess of the limit block
 * number (relativized to the current segment). To do so would be to
 * treat blocks from older backups as valid current contents even if
 * they were subsequently truncated away.
 */
if (*truncation_block_length < relative_limit)
        *truncation_block_length = relative_limit;

When clamping occurs, we also need to include the segment's final block in the incremental file if it is not already present (and fall back to a full file backup if that pushes the block count past the 90% threshold). This ensures that reconstruction preserves the segment's actual length rather than dropping trailing unwritten blocks, which is especially important when a subsequent segment exists. Attached is a patch to show this idea and a TAP test.

--
Best Regards,
Zhijie Hou
From 050f28b7471171cb8db5b1b3f67e6b5611a909af Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Sun, 29 Nov 2026 22:51:55 +0800
Subject: [PATCH v1] Fix stale blocks in incremental backups after relation
 truncation.

When a relation is truncated and later extended with unwritten
zero-filled blocks before an incremental backup, such as during COPY
bulk extension, GetFileBackupMethod() sets truncation_block_length to
the current file size rather than clamping it to the WAL summary's
limit block. Because the comparison against relative_limit used '<'
instead of '>', pg_combinebackup treats those unwritten blocks as
unchanged and copies pre-truncation blocks from the earlier backup,
bringing back deleted rows and leaving indexes inconsistent with the
heap. When the current segment size was smaller than relative_limit,
the reversed comparison also inflated truncation_block_length past the
segment's actual block count.

Fix this by clamping truncation_block_length down to relative_limit
when the current segment size exceeds it. When clamping occurs, also
include the segment's final block in the incremental file if it is not
already present (falling back to a full file backup if that pushes the
modified block count past the 90% threshold), so that reconstruction
preserves the segment's current length while zero-filling any unwritten
blocks at or above relative_limit.

With truncation_block_length no longer raised above the segment's
current block count (which is already bounded by RELSEG_SIZE), the
subsequent RELSEG_SIZE cap added by commit ecd275718be can no longer be
reached, so remove it.

Note that incremental backups taken before this fix already record the
unclamped truncation_block_length in their incremental files, so a new
backup should be taken from an uncorrupted server after updating.

Author: Zhijie Hou <[email protected]>
Backpatch-through: 17
---
 src/backend/backup/basebackup_incremental.c   | 36 +++++++---
 .../pg_combinebackup/t/011_ib_truncation.pl   | 65 +++++++++++++++++--
 2 files changed, 86 insertions(+), 15 deletions(-)

diff --git a/src/backend/backup/basebackup_incremental.c 
b/src/backend/backup/basebackup_incremental.c
index 233da98043c..e35f4d1d032 100644
--- a/src/backend/backup/basebackup_incremental.c
+++ b/src/backend/backup/basebackup_incremental.c
@@ -857,7 +857,6 @@ GetFileBackupMethod(IncrementalBackupInfo *ib, const char 
*path,
                for (i = 0; i < nblocks; ++i)
                        relative_block_numbers[i] -= start_blkno;
        }
-       *num_blocks_required = nblocks;
 
        /*
         * The truncation block length is the minimum length of the 
reconstructed
@@ -877,19 +876,36 @@ GetFileBackupMethod(IncrementalBackupInfo *ib, const char 
*path,
                 * number (relativized to the current segment). To do so would 
be to
                 * treat blocks from older backups as valid current contents 
even if
                 * they were subsequently truncated away.
+                *
+                * If the segment has grown past relative_limit, zero-filled 
blocks
+                * may have been added without generating WAL. Include the 
segment's
+                * last block in the backup if not already present so that
+                * reconstruction preserves the file length and zero-fills any
+                * unwritten blocks at or above relative_limit.
                 */
-               if (*truncation_block_length < relative_limit)
-                       *truncation_block_length = relative_limit;
+               if (*truncation_block_length > relative_limit)
+               {
+                       BlockNumber last_blkno = *truncation_block_length - 1;
 
-               /*
-                * We also can't set a truncation_block_length in excess of the
-                * segment size, since the reconstructed file can't be larger 
than
-                * that.
-                */
-               if (*truncation_block_length > RELSEG_SIZE)
-                       *truncation_block_length = RELSEG_SIZE;
+                       if (nblocks == 0 ||
+                               relative_block_numbers[nblocks - 1] < 
last_blkno)
+                       {
+                               Assert(nblocks < RELSEG_SIZE);
+                               relative_block_numbers[nblocks++] = last_blkno;
+
+                               /*
+                                * As above, back up the whole file if 
including the last
+                                * block means sending nearly all of the blocks.
+                                */
+                               if (nblocks * BLCKSZ > size * 0.9)
+                                       return BACK_UP_FILE_FULLY;
+                       }
+                       *truncation_block_length = relative_limit;
+               }
        }
 
+       *num_blocks_required = nblocks;
+
        /* Send it incrementally. */
        return BACK_UP_FILE_INCREMENTALLY;
 }
diff --git a/src/bin/pg_combinebackup/t/011_ib_truncation.pl 
b/src/bin/pg_combinebackup/t/011_ib_truncation.pl
index 11749286467..f18fe3e5d44 100644
--- a/src/bin/pg_combinebackup/t/011_ib_truncation.pl
+++ b/src/bin/pg_combinebackup/t/011_ib_truncation.pl
@@ -1,8 +1,9 @@
 # Copyright (c) 2025-2026, PostgreSQL Global Development Group
 #
-# This test aims to validate two things: (1) that the calculated truncation
-# block never exceeds the segment size and (2) that the correct limit block
-# length is calculated for the VM fork.
+# This test aims to validate three things: (1) that the calculated truncation
+# block never exceeds the segment size, (2) that the correct limit block
+# length is calculated for the VM fork, and (3) that truncating and regrowing
+# a relation with unwritten zero-filled blocks does not restore stale blocks.
 
 use strict;
 use warnings FATAL => 'all';
@@ -13,7 +14,12 @@ use Test::More;
 # Initialize primary node
 my $primary = PostgreSQL::Test::Cluster->new('primary');
 $primary->init(has_archiving => 1, allows_streaming => 1);
-$primary->append_conf('postgresql.conf', 'summarize_wal = on');
+# Raise shared_buffers above the 1MB test default so COPY can extend
+# relations by multiple blocks at once.
+$primary->append_conf('postgresql.conf', <<EOF);
+summarize_wal = on
+shared_buffers = 2048
+EOF
 $primary->start;
 
 # Backup locations
@@ -115,7 +121,56 @@ my $restored_count =
 is($restored_count, $rows_after_truncation,
        'Restored backup has correct row count');
 
-$primary->stop;
 $restored->stop;
 
+# Now truncate t to two blocks and regrow it via COPY with a low fillfactor so
+# that COPY bulk-extends an extra unwritten zero-filled block.  Combining a
+# single incremental backup with the full backup must zero-fill that block
+# rather than copying a pre-truncation block from the full backup, while
+# preserving the relation's block length.
+my $pad =
+  '0123456789ABCDEF0123456789ABCDEF' x int($block_size / (2 * 32));
+my $t_relpath =
+  $primary->safe_psql('postgres', "SELECT pg_relation_filepath('t');");
+(my $t_inc_relpath = $t_relpath) =~ s{([^/]+)$}{INCREMENTAL.$1};
+
+$primary->safe_psql('postgres', <<EOF);
+ALTER TABLE t SET (fillfactor = 10);
+DELETE FROM t WHERE id > 2;
+VACUUM (TRUNCATE) t;
+COPY t FROM STDIN;
+100    $pad
+\\.
+EOF
+
+$t_blocks = $primary->safe_psql('postgres',
+       "SELECT pg_relation_size('t') / $block_size;");
+is($t_blocks, '4', 'COPY bulk extension left a trailing zero-filled block');
+
+$primary->backup('incr2',
+       backup_options => [ '--incremental', "$full_backup/backup_manifest" ]);
+$primary->stop;
+
+ok(-f "$backup_path/incr2/$t_inc_relpath",
+       'truncated and regrown relation was backed up incrementally');
+
+my $restored2 = PostgreSQL::Test::Cluster->new('node3');
+$restored2->init_from_backup($primary, 'incr2',
+       combine_with_prior => ['full']);
+$restored2->start();
+
+my $restored2_rows = $restored2->safe_psql(
+       'postgres',
+       "SELECT count(*),
+               count(*) FILTER (WHERE id BETWEEN 3 AND $target_rows)
+       FROM t;");
+is($restored2_rows, '3|0',
+       'restored backup does not retain rows from truncated blocks');
+my $restored2_blocks = $restored2->safe_psql('postgres',
+       "SELECT pg_relation_size('t') / $block_size;");
+is($restored2_blocks, '4',
+       'restored backup preserves relation block length');
+
+$restored2->stop;
+
 done_testing();
-- 
2.54.0 (Apple Git-157)

Reply via email to