# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group # # Combining incremental backups of CFS (compressed) relations. # # pg_combinebackup rebuilds data files by applying per-page WAL # summaries, but CFS sidecar files (.cfp/.cfsmap/.cfsjrn) are not # covered by those summaries and are carried whole by every incremental # backup. These scenarios verify that a cluster restored from a # combined backup holds complete, readable CFS data with structurally # valid sidecars in the situations where this is most likely to break: # # * the whole relation lifecycle (growth, TRUNCATE, VACUUM FULL, # DROP, pg_cfs_compact) happening between the full and the # incremental backup, cross-checked by PITR from both backups; # * a chain of incremental backups across a timeline fork, with a # compaction swapping the sidecar pair between generations; # * an incremental backup taken right after promoting a standby at # an arbitrary LSN, with a compaction in the promotion window; # * --link mode, where restored sidecars must be hard links of the # newest backup's copies, never of a stale full-backup copy; # * the truncation math for segmented .cfp files when # VACUUM (TRUNCATE) shrinks a relation between the two backups. use strict; use warnings FATAL => 'all'; use File::Compare qw(compare); use PostgreSQL::Test::Cluster; use PostgreSQL::Test::Utils; use Test::More; # Assert that the CFS sidecar files of relation $rel on node $node are # structurally valid. sub cfs_sidecars_ok { my ($node, $rel, $desc) = @_; is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('$rel'::regclass, true)" ), 't', $desc); } # True if both paths resolve to the same inode (i.e. are hard links of # each other). sub same_inode { my ($a, $b) = @_; my @sa = stat($a) or return 0; my @sb = stat($b) or return 0; return $sa[0] == $sb[0] && $sa[1] == $sb[1]; } #---------------------------------------------------------------------- # Full + incremental backup cycle over the whole CFS relation # lifecycle: growth, TRUNCATE, VACUUM FULL, DROP and explicit # compaction (pg_cfs_compact) between the backups. PITR to the same # LSN from the full backup and from the combined incremental one must # produce identical logical dumps, and every surviving CFS relation # must pass pg_cfs_check on the restored cluster. #---------------------------------------------------------------------- { # Can be changed to test the other modes. my $mode = $ENV{PG_TEST_PG_COMBINEBACKUP_MODE} || '--copy'; note "testing using mode $mode"; # Set up a new database instance. my $primary = PostgreSQL::Test::Cluster->new('primary'); $primary->init(has_archiving => 1, allows_streaming => 1); $primary->append_conf('postgresql.conf', 'summarize_wal = on'); $primary->start; # Create the CFS test tables, each with some data. $primary->safe_psql('postgres', <backup_dir . '/backup1'; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $backup1path, '--checkpoint' => 'fast', ], "full backup"); # Now make the lifecycle changes. $primary->safe_psql('postgres', <backup_dir . '/backup2'; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $backup2path, '--checkpoint' => 'fast', '--incremental' => $backup1path . '/backup_manifest' ], "incremental backup"); # Find an LSN to which either backup can be recovered. my $lsn = $primary->safe_psql('postgres', "SELECT pg_current_wal_lsn();"); # Make sure that the WAL segment containing that LSN has been archived. # PostgreSQL won't issue two consecutive XLOG_SWITCH records, and the backup # just issued one, so call txid_current() to generate some WAL activity # before calling pg_switch_wal(). $primary->safe_psql('postgres', 'SELECT txid_current();'); $primary->safe_psql('postgres', 'SELECT pg_switch_wal()'); # Now wait for the LSN we chose above to be archived. my $archive_wait_query = "SELECT pg_walfile_name('$lsn') <= last_archived_wal FROM pg_stat_archiver;"; $primary->poll_query_until('postgres', $archive_wait_query) or die "Timed out while waiting for WAL segment to be archived"; # Perform PITR from the full backup. Disable archive_mode so that the archive # doesn't find out about the new timeline; that way, the later PITR below will # choose the same timeline. my $pitr1 = PostgreSQL::Test::Cluster->new('pitr1'); $pitr1->init_from_backup( $primary, 'backup1', standby => 1, has_restoring => 1); $pitr1->append_conf( 'postgresql.conf', qq{ recovery_target_lsn = '$lsn' recovery_target_action = 'promote' archive_mode = 'off' }); $pitr1->start(); # Perform PITR to the same LSN from the incremental backup. Use the same # basic configuration as before. my $pitr2 = PostgreSQL::Test::Cluster->new('pitr2'); $pitr2->init_from_backup( $primary, 'backup2', standby => 1, has_restoring => 1, combine_with_prior => ['backup1'], combine_mode => $mode); $pitr2->append_conf( 'postgresql.conf', qq{ recovery_target_lsn = '$lsn' recovery_target_action = 'promote' archive_mode = 'off' }); $pitr2->start(); # Wait until both servers exit recovery. $pitr1->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery();") or die "Timed out while waiting apply to reach LSN $lsn"; $pitr2->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery();") or die "Timed out while waiting apply to reach LSN $lsn"; # Perform a logical dump of each server, and check that they match. my $backupdir = $primary->backup_dir; my $dump1 = $backupdir . '/pitr1.dump'; my $dump2 = $backupdir . '/pitr2.dump'; $pitr1->command_ok( [ 'pg_dumpall', '--restrict-key=test', '--no-sync', '--no-unlogged-table-data', '--file' => $dump1, '--dbname' => $pitr1->connstr('postgres'), ], 'dump from PITR 1'); $pitr2->command_ok( [ 'pg_dumpall', '--restrict-key=test', '--no-sync', '--no-unlogged-table-data', '--file' => $dump2, '--dbname' => $pitr2->connstr('postgres'), ], 'dump from PITR 2'); compare_files($dump1, $dump2, "contents of dumps match for both PITRs"); # Every surviving CFS relation must be structurally sound on the cluster # restored from the combined incremental backup, and the row counts must # reflect the post-change state. my %expected_rows = ( will_grow => 5000, will_shrink => 0, will_get_vacuumed => 100, will_get_rewritten => 100, will_get_compacted => 100,); for my $rel (sort keys %expected_rows) { is($pitr2->safe_psql('postgres', "SELECT count(*) FROM $rel"), "$expected_rows{$rel}", "$rel row count after incremental restore"); cfs_sidecars_ok($pitr2, $rel, "$rel sidecars intact after incremental restore"); } } #---------------------------------------------------------------------- # A chain of incremental backups across a timeline fork. Between the # backup generations the table is compacted, so the .cfp/.cfsmap pair # is swapped wholesale on one generation and must still combine # correctly with the others; every backup in the chain is verified # with pg_verifybackup. #---------------------------------------------------------------------- { # Can be changed to test the other modes. my $mode = $ENV{PG_TEST_PG_COMBINEBACKUP_MODE} || '--copy'; note "testing using mode $mode"; # Set up a new database instance. my $node1 = PostgreSQL::Test::Cluster->new('node1'); $node1->init(has_archiving => 1, allows_streaming => 1); $node1->append_conf('postgresql.conf', 'summarize_wal = on'); $node1->start; # Create a table and insert a test row into it. $node1->safe_psql('postgres', <backup_dir . '/backup1'; $node1->command_ok( [ 'pg_basebackup', '--pgdata' => $backup1path, '--no-sync', '--checkpoint' => 'fast' ], "full backup from node1"); # Insert a second row on the original node. $node1->safe_psql('postgres', <backup_dir . '/backup2'; $node1->command_ok( [ 'pg_basebackup', '--pgdata' => $backup2path, '--no-sync', '--checkpoint' => 'fast', '--incremental' => $backup1path . '/backup_manifest' ], "incremental backup from node1"); # Restore the incremental backup and use it to create a new node. my $node2 = PostgreSQL::Test::Cluster->new('node2'); $node2->init_from_backup($node1, 'backup2', combine_with_prior => ['backup1']); $node2->start(); # Insert rows on both nodes. The compaction on node2 swaps the CFS # sidecar pair wholesale between backup generations. $node1->safe_psql('postgres', <safe_psql('postgres', <backup_dir . '/backup3'; $node2->command_ok( [ 'pg_basebackup', '--pgdata' => $backup3path, '--no-sync', '--checkpoint' => 'fast', '--incremental' => $backup2path . '/backup_manifest' ], "incremental backup from node2"); # Restore the incremental backup and use it to create a new node. my $node3 = PostgreSQL::Test::Cluster->new('node3'); $node3->init_from_backup( $node1, 'backup3', combine_with_prior => [ 'backup1', 'backup2' ], combine_mode => $mode); $node3->start(); # Let's insert one more row. $node3->safe_psql('postgres', <safe_psql('postgres', <command_ok( [ 'pg_verifybackup', $node1->backup_dir . '/' . $backup_name ], "verify backup $backup_name"); } # The CFS sidecars on the final node must be structurally valid. cfs_sidecars_ok($node3, 'mytable', 'CFS sidecars intact on node3'); } #---------------------------------------------------------------------- # Incremental backup after promoting a standby at an arbitrary # (non-checkpoint) LSN. Right after the promotion the table is # compacted -- the window where a compaction could otherwise end up # half-finished relative to the promotion point. The restored node # must hold the complete data with structurally valid sidecars. #---------------------------------------------------------------------- { my $mode = $ENV{PG_TEST_PG_COMBINEBACKUP_MODE} || '--copy'; note "testing using mode $mode"; # Set up a new database instance. my $node1 = PostgreSQL::Test::Cluster->new('node1_promo'); $node1->init(has_archiving => 1, allows_streaming => 1); $node1->append_conf('postgresql.conf', 'summarize_wal = on'); $node1->append_conf('postgresql.conf', 'log_min_messages = debug1'); $node1->start; # Create a table and insert a test row into it. $node1->safe_psql('postgres', <backup_dir . '/backup1'; $node1->command_ok( [ 'pg_basebackup', '--pgdata' => $backup1path, '--no-sync', '--checkpoint' => 'fast', ], "full backup from node1"); # Checkpoint and record LSN after. $node1->safe_psql('postgres', 'CHECKPOINT'); my $lsn = $node1->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()'); # Insert a second row on the original node. $node1->safe_psql('postgres', <new('node2_promo'); $node2->init_from_backup($node1, 'backup1', has_streaming => 1); $node2->append_conf('postgresql.conf', <start(); # Wait until recovery pauses, then promote. $node2->poll_query_until('postgres', "SELECT pg_get_wal_replay_pause_state() = 'paused';"); $node2->safe_psql('postgres', "SELECT pg_promote()"); # Once promotion occurs, insert a second row on the new node. $node2->poll_query_until('postgres', "SELECT pg_is_in_recovery() = 'f';"); $node2->safe_psql('postgres', <backup_dir . '/backup2'; $node2->command_ok( [ 'pg_basebackup', '--pgdata' => $backup2path, '--no-sync', '--checkpoint' => 'fast', '--incremental' => $backup1path . '/backup_manifest', ], "incremental backup from node2"); # Restore the incremental backup and use it to create a new node. my $node3 = PostgreSQL::Test::Cluster->new('node3_promo'); $node3->init_from_backup( $node1, 'backup2', combine_with_prior => ['backup1'], combine_mode => $mode); $node3->start(); # The restored node must hold all the rows with intact CFS sidecars. my $result = $node3->safe_psql('postgres', "SELECT count(*) FROM mytable"); is($result, '101', 'rows complete after restore'); cfs_sidecars_ok($node3, 'mytable', 'CFS sidecars intact after restore'); } #---------------------------------------------------------------------- # --link mode with CFS sidecar files. Sidecars are carried whole by # every incremental backup, so the restored sidecars must be hard # links of the incremental backup's copies -- and the compacted # table's .cfp must be the new generation, not the full backup's # stale one. #---------------------------------------------------------------------- { # Set up a new database instance. my $primary = PostgreSQL::Test::Cluster->new('primary_link'); $primary->init(has_archiving => 1, allows_streaming => 1); $primary->append_conf('postgresql.conf', 'summarize_wal = on'); # We disable autovacuum to prevent "something else" to modify our test tables. $primary->append_conf('postgresql.conf', 'autovacuum = off'); $primary->start; # Create two CFS tables. $primary->safe_psql( 'postgres', q[CREATE TABLE test_1 (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO test_1 SELECT g, md5(g::text) FROM generate_series(1, 100) g; CREATE TABLE test_2 (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO test_2 SELECT g, md5(g::text) FROM generate_series(1, 100) g; CHECKPOINT;]); # Fetch information about the data files. my $test_1_path = $primary->safe_psql('postgres', "SELECT pg_relation_filepath('test_1')"); my $test_2_path = $primary->safe_psql('postgres', "SELECT pg_relation_filepath('test_2')"); # Take a full backup. my $backup1path = $primary->backup_dir . '/backup1'; $primary->command_ok( [ 'pg_basebackup', '--pgdata' => $backup1path, '--no-sync', '--checkpoint' => 'fast', '--wal-method' => 'none' ], "full backup"); # Compact test_2: the .cfp/.cfsmap pair is swapped wholesale. $primary->safe_psql('postgres', "SELECT pg_cfs_compact('test_2')"); # Take an incremental backup. my $backup2path = $primary->backup_dir . '/backup2'; $primary->command_ok( [ 'pg_basebackup', '--pgdata' => $backup2path, '--no-sync', '--checkpoint' => 'fast', '--wal-method' => 'none', '--incremental' => $backup1path . '/backup_manifest' ], "incremental backup"); # Restore the incremental backup with --link. my $restore = PostgreSQL::Test::Cluster->new('restore'); $restore->init_from_backup( $primary, 'backup2', standby => 1, has_restoring => 1, combine_with_prior => ['backup1'], combine_mode => '--link'); # CFS sidecar files cannot be block-diffed from WAL summaries (their # writes are not per-page WAL records), so every incremental backup # carries them whole. With --link the combine step must therefore link # them from the INCREMENTAL backup (the newest copy), never from the # full backup's potentially stale one. for my $suffix ('.cfp', '.cfsmap', '.cfsjrn') { my $f1 = join('/', $restore->data_dir, $test_1_path . $suffix); my $f2 = join('/', $restore->data_dir, $test_2_path . $suffix); ok( same_inode($f1, "$backup2path/$test_1_path$suffix"), "untouched table's $suffix linked from the incremental backup"); ok( same_inode($f2, "$backup2path/$test_2_path$suffix"), "compacted table's $suffix linked from the incremental backup"); } # The compacted table's restored .cfp must be the new generation, not # the full backup's stale copy. cmp_ok( compare( "$restore->data_dir/$test_2_path.cfp", "$backup1path/$test_2_path.cfp"), '!=', 0, "compacted table's .cfp is not the full backup's stale copy"); # And both tables must be fully readable with valid sidecars on the # restored node. $restore->start; for my $rel ('test_1', 'test_2') { is($restore->safe_psql('postgres', "SELECT count(*) FROM $rel"), '100', "$rel rows after --link restore"); cfs_sidecars_ok($restore, $rel, "$rel sidecars intact after --link restore"); } } #---------------------------------------------------------------------- # Incremental-backup truncation math with a CFS relation. The # calculated truncation block must never exceed the segment size; for # CFS the same class of off-by-segment bugs applies to the segmented # .cfp files and to the RESIZE that VACUUM (TRUNCATE) performs between # the two backups. The segment-boundary case only really bites in a # small-RELSEG_SIZE build; the assertions hold in any build. #---------------------------------------------------------------------- { # Initialize primary node my $primary = PostgreSQL::Test::Cluster->new('primary_trunc'); $primary->init(has_archiving => 1, allows_streaming => 1); $primary->append_conf('postgresql.conf', 'summarize_wal = on'); $primary->start; # Backup locations my $backup_path = $primary->backup_dir; my $full_backup = "$backup_path/full"; # See the core test: the boundary case is only hit with a small # RELSEG_SIZE build, the flow is verified everywhere. my $target_blocks = 6; my $block_size = $primary->safe_psql('postgres', "SELECT current_setting('block_size')::int;"); # We'll have two blocks more than the target number of blocks (one will # survive the subsequent truncation). my $target_rows = int($target_blocks + 2); my $rows_after_truncation = int($target_rows - 1); # Create a CFS test table. STORAGE PLAIN prevents TOASTing and PGLZ of # the column itself, ensuring predictable row sizes; the CFS compression # below that layer does not change the logical block count. $primary->safe_psql( 'postgres', q{ CREATE TABLE t ( id int, data text STORAGE PLAIN ) WITH (algorithm = 'lz4'); }); # The tuple size should be enough to prevent two tuples from being on the same # page. Since the template string has a length of 32 bytes, it's enough to # repeat it (block_size / (2*32)) times. $primary->safe_psql( 'postgres', "INSERT INTO t SELECT i, repeat('0123456789ABCDEF0123456789ABCDEF', ($block_size / (2*32))) FROM generate_series(1, $target_rows) i;" ); # Make sure hint bits are set. $primary->safe_psql('postgres', 'VACUUM t;'); # Verify that the relation is as large as was desired. The main fork of # a CFS relation is a small stub, so the logical block count comes from # pg_cfs_relation_size. my $t_blocks = $primary->safe_psql( 'postgres', "SELECT logical_size / current_setting('block_size')::int FROM pg_cfs_relation_size('t');"); cmp_ok($t_blocks, '>', $target_blocks, 'relation grew past the target block count'); # Take a full base backup $primary->backup('full'); # Delete rows at the logical end of the table, creating removable pages. $primary->safe_psql('postgres', "DELETE FROM t WHERE id > ($rows_after_truncation);"); # VACUUM the table. TRUNCATE is enabled by default, and is just mentioned here # for emphasis. $primary->safe_psql('postgres', 'VACUUM (TRUNCATE) t;'); # Verify expected length after truncation. $t_blocks = $primary->safe_psql( 'postgres', "SELECT logical_size / current_setting('block_size')::int FROM pg_cfs_relation_size('t');"); is($t_blocks, $rows_after_truncation, 'one block per surviving row after truncation'); cmp_ok($t_blocks, '>', $target_blocks, 'post-truncation block count as expected'); # Take an incremental backup based on the full backup manifest $primary->backup('incr', backup_options => [ '--incremental', "$full_backup/backup_manifest" ] ); # Combine full and incremental backups. my $restored = PostgreSQL::Test::Cluster->new('node2_trunc'); $restored->init_from_backup($primary, 'incr', combine_with_prior => ['full']); $restored->start(); # Check that the restored table contains the correct number of rows and # structurally valid sidecars. my $restored_count = $restored->safe_psql('postgres', "SELECT count(*) FROM t;"); is($restored_count, $rows_after_truncation, 'Restored backup has correct row count'); cfs_sidecars_ok($restored, 't', 'CFS sidecars intact after restore'); $primary->stop; $restored->stop; } done_testing();