# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group # # src/bin/pg_upgrade/t/500_cfs_upgrade.pl # # pg_upgrade coverage for CFS (Compressed File Store) relations, in four # scenarios: # # 1. On-disk format scan: the pre-flight CFS compatibility check must # follow the pg_tblspc/ symlinks, otherwise every relation stored # in a non-default tablespace escapes the scan and pg_upgrade reports # an incompatible cluster as compatible. # 2. Target CFS support: the check must refuse the upgrade when the old # cluster contains CFS sidecar files but the target binary was built # without CFS support, and must not fire when the old cluster has no # CFS relations. # 3. Transfer modes: every transfer mode (--clone/--copy/--copy-file-range/ # --link/--swap) must carry the CFS sidecar files (.cfp/.cfsmap/.cfsjrn) # over with the same guarantees it gives the main fork. # 4. Full upgrade cycle: a same-version upgrade of a cluster carrying CFS # tables and indexes with a variety of policies; dumps taken before and # after the upgrade must match, and rows, resolved CFS policies and # sidecar integrity must survive on the upgraded cluster. use strict; use warnings FATAL => 'all'; use File::Find (); use File::Path qw(rmtree); use File::Temp (); use PostgreSQL::Test::Cluster; use PostgreSQL::Test::Utils; use Test::More; # Plant an orphan .cfsmap with a zeroed header into "$root/$dboid". The # database must not exist, so the server's recovery scan never opens the # file (a broken header of a live relation's map is a startup FATAL), # while the lexical format scan of pg_upgrade still finds it. sub corrupt_map_orphan { my ($root, $dboid, $relfileno) = @_; my $dir = "$root/$dboid"; mkdir($dir) or die "could not create $dir: $!"; my $path = "$dir/$relfileno.cfsmap"; open(my $fh, '>', $path) or die "could not create $path: $!"; binmode($fh); print $fh "\0" x 8; close($fh); return; } # Collect .cfsmap files under a directory. sub find_maps { my ($root) = @_; my @maps; File::Find::find( sub { push @maps, $File::Find::name if /\.cfsmap$/; }, $root); return @maps; } # Run "pg_upgrade --check" of $oldnode into $newnode. Custom bindirs may # be passed to emulate a non-default source or target installation; the # target's own bindir is the default for both. sub run_upgrade_check { my ($oldnode, $newnode, $oldbin, $newbin) = @_; my $bindir = $newnode->config_data('--bindir'); $oldbin ||= $bindir; $newbin ||= $bindir; return [ 'pg_upgrade', '--no-sync', '--old-datadir' => $oldnode->data_dir, '--new-datadir' => $newnode->data_dir, '--old-bindir' => $oldbin, '--new-bindir' => $newbin, '--socketdir' => $newnode->host, '--old-port' => $oldnode->port, '--new-port' => $newnode->port, '--check', ]; } # Build a fake target bindir that behaves like a build without CFS: # symlinks to the real binaries, except "postgres", which is replaced by # a wrapper that rejects the CFS-only GUC probe exactly like a non-CFS # binary would and delegates everything else to the real binary. sub make_nocfs_bindir { my ($realbin, $fakebin) = @_; mkdir($fakebin) or die "could not create $fakebin: $!"; foreach my $prog ( qw(postgres pg_controldata pg_ctl pg_resetwal initdb pg_dump pg_dumpall pg_restore psql vacuumdb)) { if ($prog ne 'postgres') { symlink("$realbin/$prog", "$fakebin/$prog") or die "could not symlink $prog: $!"; next; } # Wrapper: fail the CFS-only GUC probe, delegate the rest. open(my $fh, '>', "$fakebin/postgres") or die "could not write $fakebin/postgres: $!"; print $fh <<"EOS"; #!/bin/sh # Emulate a postgres binary built without CFS support. prev="" for arg in "\$\@"; do if [ "\$prev" = "-C" ] && [ "\$arg" = "cfs_default_lz4_level" ]; then echo 'FATAL: unrecognized configuration parameter "cfs_default_lz4_level"' >&2 exit 1 fi prev="\$arg" done exec "$realbin/postgres" "\$\@" EOS close($fh); chmod(0755, "$fakebin/postgres") or die "could not chmod $fakebin/postgres: $!"; } return; } # Probe CFS availability: the "algorithm" reloption exists only in a CFS # build, and the "lz4" algorithm only when LZ4 was compiled in. Skip the # whole test when either is missing. sub probe_cfs_lz4 { my ($node) = @_; my ($probe_ret, undef, $probe_err) = $node->psql('postgres', "CREATE TABLE cfs_probe (id int) WITH (algorithm = 'lz4')"); if ($probe_ret != 0) { plan skip_all => "CFS with LZ4 not available in this build, skipping: $probe_err"; } $node->safe_psql('postgres', 'DROP TABLE cfs_probe'); return; } # --------------------------------------------------------------------------- # On-disk format scan through pg_tblspc symlinks. # # Same-version pg_upgrade refuses to run with registered tablespaces, so # the test detaches the tablespace from the catalog (DROP TABLESPACE) # while keeping its files, then recreates the pg_tblspc/ symlink by # hand. The directory walker under test sees exactly the same layout as # with a live tablespace: pg_tblspc/ -> real directory with .cfsmap # files. # --------------------------------------------------------------------------- { # Absolute path: a tablespace location must be absolute. my $tmp = File::Temp::tempdir(CLEANUP => 1); # Old cluster: one CFS table in a user tablespace, one in pg_default. my $oldnode = PostgreSQL::Test::Cluster->new('old_cfs'); $oldnode->init; $oldnode->start; probe_cfs_lz4($oldnode); my $tsdir = "$tmp/ts1"; my $tsdir_sql = $tsdir; $tsdir_sql =~ s{\\}{/}g; mkdir($tsdir) or die "could not create $tsdir: $!"; $oldnode->safe_psql('postgres', "CREATE TABLESPACE ts1 LOCATION '$tsdir_sql'"); $oldnode->safe_psql('postgres', "CREATE TABLE t_ts (id int, payload text) WITH (algorithm = 'lz4') TABLESPACE ts1" ); $oldnode->safe_psql('postgres', "INSERT INTO t_ts SELECT g, repeat('x', 200) FROM generate_series(1, 50) g" ); $oldnode->safe_psql('postgres', "CREATE TABLE t_def (id int, payload text) WITH (algorithm = 'lz4')"); $oldnode->safe_psql('postgres', "INSERT INTO t_def SELECT g, repeat('y', 200) FROM generate_series(1, 50) g" ); $oldnode->safe_psql('postgres', 'CHECKPOINT'); my $tsoid = $oldnode->safe_psql('postgres', "SELECT oid FROM pg_tablespace WHERE spcname = 'ts1'"); my @ts_maps = find_maps($tsdir); ok(@ts_maps > 0, 'CFS sidecar files exist in the tablespace'); my @base_maps = find_maps($oldnode->data_dir . '/base'); ok(@base_maps > 0, 'CFS sidecar files exist in pg_default'); # Move the tablespace directory aside (preserving the .cfsmap files) # and detach the tablespace from the catalog; the server cannot # remove the relation files anymore and only logs warnings. my $ts_saved = "$tmp/ts1_saved"; rename($tsdir, $ts_saved) or die "could not move $tsdir aside: $!"; mkdir($tsdir) or die "could not recreate $tsdir: $!"; $oldnode->safe_psql('postgres', 'DROP TABLE t_ts'); $oldnode->safe_psql('postgres', 'DROP TABLESPACE ts1'); $oldnode->stop; # Restore the pg_tblspc/ symlink, pointing at the saved # tablespace tree. From here on the old cluster's layout matches a # cluster with a real tablespace, but no pg_tablespace entry is # left, so a same-version "pg_upgrade --check" proceeds to the CFS # format scan. my $link = $oldnode->data_dir . "/pg_tblspc/$tsoid"; PostgreSQL::Test::Utils::dir_symlink($ts_saved, $link); # Case 1: everything is valid, the scan must pass (no false # positives from following the symlink). my $newnode = PostgreSQL::Test::Cluster->new('new_cfs_valid'); $newnode->init; command_ok(run_upgrade_check($oldnode, $newnode), 'valid cluster behind pg_tblspc symlink passes --check'); # Case 1b: a foreign directory in the tablespace root, outside # TABLESPACE_VERSION_DIRECTORY, holding an unreadable .cfsmap: it # does not belong to this cluster and must not cause a false # refusal. Only the versioned subdirectory of a tablespace # location is part of the cluster, exactly as in every vanilla # directory walker (pg_checksums, basebackup). my $foreign_map = "$ts_saved/not_a_cluster_dir.cfsmap"; open(my $ffh, '>', $foreign_map) or die "could not create $foreign_map"; binmode($ffh); print $ffh "\0" x 8; close($ffh); my $newnode1b = PostgreSQL::Test::Cluster->new('new_cfs_foreign'); $newnode1b->init; command_ok( run_upgrade_check($oldnode, $newnode1b), 'foreign .cfsmap outside the versioned tablespace dir is not scanned' ); unlink($foreign_map); # Case 2: an unreadable .cfsmap inside the tablespace tree; the scan # must follow the pg_tblspc symlink and reject the upgrade. # # The corrupt file is deliberately an orphan: a .cfsmap with zeroed # magic placed in the directory of a database that does not exist. # Corrupting the live map of a real relation is not an option since # the recovery scan makes a broken .cfsmap header a hard startup # FATAL, so pg_upgrade would fail to start the old server at all # and never reach its own format scan. An orphan in a nonexistent # database directory is invisible to the server (it only opens maps # of relations it knows about) but is still found by the lexical # walk of the format scan, which is exactly what this case verifies. my ($ts_verdir) = glob("$ts_saved/PG_*"); ok( defined($ts_verdir) && -d $ts_verdir, 'versioned tablespace directory found'); corrupt_map_orphan($ts_verdir, 99999, 54321); my $newnode2 = PostgreSQL::Test::Cluster->new('new_cfs_ts'); $newnode2->init; command_checks_all( run_upgrade_check($oldnode, $newnode2), 1, [ qr/incompatible on-disk format/, qr{pg_tblspc/$tsoid/}, ], [qr/^$/], 'corrupt .cfsmap in tablespace is detected through pg_tblspc symlink' ); # Case 3: remove the tablespace orphan and plant the same kind of # orphan in pg_default; the scan must keep rejecting it (no # regression for the base/ walk). rmtree("$ts_verdir/99999"); corrupt_map_orphan($oldnode->data_dir . '/base', 99998, 54322); my $newnode3 = PostgreSQL::Test::Cluster->new('new_cfs_base'); $newnode3->init; command_checks_all( run_upgrade_check($oldnode, $newnode3), 1, [ qr/incompatible on-disk format/, qr{/base/\d+/\d+\.cfsmap}, ], [qr/^$/], 'corrupt .cfsmap in pg_default is still detected'); } # --------------------------------------------------------------------------- # Target CFS support. # # The check must stop pg_upgrade before any file is copied or linked when # the target binary lacks CFS support. Such a target is emulated by a # bindir of symlinks to the real binaries, where "postgres" is replaced # by a wrapper rejecting the CFS-only GUC probe. The wrapper relies on # symlinks and /bin/sh, so this scenario does not run on Windows. # --------------------------------------------------------------------------- if (!$PostgreSQL::Test::Utils::windows_os) { my $tmp = File::Temp::tempdir(CLEANUP => 1); my $realbin; # Old cluster with a CFS table. my $oldnode = PostgreSQL::Test::Cluster->new('old_cfs_target'); $oldnode->init; $oldnode->start; probe_cfs_lz4($oldnode); $realbin = $oldnode->config_data('--bindir'); $oldnode->safe_psql('postgres', "CREATE TABLE t_cfs (id int, payload text) WITH (algorithm = 'lz4')"); $oldnode->safe_psql('postgres', "INSERT INTO t_cfs SELECT g, repeat('x', 200) FROM generate_series(1, 50) g" ); $oldnode->safe_psql('postgres', 'CHECKPOINT'); $oldnode->stop; my $fakebin = "$tmp/fakebin"; make_nocfs_bindir($realbin, $fakebin); # Case 1: target without CFS support must be rejected by --check, # before any file transfer. my $newnode = PostgreSQL::Test::Cluster->new('new_nocfs'); $newnode->init; command_checks_all( run_upgrade_check($oldnode, $newnode, $realbin, $fakebin), 1, [qr/the target server does not support CFS/], [qr/^$/], 'CFS cluster is rejected when the target server lacks CFS support'); # The refusal must happen before the file transfer: no CFS sidecar # file may appear in the target data directory. my @leaked = glob($newnode->data_dir . '/base/*/*.cf*'); is(scalar(@leaked), 0, 'no CFS sidecar files were transferred'); # Case 2: an old cluster without CFS relations must still pass # --check against the same target: the probe must not fire without # .cfsmap files. my $plainnode = PostgreSQL::Test::Cluster->new('old_plain'); $plainnode->init; $plainnode->start; $plainnode->safe_psql('postgres', 'CREATE TABLE t_plain (id int); INSERT INTO t_plain VALUES (1)'); $plainnode->stop; my $newnode2 = PostgreSQL::Test::Cluster->new('new_plain'); $newnode2->init; command_ok( run_upgrade_check($plainnode, $newnode2, $realbin, $fakebin), 'non-CFS cluster passes --check against a non-CFS target'); } # --------------------------------------------------------------------------- # File transfer modes. # # After each upgrade the test verifies the rows, the CFS policy and the # structural integrity of the sidecars. # --------------------------------------------------------------------------- sub test_mode { my ($mode) = @_; my $old = PostgreSQL::Test::Cluster->new('old', install_path => $ENV{oldinstall}); my $new = PostgreSQL::Test::Cluster->new('new'); # --swap can't be used to upgrade from versions older than 10, so just skip # the test if the old cluster version is too old. if ($old->pg_version < 10 && $mode eq "--swap") { $old->clean_node(); $new->clean_node(); return; } if (defined($ENV{oldinstall})) { # Checksums are now enabled by default, but weren't before 18, so pass # '-k' to initdb on older versions so that upgrades work. $old->init(extra => ['-k']); } else { $old->init(); } $new->init(); # CFS tables with different policies, plus a CFS index with its own # policy on a plain table. $old->start; probe_cfs_lz4($old); $old->safe_psql( 'postgres', q[CREATE TABLE cfs_lz4 (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO cfs_lz4 SELECT g, md5(g::text) FROM generate_series(1, 300) g; CREATE TABLE cfs_zstd (id int, payload text) WITH (algorithm = 'zstd', level = 5); INSERT INTO cfs_zstd SELECT g, md5(g::text) FROM generate_series(1, 300) g; CREATE TABLE plain_t (id int); INSERT INTO plain_t SELECT generate_series(1, 100); CREATE INDEX plain_t_cfs_idx ON plain_t (id) WITH (algorithm = 'lz4'); CHECKPOINT;]); $old->stop; my $result = command_ok_or_fails_like( [ 'pg_upgrade', '--no-sync', '--old-datadir' => $old->data_dir, '--new-datadir' => $new->data_dir, '--old-bindir' => $old->config_data('--bindir'), '--new-bindir' => $new->config_data('--bindir'), '--socketdir' => $new->host, '--old-port' => $old->port, '--new-port' => $new->port, $mode ], qr/.* not supported on this platform|could not .* between old and new data directories: .*/, qr/^$/, "pg_upgrade with transfer mode $mode"); # If pg_upgrade was successful, check that all of our test objects reached # the new version. if ($result) { $new->start; is($new->safe_psql('postgres', "SELECT count(*) FROM cfs_lz4"), '300', "cfs_lz4 rows after pg_upgrade $mode"); is( $new->safe_psql( 'postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_lz4" ), $new->safe_psql( 'postgres', "SELECT md5(string_agg(md5(g::text), '' ORDER BY g)) FROM generate_series(1, 300) g"), "cfs_lz4 contents after pg_upgrade $mode"); is( $new->safe_psql( 'postgres', "SELECT algorithm || '/' || level FROM pg_cfs_relation_info('cfs_zstd'::regclass)" ), 'zstd/5', "cfs_zstd policy after pg_upgrade $mode"); is($new->safe_psql('postgres', "SELECT count(*) FROM plain_t"), '100', "plain_t rows after pg_upgrade $mode"); is( $new->safe_psql( 'postgres', "SELECT is_cfs FROM pg_cfs_relation_info('plain_t_cfs_idx'::regclass)" ), 't', "index policy after pg_upgrade $mode"); for my $rel ('cfs_lz4', 'cfs_zstd', 'plain_t_cfs_idx') { is( $new->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('$rel'::regclass, true)"), 't', "$rel sidecars after pg_upgrade $mode"); } $new->stop; } $old->clean_node(); $new->clean_node(); } { # Run pg_upgrade in tmp_check to avoid leaving files like # delete_old_cluster.{sh,bat} in the source directory for VPATH and meson # builds. chdir ${PostgreSQL::Test::Utils::tmp_check}; test_mode('--clone'); test_mode('--copy'); test_mode('--copy-file-range'); test_mode('--link'); test_mode('--swap'); } # --------------------------------------------------------------------------- # Full upgrade cycle. # # Like the core harness, a plain pg_dump is taken before and after the # upgrade and the two dumps must be identical; on top of that the test # verifies the rows, the resolved CFS policies and the structural # integrity of the sidecar files on the upgraded cluster. # --------------------------------------------------------------------------- { my $tempdir = PostgreSQL::Test::Utils::tempdir; # Can be changed to test the other modes. my $mode = $ENV{PG_TEST_PG_UPGRADE_MODE} || '--copy'; # Cross-version runs use "oldinstall" to point at the installation path # of the old cluster; unlike the core harness, this test builds its own # fixtures, so "olddump" is not needed. my $dump1_file = "$tempdir/dump1.sql"; my $dump2_file = "$tempdir/dump2.sql"; note "testing using transfer mode $mode"; # Initialize node to upgrade my $oldnode = PostgreSQL::Test::Cluster->new('old_node', install_path => $ENV{oldinstall}); if (defined($ENV{oldinstall})) { # Checksums are now enabled by default, but weren't before 18, so pass # '-k' to initdb on older versions so that upgrades work. $oldnode->init(extra => ['-k']); } else { $oldnode->init(); } $oldnode->start; probe_cfs_lz4($oldnode); # The CFS payload: a spread of policies on tables and indexes. $oldnode->safe_psql( 'postgres', q[CREATE TABLE cfs_defaults (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO cfs_defaults SELECT g, md5(g::text) FROM generate_series(1, 300) g; CREATE TABLE cfs_zstd (id int, payload text) WITH (algorithm = 'zstd', level = 5, min_gain_bytes = 128); INSERT INTO cfs_zstd SELECT g, md5(g::text) FROM generate_series(1, 500) g; CREATE TABLE plain_t (id int, payload text); INSERT INTO plain_t SELECT g, md5(g::text) FROM generate_series(1, 200) g; -- Index with its own CFS policy on a plain table. CREATE INDEX plain_t_cfs_idx ON plain_t (id) WITH (algorithm = 'lz4'); -- CFS table with a toasted column. CREATE TABLE cfs_toast (id int, big text) WITH (algorithm = 'zstd'); INSERT INTO cfs_toast SELECT g, (SELECT string_agg(md5((g * 1000 + i)::text), '') FROM generate_series(1, 150) i) FROM generate_series(1, 10) g; CHECKPOINT;]); # Logical dump of the old cluster before the upgrade. $oldnode->run_log( [ 'pg_dump', '--no-sync', '--restrict-key=test', '-d' => $oldnode->connstr('postgres'), '-f' => $dump1_file ]); $oldnode->stop; # Upgrade my $newnode = PostgreSQL::Test::Cluster->new('new_node'); $newnode->init; command_ok( [ 'pg_upgrade', '--no-sync', '--old-datadir' => $oldnode->data_dir, '--new-datadir' => $newnode->data_dir, '--old-bindir' => $oldnode->config_data('--bindir'), '--new-bindir' => $newnode->config_data('--bindir'), '--socketdir' => $newnode->host, '--old-port' => $oldnode->port, '--new-port' => $newnode->port, $mode ], "pg_upgrade run with transfer mode $mode"); $newnode->start; # Logical dump of the new cluster after the upgrade. $newnode->run_log( [ 'pg_dump', '--no-sync', '--restrict-key=test', '-d' => $newnode->connstr('postgres'), '-f' => $dump2_file ]); # The two dumps must be identical (same-version upgrade). is(slurp_file($dump1_file), slurp_file($dump2_file), 'dumps of old and new cluster match'); # Rows survived, readable from the upgraded sidecars. is( $newnode->safe_psql('postgres', "SELECT count(*) FROM cfs_defaults"), '300', 'cfs_defaults rows after upgrade'); is($newnode->safe_psql('postgres', "SELECT count(*) FROM cfs_zstd"), '500', 'cfs_zstd rows after upgrade'); is( $newnode->safe_psql( 'postgres', "SELECT md5(string_agg(big, '' ORDER BY id)) FROM cfs_toast"), $newnode->safe_psql( 'postgres', "SELECT md5(string_agg((SELECT string_agg(md5((g * 1000 + i)::text), '') FROM generate_series(1, 150) i), '' ORDER BY g)) FROM generate_series(1, 10) g"), 'cfs_toast contents after upgrade'); # Policies survived with their exact parameters. is( $newnode->safe_psql( 'postgres', "SELECT algorithm || '/' || level || '/' || min_gain_bytes FROM pg_cfs_relation_info('cfs_zstd'::regclass)"), 'zstd/5/128', 'cfs_zstd policy after upgrade'); is( $newnode->safe_psql( 'postgres', "SELECT is_cfs FROM pg_cfs_relation_info('plain_t'::regclass)"), 'f', 'plain_t stayed plain after upgrade'); is( $newnode->safe_psql( 'postgres', "SELECT is_cfs FROM pg_cfs_relation_info('plain_t_cfs_idx'::regclass)" ), 't', 'index policy after upgrade'); # Structural integrity of every CFS relation's sidecars. for my $rel ('cfs_defaults', 'cfs_zstd', 'plain_t_cfs_idx', 'cfs_toast') { is( $newnode->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('$rel'::regclass, true)"), 't', "$rel sidecars intact after upgrade"); } $newnode->stop; } done_testing();