# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group # # src/test/recovery/t/507_cfs_backup.pl # # Backup and restore of a cluster with CFS-compressed relations. # # The CFS sidecar files (.cfp/.cfsmap/.cfsjrn) are plain files for the # backup tools: they are copied as they are, possibly mid-append, and # backup recovery repairs them through the WAL stream and the CFS # journal just like it does for heap pages. The scenarios cover # pg_rewind from a running source after divergence, incremental # pg_basebackup chains combined with pg_combinebackup, and a low-level # backup made with pg_backup_start/stop plus a raw file copy. Restored # and rewound nodes must serve exactly the source contents and pass the # structural pg_cfs_check(). use strict; use warnings FATAL => 'all'; use PostgreSQL::Test::Cluster; use PostgreSQL::Test::Utils; use File::Copy; use File::Path qw(rmtree); use Test::More; # ---------------------------------------------------------------------- # pg_rewind against CFS-compressed relations: a promoted standby and the # old primary write divergent CFS data, then the old primary is rewound # from the running source and restarted as a standby. The CFS contents # must match the source exactly: divergent rows discarded, source-only # tables copied, target-only tables removed, and new CFS writes from the # source replayed. # ---------------------------------------------------------------------- { # Initialize the primary node. my $primary = PostgreSQL::Test::Cluster->new('cfs_rewind_primary'); $primary->init(allows_streaming => 1); $primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s\n" . "wal_keep_size = 320MB\n"); $primary->start; # Skip when LZ4 is not compiled in. my $configure = $primary->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS backup tests'; } # Create a CFS table on the primary and populate it. $primary->safe_psql('postgres', "CREATE TABLE cfs_rw (id int, payload text) WITH (algorithm = 'lz4')" ); $primary->safe_psql('postgres', "INSERT INTO cfs_rw SELECT g, repeat('a' || g, 100) " . "FROM generate_series(1, 500) g"); $primary->safe_psql('postgres', "CHECKPOINT"); my $primary_dir = $primary->data_dir; my $primary_path = $primary->safe_psql('postgres', "SELECT pg_relation_filepath('cfs_rw')"); ok( -f "$primary_dir/$primary_path.cfp", 'CFS table has .cfp sidecar on primary'); # Create a standby and promote it. $primary->backup('my_backup'); my $standby = PostgreSQL::Test::Cluster->new('cfs_rewind_standby'); $standby->init_from_backup($primary, 'my_backup', has_streaming => 1); $standby->start; $primary->wait_for_catchup($standby); $standby->promote; $standby->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery()") or die "standby did not promote"; # Diverge: write different CFS data on both nodes. # New CFS rows on the promoted standby (the rewind *source*). $standby->safe_psql('postgres', "INSERT INTO cfs_rw SELECT g, repeat('s' || g, 100) " . "FROM generate_series(501, 700) g"); # Divergent CFS rows on the old primary (the rewind *target*): they # must disappear after the rewind. $primary->safe_psql('postgres', "INSERT INTO cfs_rw SELECT g, repeat('p' || g, 100) " . "FROM generate_series(501, 700) g"); # A CFS table that exists only on the target must be removed by the # rewind. $primary->safe_psql('postgres', "CREATE TABLE cfs_rw_gone (id int, payload text) WITH (algorithm = 'lz4')" ); $primary->safe_psql('postgres', "INSERT INTO cfs_rw_gone SELECT g, repeat('x' || g, 100) " . "FROM generate_series(1, 50) g"); # A CFS table created only on the source must appear on the target. $standby->safe_psql('postgres', "CREATE TABLE cfs_rw_new (id int, payload text) WITH (algorithm = 'lz4')" ); $standby->safe_psql('postgres', "INSERT INTO cfs_rw_new SELECT g, repeat('n' || g, 100) " . "FROM generate_series(1, 200) g"); $standby->safe_psql('postgres', "CHECKPOINT"); $primary->safe_psql('postgres', "CHECKPOINT"); # Rewind the old primary from the running promoted standby. $primary->stop('immediate'); # Plant transient compaction leftovers on the source, exactly as an # aborted compaction would leave them (its commit phase refuses while # a non-exclusive backup is in progress). pg_rewind copies non-relation # files in toto, so the leftovers travel to the target; the target's # startup recovery cleanup must discard them again. my $standby_dir = $standby->data_dir; my $standby_path = $standby->safe_psql('postgres', "SELECT pg_relation_filepath('cfs_rw')"); open(my $orphan_fh, '>', "$standby_dir/$standby_path.cfp.tmp") or BAIL_OUT("could not create the .cfp.tmp leftover"); close($orphan_fh); open($orphan_fh, '>', "$standby_dir/$standby_path.cfp.cfsswap") or BAIL_OUT("could not create the .cfsswap marker leftover"); close($orphan_fh); # Keep the target configuration outside the data directory; pg_rewind # overwrites it with the source's copy (and removes files unknown to # the source). my $tmp_folder = PostgreSQL::Test::Utils::tempdir; my $tmp_conf = "$tmp_folder/postgresql.conf"; copy("$primary_dir/postgresql.conf", $tmp_conf); my $standby_connstr = $standby->connstr('postgres'); command_ok( [ 'pg_rewind', '--target-pgdata' => $primary->data_dir, '--source-server' => $standby_connstr, '--debug', ], 'pg_rewind from running source with CFS tables'); # Restore the target's own configuration (ports etc.) and make it # follow the promoted standby. The connection string may contain # single quotes (e.g. dbname='postgres'), which need doubling inside # the GUC literal. move($tmp_conf, "$primary_dir/postgresql.conf"); (my $ci_quoted = $standby_connstr) =~ s/'/''/g; $primary->append_conf('postgresql.conf', "primary_conninfo = '$ci_quoted'\n"); $primary->set_standby_mode(); # Start the rewound node and verify CFS contents. $primary->start; $standby->wait_for_catchup($primary); # The rewound node must serve exactly the source's rows: the 500 # common rows plus the 200 rows written on the source after # divergence. my $source_checksum = $standby->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_rw"); my $target_checksum = $primary->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_rw"); is($target_checksum, $source_checksum, 'CFS table contents match source after rewind'); my $count = $primary->safe_psql('postgres', "SELECT count(*) FROM cfs_rw"); is($count, '700', 'divergent rows on target were discarded by rewind'); # The source-only CFS table must have been copied and be readable. my $new_checksum_source = $standby->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_rw_new"); my $new_checksum_target = $primary->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_rw_new"); is($new_checksum_target, $new_checksum_source, 'source-only CFS table is readable on the rewound node'); # The target-only CFS table must be gone. my ($ret, $stdout, $stderr) = $primary->psql('postgres', "SELECT count(*) FROM cfs_rw_gone"); isnt($ret, 0, 'target-only CFS table removed by rewind'); # Structural integrity of the copied sidecar files. my $fsck = $primary->safe_psql('postgres', "SELECT ok FROM pg_cfs_check('cfs_rw')"); is($fsck, 't', 'pg_cfs_check passes on rewound CFS table'); $fsck = $primary->safe_psql('postgres', "SELECT ok FROM pg_cfs_check('cfs_rw_new')"); is($fsck, 't', 'pg_cfs_check passes on source-only CFS table'); # The transient compaction leftovers that traveled with the rewind # must have been discarded by the target's startup recovery cleanup. ok(!-f "$primary_dir/$primary_path.cfp.tmp", 'startup cleanup removed the .cfp.tmp leftover on the target'); ok( !-f "$primary_dir/$primary_path.cfp.cfsswap", 'startup cleanup removed the .cfsswap marker leftover on the target'); # The rewound node keeps following the source: new CFS writes on the # source must replay through the CFS write path on the rewound node. $standby->safe_psql('postgres', "INSERT INTO cfs_rw SELECT g, repeat('f' || g, 100) " . "FROM generate_series(701, 800) g"); $standby->wait_for_catchup($primary); my $follow_count = $primary->safe_psql('postgres', "SELECT count(*) FROM cfs_rw"); is($follow_count, '800', 'rewound node replays new CFS writes from the source'); # Compaction quiesce: compaction must be refused while a # non-exclusive backup is in progress, and work again after it ends. my $psql_backup = $standby->background_psql('postgres', on_error_die => 1); $psql_backup->query_safe( "SELECT pg_backup_start('cfs_quiesce_test', true)"); ($ret, $stdout, $stderr) = $standby->psql('postgres', "SELECT pg_cfs_compact('cfs_rw')"); is($ret, 3, 'pg_cfs_compact is refused during a backup'); like( $stderr, qr/cannot compact CFS relation while a base backup is in progress/, 'compaction error message mentions the backup'); $psql_backup->query_safe("SELECT pg_backup_stop(false)"); $psql_backup->quit; ($ret, $stdout, $stderr) = $standby->psql('postgres', "SELECT pg_cfs_compact('cfs_rw')"); is($ret, 0, 'pg_cfs_compact works again after the backup ended'); # Stale compaction leftovers of an aborted attempt are discarded by # the next compaction: the candidate files are recreated (O_TRUNC) and # the swap marker is unlinked at the end of a successful swap. open($orphan_fh, '>', "$standby_dir/$standby_path.cfp.tmp") or BAIL_OUT("could not recreate the .cfp.tmp leftover"); close($orphan_fh); open($orphan_fh, '>', "$standby_dir/$standby_path.cfp.cfsswap") or BAIL_OUT("could not recreate the .cfsswap marker leftover"); close($orphan_fh); ($ret, $stdout, $stderr) = $standby->psql('postgres', "SELECT pg_cfs_compact('cfs_rw')"); is($ret, 0, 'pg_cfs_compact succeeds over stale leftovers'); ok(!-f "$standby_dir/$standby_path.cfp.tmp", 'next compaction removed the stale .cfp.tmp candidate'); ok( !-f "$standby_dir/$standby_path.cfp.cfsswap", 'next compaction removed the stale swap marker'); $fsck = $standby->safe_psql('postgres', "SELECT ok FROM pg_cfs_check('cfs_rw')"); is($fsck, 't', 'pg_cfs_check passes after compaction over leftovers'); $primary->stop('fast'); $standby->stop('fast'); } # ---------------------------------------------------------------------- # Incremental pg_basebackup with CFS-compressed relations. The .cfp # data file is append-only within one lifespan, so an incremental backup # must send only the blocks covering the tail grown since the prior # backup, instead of silently falling back to a full copy; the map and # journal always remain full copies. A compaction swap replaces the # .cfp and stamps a fresh creation epoch into its lead-in, so the next # incremental backup after a compaction must fall back to a full copy. # The chain full -> incr -> incr -> (compact) -> incr is then combined # with pg_combinebackup and restored via PITR. # ---------------------------------------------------------------------- subtest 'incremental pg_basebackup with CFS relations' => sub { my $primary = PostgreSQL::Test::Cluster->new('cfs_incr_primary'); $primary->init(has_archiving => 1, allows_streaming => 1); $primary->append_conf('postgresql.conf', "summarize_wal = on\n"); $primary->start; my $configure = $primary->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS backup tests'; } # CFS table with a first, sizable batch of rows. $primary->safe_psql('postgres', "CREATE TABLE cfs_incr (id int, payload text) WITH (algorithm = 'lz4')" ); $primary->safe_psql('postgres', "INSERT INTO cfs_incr SELECT g, repeat('a' || g, 100) " . "FROM generate_series(1, 3000) g"); $primary->safe_psql('postgres', "CHECKPOINT"); my $dboid = $primary->safe_psql('postgres', "SELECT oid FROM pg_database WHERE datname = 'postgres'"); my $relfile = $primary->safe_psql('postgres', "SELECT relfilenode FROM pg_class WHERE relname = 'cfs_incr'"); my $dir = $primary->backup_dir; # Full backup, then a small second batch and an incremental backup. my $b1 = "$dir/backup1"; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $b1, '--checkpoint' => 'fast', ], 'full backup'); $primary->safe_psql('postgres', "INSERT INTO cfs_incr SELECT g, repeat('b' || g, 100) " . "FROM generate_series(3001, 3200) g"); $primary->safe_psql('postgres', "CHECKPOINT"); my $b2 = "$dir/backup2"; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $b2, '--checkpoint' => 'fast', '--incremental' => "$b1/backup_manifest", ], 'incremental backup 2'); ok( -f "$b2/base/$dboid/INCREMENTAL.$relfile.cfp", '.cfp is sent as an incremental tail diff'); ok(-f "$b2/base/$dboid/$relfile.cfsmap", '.cfsmap stays a full copy'); ok(-f "$b2/base/$dboid/$relfile.cfsjrn", '.cfsjrn stays a full copy'); ok( !-f "$b2/base/$dboid/$relfile.cfp", 'no full .cfp in the incremental backup'); # Third batch: a second incremental backup chained off the first one. $primary->safe_psql('postgres', "INSERT INTO cfs_incr SELECT g, repeat('c' || g, 100) " . "FROM generate_series(3201, 3400) g"); $primary->safe_psql('postgres', "CHECKPOINT"); my $b3 = "$dir/backup3"; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $b3, '--checkpoint' => 'fast', '--incremental' => "$b2/backup_manifest", ], 'incremental backup 3 (chained)'); ok(-f "$b3/base/$dboid/INCREMENTAL.$relfile.cfp", '.cfp tail diff works against a chained incremental backup'); # Quiet interval: no writes to the CFS table between two incremental # backups, only unrelated activity keeps the WAL summaries alive. The # .cfp is unchanged (same epoch, same size), so the incremental stub # must carry the tail block straddling the unaligned end of the file, # and pg_combinebackup must reconstruct the exact byte length from the # chain. A stub with zero blocks and an unaligned exact size would # make the reconstruction fail loudly ("inconsistent exact size"). $primary->safe_psql('postgres', "CREATE TABLE plain_noise (id int)"); $primary->safe_psql('postgres', "INSERT INTO plain_noise SELECT g FROM generate_series(1, 100) g"); my $srcdir = $primary->data_dir; my $src_cfp_size = -s "$srcdir/base/$dboid/$relfile.cfp"; ok( defined($src_cfp_size) && $src_cfp_size >= 9216, 'source .cfp is above the 90% full-copy threshold floor'); my $b3q = "$dir/backup3q"; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $b3q, '--checkpoint' => 'fast', '--incremental' => "$b3/backup_manifest", ], 'incremental backup during a quiet interval'); ok( -f "$b3q/base/$dboid/INCREMENTAL.$relfile.cfp", 'unchanged .cfp still gets an incremental stub with the straddling tail block' ); ok(!-f "$b3q/base/$dboid/$relfile.cfp", 'no full .cfp in the quiet-interval incremental backup'); # The main fork of a CFS relation is a zero-byte marker: the real data # lives in the .cfp sidecar, and the WAL summary carries no main-fork # blocks for the relation, so the marker travels as a full (empty) # copy rather than as an incremental stub; combining must keep it # empty. (An incremental stub would derive its truncation length # from the WAL summary limit and reconstruct the marker as a large # file of zeroes.) ok(-f "$b3q/base/$dboid/$relfile", 'CFS main-fork marker is sent as a full copy'); ok( !-f "$b3q/base/$dboid/INCREMENTAL.$relfile", 'no incremental stub for the CFS main-fork marker'); my $combined_quiet = "$dir/combined_quiet"; $primary->command_ok( [ 'pg_combinebackup', $b1, $b2, $b3, $b3q, '-o' => $combined_quiet, ], 'pg_combinebackup over the chain with a quiet interval'); $primary->command_ok([ 'pg_verifybackup', $combined_quiet ], 'pg_verifybackup accepts the quiet-interval combined backup'); is(-s "$combined_quiet/base/$dboid/$relfile.cfp", $src_cfp_size, 'quiet-interval .cfp is reconstructed to the exact byte length'); is(-s "$combined_quiet/base/$dboid/$relfile", 0, 'CFS main-fork marker stays a zero-byte file after combining'); rmtree($combined_quiet); # Compaction replaces the .cfp (fresh epoch): the next incremental # must fall back to a full copy. $primary->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_incr')"); $primary->safe_psql('postgres', "CHECKPOINT"); my $b4 = "$dir/backup4"; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $b4, '--checkpoint' => 'fast', '--incremental' => "$b3q/backup_manifest", ], 'incremental backup 4 (after compaction)'); ok(-f "$b4/base/$dboid/$relfile.cfp", 'epoch change after compaction forces a full .cfp copy'); ok( !-f "$b4/base/$dboid/INCREMENTAL.$relfile.cfp", 'no stale incremental .cfp after compaction'); # Combine the chain and restore it via PITR. my $lsn = $primary->safe_psql('postgres', "SELECT pg_current_wal_lsn()"); my $expected_checksum = $primary->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_incr"); # Make sure the WAL up to that LSN is archived. $primary->safe_psql('postgres', 'SELECT txid_current()'); $primary->safe_psql('postgres', 'SELECT pg_switch_wal()'); $primary->poll_query_until('postgres', "SELECT pg_walfile_name('$lsn') <= last_archived_wal " . "FROM pg_stat_archiver") or die "Timed out while waiting for WAL segment to be archived"; my $combined = "$dir/combined"; $primary->command_ok( [ 'pg_combinebackup', $b1, $b2, $b3, $b3q, $b4, '-o' => $combined, ], 'pg_combinebackup over the CFS chain'); $primary->command_ok([ 'pg_verifybackup', $b2 ], 'pg_verifybackup accepts CFS manifest fields (incremental)'); $primary->command_ok([ 'pg_verifybackup', $combined ], 'pg_verifybackup accepts the combined backup'); my $restore = PostgreSQL::Test::Cluster->new('cfs_incr_restore'); $restore->init_from_backup( $primary, 'combined', standby => 0, has_restoring => 1); $restore->append_conf( 'postgresql.conf', qq{ recovery_target_lsn = '$lsn' recovery_target_action = 'promote' archive_mode = 'off' }); $restore->start; $restore->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery()") or die "restore node did not promote"; my $count = $restore->safe_psql('postgres', "SELECT count(*) FROM cfs_incr"); is($count, '3400', 'all rows present after combining the CFS chain'); my $checksum = $restore->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_incr"); is($checksum, $expected_checksum, 'CFS contents match after combining the chain'); my $fsck = $restore->safe_psql('postgres', "SELECT ok FROM pg_cfs_check('cfs_incr')"); is($fsck, 't', 'pg_cfs_check passes on the restored node'); $restore->stop('fast'); # A truncated .cfp lead-in makes the creation epoch unreadable: the # incremental backup must warn about it and send the file as a full # copy, since the epoch can no longer prove append-only continuity. $primary->stop('fast'); my $corrupt_cfp = "$srcdir/base/$dboid/$relfile.cfp"; open(my $cfp_fh, '+<', $corrupt_cfp) or BAIL_OUT("could not open $corrupt_cfp"); truncate($cfp_fh, 4) or BAIL_OUT("could not truncate $corrupt_cfp"); close($cfp_fh); $primary->start; my $b5 = "$dir/backup5"; $primary->command_ok( [ 'pg_basebackup', '--no-sync', '--pgdata' => $b5, '--checkpoint' => 'fast', '--incremental' => "$b4/backup_manifest", ], 'incremental backup 5 (unreadable epoch)'); ok(-f "$b5/base/$dboid/$relfile.cfp", 'unreadable epoch forces a full .cfp copy'); ok( !-f "$b5/base/$dboid/INCREMENTAL.$relfile.cfp", 'no incremental stub when the epoch is unreadable'); my $log_contents = slurp_file($primary->logfile); like( $log_contents, qr/could not read the creation epoch of CFS data file/, 'backup warns about the unreadable .cfp epoch'); $primary->stop('fast'); }; # ---------------------------------------------------------------------- # Low-level backup (pg_backup_start/stop + raw recursive file copy) of a # cluster containing CFS relations. A CFS table loaded before the # backup rides through; the canary table (created after the copy, so it # exists only in WAL) is also CFS, so its sidecars are created entirely # by redo. The first recovery attempt deliberately omits backup_label # to demonstrate that recovery then starts at the wrong location. # ---------------------------------------------------------------------- { # Start primary node with archiving. my $node_primary = PostgreSQL::Test::Cluster->new('llb_primary'); $node_primary->init(has_archiving => 1, allows_streaming => 1); $node_primary->start; # A CFS table with real compressed content that will be caught by the # raw file copy below. $node_primary->safe_psql( 'postgres', q[CREATE TABLE cfs_rider (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO cfs_rider SELECT g, md5(g::text) FROM generate_series(1, 300) g; CHECKPOINT;]); # Start backup. my $backup_name = 'backup1'; my $psql = $node_primary->background_psql('postgres'); $psql->query_safe("SET client_min_messages TO WARNING"); $psql->set_query_timer_restart; $psql->query_safe("select pg_backup_start('test label')"); # Copy files. my $backup_dir = $node_primary->backup_dir . '/' . $backup_name; PostgreSQL::Test::RecursiveCopy::copypath($node_primary->data_dir, $backup_dir); # Cleanup some files/paths that should not be in the backup. There # is no attempt to handle all the exclusions done by pg_basebackup # here, in part because these are not required, but also to keep the # test simple. # # Also remove pg_control because it needs to be copied later. unlink("$backup_dir/postmaster.pid") or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid"); unlink("$backup_dir/postmaster.opts") or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts"); unlink("$backup_dir/global/pg_control") or BAIL_OUT("unable to unlink $backup_dir/global/pg_control"); rmtree("$backup_dir/pg_wal") or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal"); mkdir("$backup_dir/pg_wal"); # Create a table that will be used to verify that recovery started at # the correct location, rather than a location recorded in the # control file. It is a CFS table, so its sidecars are created # entirely by WAL redo. $node_primary->safe_psql('postgres', "create table canary (id int) with (algorithm = 'lz4')"); # More CFS writes after the copy: these are covered by WAL only, the # backup's sidecar files predate them. $node_primary->safe_psql( 'postgres', "INSERT INTO cfs_rider SELECT g, md5(g::text) FROM generate_series(301, 400) g;"); # Advance the checkpoint location in pg_control past the location # where the backup started. Switch WAL to make it really clear that # the location is different and to put the checkpoint in a new WAL # segment. my $segment_name = $node_primary->safe_psql('postgres', "select pg_walfile_name(pg_switch_wal())"); # Ensure that the segment just switched from is archived. The # follow-up tests depend on its presence to begin recovery. $node_primary->poll_query_until('postgres', q{SELECT last_archived_wal FROM pg_stat_archiver}, $segment_name) or die "Timed out while waiting for archiving of switched segment to finish"; $node_primary->safe_psql('postgres', "checkpoint"); # Copy pg_control last so it contains the new checkpoint. copy($node_primary->data_dir . '/global/pg_control', "$backup_dir/global/pg_control") or BAIL_OUT("unable to copy global/pg_control"); # Save the name segment that will be archived by pg_backup_stop(). # This is copied to the pg_wal directory of the node whose recovery # is done without a backup_label. my $stop_segment_name = $node_primary->safe_psql('postgres', 'SELECT pg_walfile_name(pg_current_wal_lsn())'); # Stop backup and get backup_label, the last segment is archived. my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()"); $psql->quit; # Rather than writing out backup_label, try to recover the backup # without backup_label to demonstrate that recovery will not work # correctly without it, i.e. the canary table will be missing and the # cluster will be corrupted. Provide only the WAL segment that # recovery will think it needs. # # The point of this test is to explicitly demonstrate that # backup_label is being used in a later test to get the correct # recovery info. my $node_replica = PostgreSQL::Test::Cluster->new('replica_fail'); $node_replica->init_from_backup($node_primary, $backup_name); $node_replica->append_conf('postgresql.conf', "archive_mode = off"); my $canary_query = "select count(*) from pg_class where relname = 'canary'"; copy( $node_primary->archive_dir . "/$stop_segment_name", $node_replica->data_dir . "/pg_wal/$stop_segment_name" ) or BAIL_OUT("unable to copy $stop_segment_name"); $node_replica->start; is($node_replica->safe_psql('postgres', $canary_query), '0', 'canary is missing'); # Check log to ensure that crash recovery was used as there is no # backup_label. ok( $node_replica->log_contains( 'database system was not properly shut down; automatic recovery in progress' ), 'verify backup recovery performed with crash recovery'); $node_replica->teardown_node; $node_replica->clean_node; # Save backup_label into the backup directory and recover using the # primary's archive. This time recovery will succeed and the canary # table will be present. open my $fh, ">>", "$backup_dir/backup_label" or die "could not open backup_label"; # Binary mode is required for Windows, as the backup_label parsing is # not able to cope with CRLFs. binmode $fh; print $fh $backup_label; close $fh; $node_replica = PostgreSQL::Test::Cluster->new('replica_success'); $node_replica->init_from_backup($node_primary, $backup_name, has_restoring => 1); $node_replica->start; is($node_replica->safe_psql('postgres', $canary_query), '1', 'canary is present'); # Check log to ensure that backup_label was used for recovery. ok($node_replica->log_contains('starting backup recovery with redo LSN'), 'verify backup recovery performed with backup_label'); # The canary's sidecars were built by redo; the rider's sidecars came # from the raw copy plus WAL repair. Both must be complete and # sound. is( $node_replica->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('canary'::regclass, true)"), 't', 'canary CFS sidecars intact after backup recovery'); is( $node_replica->safe_psql( 'postgres', "SELECT count(*) FROM cfs_rider"), '400', 'CFS rider rows complete after backup recovery'); is( $node_replica->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('cfs_rider'::regclass, true)"), 't', 'CFS rider sidecars intact after backup recovery'); $node_replica->stop; $node_primary->stop; } done_testing();