# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
|
#
|
# src/test/recovery/t/505_cfs_replication.pl
|
#
|
# CFS tables under physical replication.
|
#
|
# CFS relations store their data in sidecar files (.cfp/.cfsmap/.cfsjrn)
|
# next to the (empty) main fork, so every replication mechanism has to
|
# carry both the base files and the sidecars, and WAL redo on a standby
|
# has to write pages through the CFS path. This test checks the whole
|
# matrix:
|
#
|
# * pg_basebackup copies the sidecar files, a standby built from the
|
# backup reads CFS tables, and WAL replay keeps it in sync — including
|
# CFS tables created while the standby is already streaming;
|
# * a standby without the named compression codec degrades new writes
|
# to RAW with a warning instead of dying during redo;
|
# * a promoted standby keeps its CFS data readable and writable on the
|
# new timeline;
|
# * cascading replication (primary -> standby -> standby) carries CFS
|
# data to the bottom of the cascade, also across a promote of the
|
# intermediate node;
|
# * a replica built WITHOUT CFS refuses a CFS primary in a managed way
|
# (connect-time rejection when streaming, a clear FATAL during archive
|
# redo) instead of crashing with a PANIC;
|
# * hot standby recovery conflicts (buffer pin, snapshot) cancel
|
# standby queries on CFS pages correctly and leave the sidecars
|
# structurally valid;
|
# * a physical replication slot maintains correct WAL retention across
|
# checkpoints that flush CFS sidecars.
|
|
use strict;
|
use warnings FATAL => 'all';
|
|
use PostgreSQL::Test::Utils;
|
use PostgreSQL::Test::Cluster;
|
use Test::More;
|
|
# ---------------------------------------------------------------------------
|
# Base backup and physical streaming replication.
|
#
|
# Verifies that:
|
# * pg_basebackup (via the test framework's backup()) copies CFS sidecar
|
# files (.cfp/.cfsmap/.cfsjrn);
|
# * a standby initialised from the backup can read CFS tables;
|
# * WAL replay on the standby writes dirty pages through CFS;
|
# * query results on primary and standby match for CFS tables;
|
# * a standby built without the codec named by a replayed CFS policy
|
# degrades new writes to RAW (with a warning) instead of dying with
|
# ERROR during WAL redo.
|
# ---------------------------------------------------------------------------
|
{
|
# Initialize the primary node.
|
my $primary = PostgreSQL::Test::Cluster->new('cfs_primary');
|
$primary->init(allows_streaming => 1);
|
$primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
|
$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 replication test';
|
}
|
|
# Create a CFS table on the primary and populate it.
|
$primary->safe_psql('postgres',
|
"CREATE TABLE cfs_repl (id int, payload text) WITH (algorithm = 'lz4')"
|
);
|
$primary->safe_psql('postgres',
|
"INSERT INTO cfs_repl SELECT g, repeat('r' || g, 100) "
|
. "FROM generate_series(1, 500) g");
|
|
$primary->safe_psql('postgres', "CHECKPOINT");
|
|
# Verify sidecar files exist on the primary.
|
my $primary_path = $primary->safe_psql('postgres',
|
"SELECT pg_relation_filepath('cfs_repl')");
|
my $primary_dir = $primary->data_dir;
|
ok( -f "$primary_dir/$primary_path.cfp",
|
'CFS table has .cfp sidecar on primary');
|
ok( -f "$primary_dir/$primary_path.cfsmap",
|
'CFS table has .cfsmap sidecar on primary');
|
|
# Capture the primary checksum for comparison.
|
my $primary_checksum = $primary->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
|
|
# Take a base backup and create a standby.
|
$primary->backup('my_backup');
|
my $standby = PostgreSQL::Test::Cluster->new('cfs_standby');
|
$standby->init_from_backup($primary, 'my_backup', has_streaming => 1);
|
$standby->start;
|
|
# Verify sidecar files were included in the base backup on standby.
|
$primary->wait_for_catchup($standby);
|
|
my $standby_path = $standby->safe_psql('postgres',
|
"SELECT pg_relation_filepath('cfs_repl')");
|
my $standby_dir = $standby->data_dir;
|
ok(-f "$standby_dir/$standby_path.cfp",
|
'CFS .cfp sidecar present on standby via basebackup');
|
ok(-f "$standby_dir/$standby_path.cfsmap",
|
'CFS .cfsmap sidecar present on standby via basebackup');
|
|
# The standby should be able to read the CFS table.
|
my $standby_checksum = $standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
|
is($standby_checksum, $primary_checksum,
|
'CFS table checksum matches between primary and standby');
|
|
# Write more data on the primary; standby must catch up via WAL
|
# replay.
|
$primary->safe_psql('postgres',
|
"INSERT INTO cfs_repl SELECT g, repeat('n' || g, 100) "
|
. "FROM generate_series(501, 1000) g");
|
|
$primary->wait_for_catchup($standby);
|
|
my $standby_count =
|
$standby->safe_psql('postgres', "SELECT count(*) FROM cfs_repl");
|
is($standby_count, '1000',
|
'Standby has 1000 rows after WAL replay (CFS write path)');
|
|
# Checksum comparison after WAL replay.
|
my $primary_checksum2 = $primary->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
|
my $standby_checksum2 = $standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
|
is($standby_checksum2, $primary_checksum2,
|
'CFS table checksum matches after WAL replay');
|
|
# Redo-only CREATE: a CFS table created while the standby is already
|
# streaming must keep its CFS status through WAL replay.
|
#
|
# On the standby the startup process has no relcache entry for the new
|
# relation when XLOG_SMGR_CREATE replays, so the CFS policy must arrive
|
# via WAL itself. A regression here makes replay take the plain md
|
# path: the pages land raw in the base file, the sidecars are never
|
# created, and the first hot-standby read (which resolves CFS from
|
# reloptions) sees an empty relation.
|
$primary->safe_psql('postgres',
|
"CREATE TABLE cfs_repl_new (id int, payload text) WITH (algorithm = 'lz4')"
|
);
|
$primary->safe_psql('postgres', "CHECKPOINT");
|
|
$primary->wait_for_catchup($standby);
|
|
# Restart the standby between the CREATE and the first INSERT: the
|
# shared-memory policy published by the CFS policy record's replay is
|
# lost, so after the restart redo must recognise the relation as CFS
|
# from the eagerly created sidecar files alone.
|
$standby->restart;
|
|
$primary->safe_psql('postgres',
|
"INSERT INTO cfs_repl_new SELECT g, repeat('w' || g, 100) "
|
. "FROM generate_series(1, 300) g");
|
|
$primary->wait_for_catchup($standby);
|
|
my $standby_new_path = $standby->safe_psql('postgres',
|
"SELECT pg_relation_filepath('cfs_repl_new')");
|
ok(-f "$standby_dir/$standby_new_path.cfp",
|
'redo-only CREATE: .cfp sidecar created on standby during replay');
|
ok( -f "$standby_dir/$standby_new_path.cfsmap",
|
'redo-only CREATE: .cfsmap sidecar created on standby during replay');
|
|
my $standby_new_count =
|
$standby->safe_psql('postgres', "SELECT count(*) FROM cfs_repl_new");
|
is($standby_new_count, '300',
|
'redo-only CREATE: standby reads 300 rows via the CFS path');
|
|
my $primary_new_checksum = $primary->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_new");
|
my $standby_new_checksum = $standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_new");
|
is($standby_new_checksum, $primary_new_checksum,
|
'redo-only CREATE: checksum matches between primary and standby');
|
|
# Codec mismatch: a standby built without the codec named by a
|
# replayed CFS policy must degrade new writes to RAW (with a warning)
|
# instead of dying with ERROR during WAL redo.
|
#
|
# The codec-less build is simulated with the debug GUC
|
# cfs_debug_disable_codecs (bits 1 << CFS_ALGORITHM_LZ4 and
|
# 1 << CFS_ALGORITHM_ZSTD), which makes both real codecs report
|
# themselves as not compiled in. A tiny shared_buffers forces redo to
|
# evict (and therefore compress) dirty pages while replaying —
|
# exactly the path that used to raise the fatal ERROR.
|
#
|
# The table is created only now, while the standby is already
|
# streaming, so the standby learns the policy solely from the
|
# XLOG_SMGR_CFS_POLICY record and builds the sidecar files from
|
# scratch: every block in them is then written by the codec-less
|
# standby itself. With both codecs disabled any compressed block
|
# would be unreadable, so the successful reads below prove that every
|
# flushed page — including the ones evicted by auxiliary processes at
|
# the restartpoint — really went through the RAW fallback.
|
my $log_offset = -s $standby->logfile;
|
$standby->append_conf('postgresql.conf',
|
"cfs_debug_disable_codecs = 6\nshared_buffers = 1MB");
|
$standby->restart;
|
|
$primary->safe_psql('postgres',
|
"CREATE TABLE cfs_repl_nocodec (id int, payload text) WITH (algorithm = 'lz4')"
|
);
|
$primary->safe_psql('postgres',
|
"INSERT INTO cfs_repl_nocodec SELECT g, repeat('m' || (g % 100), 200) "
|
. "FROM generate_series(1, 30000) g");
|
|
# Redo must survive: replay catches up even though the standby cannot
|
# compress with LZ4.
|
$primary->wait_for_catchup($standby);
|
|
my $standby_nc_count = $standby->safe_psql('postgres',
|
"SELECT count(*) FROM cfs_repl_nocodec");
|
is($standby_nc_count, '30000',
|
'codec-less standby replays CFS table (RAW fallback during redo)');
|
|
# A standby restart forces a shutdown restartpoint that flushes the
|
# remaining dirty pages through the CFS write path, and the following
|
# recovery must read back the RAW blocks written by the codec-less
|
# redo.
|
$standby->restart;
|
|
my $primary_nc_checksum = $primary->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_nocodec"
|
);
|
my $standby_nc_checksum = $standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_nocodec"
|
);
|
is($standby_nc_checksum, $primary_nc_checksum,
|
'codec-less standby: checksum matches after restart');
|
|
ok( $standby->log_contains(
|
qr/CFS compression algorithm "lz4" is not available in this build/,
|
$log_offset),
|
'codec-less standby logged the RAW fallback warning');
|
|
$standby->stop('fast');
|
$primary->stop('fast');
|
}
|
|
# ---------------------------------------------------------------------------
|
# Promote of a standby holding CFS-compressed relations.
|
#
|
# Verifies that after pg_ctl promote:
|
# * CFS tables are readable on the new primary;
|
# * new writes go through the CFS write path (sidecar files grow);
|
# * a restart on the new timeline preserves the data (crash recovery of
|
# the sidecar files on a promoted node);
|
# * structural fsck of the sidecar files passes.
|
# ---------------------------------------------------------------------------
|
subtest 'promote of a standby with CFS relations' => sub {
|
my $primary = PostgreSQL::Test::Cluster->new('cfs_promo_primary');
|
$primary->init(allows_streaming => 1);
|
$primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s\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 promote test';
|
}
|
|
# Populate a CFS table on the primary.
|
$primary->safe_psql('postgres',
|
"CREATE TABLE cfs_promo (id int, payload text) WITH (algorithm = 'lz4')"
|
);
|
$primary->safe_psql('postgres',
|
"INSERT INTO cfs_promo SELECT g, repeat('a' || g, 100) "
|
. "FROM generate_series(1, 500) g");
|
$primary->safe_psql('postgres', "CHECKPOINT");
|
|
my $before_checksum = $primary->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
|
|
# Create and promote a standby.
|
$primary->backup('my_backup');
|
my $standby = PostgreSQL::Test::Cluster->new('cfs_promo_standby');
|
$standby->init_from_backup($primary, 'my_backup', has_streaming => 1);
|
$standby->start;
|
|
$primary->wait_for_catchup($standby);
|
$primary->stop('fast');
|
$standby->promote;
|
$standby->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery()")
|
or die "standby did not promote";
|
|
# CFS table must be readable on the promoted node.
|
my $promoted_checksum = $standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
|
is($promoted_checksum, $before_checksum,
|
'CFS table readable after promote');
|
|
# New writes must use the CFS write path on the new primary.
|
my $standby_dir = $standby->data_dir;
|
my $rel_path = $standby->safe_psql('postgres',
|
"SELECT pg_relation_filepath('cfs_promo')");
|
$standby->safe_psql('postgres',
|
"INSERT INTO cfs_promo SELECT g, repeat('b' || g, 100) "
|
. "FROM generate_series(501, 900) g");
|
$standby->safe_psql('postgres', "CHECKPOINT");
|
|
my $count =
|
$standby->safe_psql('postgres', "SELECT count(*) FROM cfs_promo");
|
is($count, '900', 'writes on promoted node go through CFS');
|
|
my $cfp_size = -s "$standby_dir/$rel_path.cfp";
|
ok($cfp_size > 0, '.cfp sidecar keeps growing on promoted node');
|
|
# Restart on the new timeline: crash/recovery of the sidecar files
|
# must preserve the data.
|
$standby->restart;
|
my $restart_checksum = $standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
|
my $expected = $standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
|
is($restart_checksum, $expected,
|
'CFS table survives restart on the new timeline');
|
|
my $fsck = $standby->safe_psql('postgres',
|
"SELECT ok FROM pg_cfs_check('cfs_promo')");
|
is($fsck, 't', 'pg_cfs_check passes after promote and restart');
|
|
$standby->stop('fast');
|
};
|
|
# ---------------------------------------------------------------------------
|
# Cascading physical replication with CFS-compressed relations:
|
# primary -> standby1 -> standby2.
|
#
|
# Verifies that CFS data flows down the cascade, that standby2 serves CFS
|
# reads, and that standby2 keeps replaying CFS writes after standby1 is
|
# promoted (cascading from a promoted intermediate node).
|
# ---------------------------------------------------------------------------
|
subtest 'cascading physical replication with CFS relations' => sub {
|
my $primary = PostgreSQL::Test::Cluster->new('cfs_casc_primary');
|
$primary->init(allows_streaming => 1);
|
$primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s\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 cascade test';
|
}
|
|
$primary->safe_psql('postgres',
|
"CREATE TABLE cfs_casc (id int, payload text) WITH (algorithm = 'lz4')"
|
);
|
$primary->safe_psql('postgres',
|
"INSERT INTO cfs_casc SELECT g, repeat('a' || g, 100) "
|
. "FROM generate_series(1, 300) g");
|
$primary->safe_psql('postgres', "CHECKPOINT");
|
|
# First level of the cascade.
|
$primary->backup('my_backup');
|
my $standby1 = PostgreSQL::Test::Cluster->new('cfs_casc_standby1');
|
$standby1->init_from_backup($primary, 'my_backup', has_streaming => 1);
|
$standby1->start;
|
$primary->wait_for_catchup($standby1);
|
|
# Second level: standby2 follows standby1.
|
$standby1->backup('casc_backup');
|
my $standby2 = PostgreSQL::Test::Cluster->new('cfs_casc_standby2');
|
$standby2->init_from_backup($standby1, 'casc_backup', has_streaming => 1);
|
$standby2->start;
|
|
# CFS data must reach the bottom of the cascade.
|
$primary->safe_psql('postgres',
|
"INSERT INTO cfs_casc SELECT g, repeat('b' || g, 100) "
|
. "FROM generate_series(301, 600) g");
|
$primary->wait_for_catchup($standby1);
|
$standby1->wait_for_catchup($standby2);
|
|
my $checksum = $primary->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
|
my $checksum2 = $standby2->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
|
is($checksum2, $checksum,
|
'CFS checksum matches at the bottom of the cascade');
|
|
my $standby2_dir = $standby2->data_dir;
|
my $rel_path = $standby2->safe_psql('postgres',
|
"SELECT pg_relation_filepath('cfs_casc')");
|
ok(-f "$standby2_dir/$rel_path.cfp",
|
'CFS sidecar present at the bottom of the cascade');
|
|
# Promote the intermediate node; standby2 must keep replaying CFS
|
# writes through the new timeline.
|
$standby1->promote;
|
$standby1->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery()")
|
or die "standby1 did not promote";
|
|
$standby1->safe_psql('postgres',
|
"INSERT INTO cfs_casc SELECT g, repeat('c' || g, 100) "
|
. "FROM generate_series(601, 900) g");
|
$standby1->wait_for_catchup($standby2);
|
|
my $count2 =
|
$standby2->safe_psql('postgres', "SELECT count(*) FROM cfs_casc");
|
is($count2, '900',
|
'cascaded standby replays CFS writes after intermediate promote');
|
|
my $checksum1 = $standby1->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
|
$checksum2 = $standby2->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
|
is($checksum2, $checksum1,
|
'CFS checksum matches after intermediate promote');
|
|
my $fsck = $standby2->safe_psql('postgres',
|
"SELECT ok FROM pg_cfs_check('cfs_casc')");
|
is($fsck, 't', 'pg_cfs_check passes at the bottom of the cascade');
|
|
$standby2->stop('fast');
|
$standby1->stop('fast');
|
$primary->stop('fast');
|
};
|
|
# ---------------------------------------------------------------------------
|
# Cross-build mismatch: non-CFS replica against a CFS primary.
|
#
|
# A physical replica built WITHOUT CFS (--without-dia-cfs) must not crash
|
# with PANIC when its CFS-enabled primary emits an XLOG_SMGR_CFS_POLICY
|
# record. Instead it must stop in a managed, informative way:
|
#
|
# * streaming: reject the CFS primary at connect time (ERROR in
|
# libpqrcv_connect, via the "dia_cfs" GUC_REPORT parameter), exactly
|
# like a system-identifier mismatch, before any WAL replay;
|
# * archive/PITR recovery: fail redo with FATAL "cannot replay CFS WAL
|
# record" instead of "PANIC: smgr_redo: unknown op code".
|
#
|
# Two builds are required: the build under test (a CFS build) as primary,
|
# plus a pre-built --without-dia-cfs installation pointed to by the
|
# CFS_NON_CFS_INSTALL environment variable. The single-build TAP harness
|
# cannot produce a non-CFS binary in one run, so the test skips cleanly
|
# when that variable is unset.
|
# ---------------------------------------------------------------------------
|
subtest 'non-CFS replica against a CFS primary' => sub {
|
my $noncfs_install = $ENV{CFS_NON_CFS_INSTALL};
|
unless (defined $noncfs_install
|
&& -d "$noncfs_install/bin"
|
&& -x "$noncfs_install/bin/postgres")
|
{
|
plan skip_all =>
|
'CFS_NON_CFS_INSTALL does not point at a non-CFS install; '
|
. 'skipping cross-build CFS mismatch test '
|
. '(the single-build TAP harness cannot build a non-CFS binary)';
|
}
|
|
# Poll a node's logfile until $pattern appears or we time out. The
|
# node may be a standby that never accepts queries (it FATALs during
|
# recovery), so we cannot use poll_query_until here.
|
sub wait_log_like
|
{
|
my ($node, $pattern, $offset, $timeout) = @_;
|
|
$timeout //= $PostgreSQL::Test::Utils::timeout_default;
|
for (my $i = 0; $i < $timeout; $i++)
|
{
|
return 1 if $node->log_contains($pattern, $offset);
|
sleep 1;
|
}
|
return 0;
|
}
|
|
# Primary uses the build under test (expected to be a CFS build).
|
my $primary = PostgreSQL::Test::Cluster->new('mm_primary');
|
$primary->init(has_archiving => 1, allows_streaming => 1);
|
$primary->start;
|
|
my $configure = $primary->safe_psql('postgres',
|
"SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
|
if ($configure =~ /--without-dia-cfs/)
|
{
|
plan skip_all =>
|
'build under test is itself non-CFS; it cannot act as a CFS primary';
|
}
|
|
# Sanity-check the second install really is a non-CFS build.
|
my $noncfs_cfg = `$noncfs_install/bin/pg_config --configure`;
|
if ($noncfs_cfg !~ /--without-dia-cfs/)
|
{
|
plan skip_all =>
|
"CFS_NON_CFS_INSTALL is not a non-CFS build (configure: $noncfs_cfg)";
|
}
|
|
note("primary configure: $configure");
|
note("non-CFS install: $noncfs_install (configure: $noncfs_cfg)");
|
|
# Detect an available codec for the primary, used only by the
|
# redo-path phase (a real XLOG_SMGR_CFS_POLICY record is needed
|
# there).
|
my $algo;
|
$algo = 'lz4' if $configure =~ /--with-lz4/;
|
$algo //= 'zstd' if $configure =~ /--with-zstd/;
|
|
# A clean base backup taken before any CFS relation exists serves both
|
# phases: it carries neither the policy record nor CFS sidecar files.
|
$primary->backup('clean_backup');
|
|
# Part A: connect-time rejection (streaming).
|
#
|
# No CFS table is required: the primary reports dia_cfs=on merely by
|
# being a CFS build (the GUC_REPORT parameter is sent during connection
|
# startup), so a non-CFS standby must be rejected in libpqrcv_connect
|
# before a single WAL record is streamed or replayed.
|
{
|
my $stb = PostgreSQL::Test::Cluster->new('mm_stream_standby',
|
install_path => $noncfs_install);
|
$stb->init_from_backup(
|
$primary, 'clean_backup',
|
has_streaming => 1,
|
has_restoring => 0);
|
|
# The standby itself stays up (recovery reaches consistency); it
|
# is the walreceiver that keeps failing to connect.
|
ok($stb->start,
|
'non-CFS streaming standby starts (connect check is async)');
|
|
ok( wait_log_like(
|
$stb, qr/CFS support differs between primary and standby/),
|
'non-CFS standby reports CFS build mismatch at connect time');
|
ok(!$stb->log_contains(qr/unknown op code/),
|
'no "unknown op code" PANIC on the streaming standby');
|
|
$stb->stop('immediate');
|
}
|
|
# Part B: redo-time FATAL (archive recovery).
|
#
|
# A real XLOG_SMGR_CFS_POLICY record must be replayed, so the primary
|
# needs a compression codec. The non-CFS node recovers purely from the
|
# WAL archive (no streaming connection, hence no connect-time check)
|
# and must hit the policy record during redo.
|
SKIP:
|
{
|
skip "no CFS compression codec on the primary", 2
|
unless defined $algo;
|
|
$primary->safe_psql('postgres',
|
"CREATE TABLE mm_cfs(id int, p text) WITH (algorithm = '$algo')");
|
|
# Force the segment carrying the policy record into the WAL
|
# archive.
|
my $walfile = $primary->safe_psql('postgres',
|
"SELECT pg_walfile_name(pg_current_wal_lsn())");
|
$primary->safe_psql('postgres', "SELECT pg_switch_wal()");
|
$primary->poll_query_until('postgres',
|
"SELECT '$walfile' <= last_archived_wal FROM pg_stat_archiver")
|
or die "timed out waiting for the CFS policy WAL to be archived";
|
|
my $node = PostgreSQL::Test::Cluster->new('mm_pitr_node',
|
install_path => $noncfs_install);
|
$node->init_from_backup(
|
$primary, 'clean_backup',
|
standby => 0,
|
has_restoring => 1);
|
|
# The node is expected to FATAL during initial redo, so a
|
# "successful" start is neither required nor expected.
|
$node->start(fail_ok => 1);
|
|
ok( wait_log_like($node, qr/cannot replay CFS WAL record/),
|
'non-CFS node FATALs with a clear message on the CFS policy record'
|
);
|
ok( !$node->log_contains(qr/PANIC: smgr_redo: unknown op code/),
|
'no "smgr_redo: unknown op code" PANIC on the redo path');
|
|
$node->teardown_node(fail_ok => 1);
|
}
|
|
$primary->stop('fast');
|
};
|
|
# ---------------------------------------------------------------------------
|
# Hot standby recovery conflicts on CFS tables.
|
#
|
# The CFS concern is that buffer-pin and snapshot conflicts on
|
# decompressed CFS pages must cancel the standby query correctly, and the
|
# CFS map cache must not leak or corrupt during conflict resolution.
|
#
|
# Two conflict types are tested:
|
# 1. Buffer pin conflict: a cursor on the standby pins a CFS page;
|
# VACUUM FREEZE on the primary needs that pin.
|
# 2. Snapshot conflict: a cursor on the standby holds a snapshot that
|
# prevents pruning of dead HOT tuples on a CFS table on the primary.
|
#
|
# Each conflict is verified three ways:
|
# * check_conflict_log — the standby log contains the exact cancellation
|
# message;
|
# * check_conflict_stat — pg_stat_database_conflicts shows the conflict
|
# type counter incremented;
|
# * $psql_standby->reconnect_and_clear — the standby session was
|
# actually broken and needs reconnection.
|
# ---------------------------------------------------------------------------
|
subtest 'hot standby recovery conflicts on CFS tables' => sub {
|
# Set up nodes
|
my $node_primary = PostgreSQL::Test::Cluster->new('cfs_confl_primary');
|
$node_primary->init(allows_streaming => 1);
|
|
$node_primary->append_conf(
|
'postgresql.conf', qq[
|
max_prepared_transactions = 10
|
max_standby_streaming_delay = 50ms
|
log_recovery_conflict_waits = on
|
deadlock_timeout = 10ms
|
]);
|
$node_primary->start;
|
|
# Skip when LZ4 is not compiled in
|
my $configure = $node_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 recovery conflict test';
|
}
|
|
my $backup_name = 'my_backup';
|
$node_primary->backup($backup_name);
|
|
my $node_standby = PostgreSQL::Test::Cluster->new('cfs_confl_standby');
|
$node_standby->init_from_backup($node_primary, $backup_name,
|
has_streaming => 1);
|
$node_standby->append_conf('postgresql.conf',
|
'max_standby_streaming_delay = 50ms');
|
$node_standby->start;
|
|
my $test_db = "cfs_conflict_db";
|
|
# Use a dedicated database so pg_stat_database_conflicts is isolated.
|
$node_primary->safe_psql('postgres', "CREATE DATABASE $test_db");
|
|
# CFS table with data. The (a int, b int) layout allows HOT updates
|
# in the snapshot test.
|
my $table1 = "cfs_conflict_t1";
|
$node_primary->safe_psql(
|
$test_db, qq[
|
CREATE TABLE $table1(a int, b int) WITH (algorithm = 'lz4');
|
INSERT INTO $table1 SELECT i % 3, 0 FROM generate_series(1, 20) i;
|
]);
|
$node_primary->wait_for_replay_catchup($node_standby);
|
|
# Long-running background psql on the standby for triggering
|
# conflicts.
|
my $psql_standby =
|
$node_standby->background_psql($test_db, on_error_stop => 0);
|
|
my $cursor1 = "cfs_conflict_cursor";
|
|
# CONFLICT 1: Buffer pin conflict
|
#
|
# An aborted INSERT on the primary creates a dead tuple. A cursor on
|
# the standby pins the buffer of that page. VACUUM FREEZE on the
|
# primary needs the pin to prune the dead tuple, triggering a
|
# buffer-pin conflict on a decompressed CFS page.
|
my $sect = "buffer pin conflict";
|
|
# Aborted INSERT + flush (LOCK ensures the WAL is flushed).
|
$node_primary->safe_psql(
|
$test_db, qq[
|
BEGIN;
|
INSERT INTO $table1 VALUES (1, 0);
|
ROLLBACK;
|
BEGIN; LOCK $table1; COMMIT;
|
]);
|
$node_primary->wait_for_replay_catchup($node_standby);
|
|
# Pin the CFS page on the standby via a cursor.
|
my $res = $psql_standby->query_safe(
|
qq[
|
BEGIN;
|
DECLARE $cursor1 CURSOR FOR SELECT b FROM $table1;
|
FETCH FORWARD FROM $cursor1;
|
]);
|
like($res, qr/^0$/m, "$sect: cursor with conflicting pin established");
|
|
# Record the current standby log offset for conflict-message scanning.
|
my $log_location = -s $node_standby->logfile;
|
|
my $check_conflict_log = sub {
|
my $message = shift;
|
my $old_log_location = $log_location;
|
|
$log_location =
|
$node_standby->wait_for_log(qr/$message/, $log_location);
|
|
cmp_ok($log_location, '>', $old_log_location,
|
"$sect: logfile contains terminated connection due to recovery conflict"
|
);
|
};
|
|
my $check_conflict_stat = sub {
|
my $conflict_type = shift;
|
my $count = $node_standby->safe_psql($test_db,
|
qq[SELECT confl_$conflict_type FROM pg_stat_database_conflicts WHERE datname='$test_db';]
|
);
|
|
is($count, 1, "$sect: stats show conflict on standby");
|
};
|
|
# VACUUM FREEZE needs the pinned buffer.
|
$node_primary->safe_psql($test_db, "VACUUM FREEZE $table1;");
|
$node_primary->wait_for_replay_catchup($node_standby);
|
|
# The standby session must have been cancelled with the buffer-pin
|
# message.
|
$check_conflict_log->("User was holding shared buffer pin for too long");
|
$psql_standby->reconnect_and_clear();
|
$check_conflict_stat->("bufferpin");
|
|
# CONFLICT 2: Snapshot conflict
|
#
|
# A cursor on the standby holds a snapshot. HOT updates + VACUUM
|
# FREEZE on the primary prune dead tuples that the standby snapshot
|
# still needs to see, triggering a snapshot conflict on a decompressed
|
# CFS page.
|
$sect = "snapshot conflict";
|
|
# More rows so there is something to HOT-update.
|
$node_primary->safe_psql($test_db,
|
qq[INSERT INTO $table1 SELECT i, 0 FROM generate_series(1, 20) i]);
|
$node_primary->wait_for_replay_catchup($node_standby);
|
|
# Establish a snapshot on the standby.
|
$res = $psql_standby->query_safe(
|
qq[
|
BEGIN;
|
DECLARE $cursor1 CURSOR FOR SELECT b FROM $table1;
|
FETCH FORWARD FROM $cursor1;
|
]);
|
like($res, qr/^0$/m,
|
"$sect: cursor with conflicting snapshot established");
|
|
# HOT updates create dead tuples that VACUUM will prune.
|
$node_primary->safe_psql($test_db,
|
qq[UPDATE $table1 SET a = a + 1 WHERE a > 2;]);
|
$node_primary->safe_psql($test_db, "VACUUM FREEZE $table1;");
|
$node_primary->wait_for_replay_catchup($node_standby);
|
|
# The standby session must have been cancelled with the snapshot
|
# message.
|
$check_conflict_log->(
|
"User query might have needed to see row versions that must be removed"
|
);
|
$psql_standby->reconnect_and_clear();
|
$check_conflict_stat->("snapshot");
|
|
# Verify CFS sidecars are structurally valid after all conflict churn.
|
$node_primary->safe_psql($test_db, "CHECKPOINT;");
|
$node_primary->wait_for_replay_catchup($node_standby);
|
my $result = $node_standby->safe_psql($test_db,
|
"SELECT ok FROM pg_cfs_check('$table1'::regclass, true);");
|
is($result, 't', 'CFS sidecars valid after recovery conflicts');
|
|
# Total conflict count should be 2.
|
$result = $node_standby->safe_psql($test_db,
|
qq[SELECT conflicts FROM pg_stat_database WHERE datname='$test_db';]);
|
is($result, '2', "2 recovery conflicts shown in pg_stat_database");
|
|
$psql_standby->quit;
|
$node_standby->stop();
|
$node_primary->stop();
|
};
|
|
# ---------------------------------------------------------------------------
|
# Physical replication slot and checkpoints on a primary with CFS tables.
|
#
|
# A physical replication slot must maintain correct WAL retention across
|
# checkpoints. The CFS concern is that the checkpoint flush of .cfsmap
|
# sidecars happens in the correct order relative to the slot's
|
# restart_lsn, so the standby can always read consistent CFS data.
|
# ---------------------------------------------------------------------------
|
subtest 'physical replication slot and checkpoints on a CFS primary' => sub {
|
# Primary with a physical replication slot
|
my $node_primary = PostgreSQL::Test::Cluster->new('cfs_slot_primary');
|
$node_primary->init(allows_streaming => 1);
|
$node_primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
|
$node_primary->start;
|
|
# Skip when LZ4 is not compiled in
|
my $configure = $node_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 checkpoint slot test';
|
}
|
|
# CFS table
|
$node_primary->safe_psql(
|
'postgres', qq{
|
CREATE TABLE cfs_slot (id int, payload text) WITH (algorithm = 'lz4');
|
INSERT INTO cfs_slot SELECT g, md5(g::text) FROM generate_series(1, 200) g;
|
CHECKPOINT;
|
});
|
|
# Create a physical replication slot
|
$node_primary->safe_psql('postgres',
|
"SELECT pg_create_physical_replication_slot('slot1');");
|
|
my $backup_name = 'my_backup';
|
$node_primary->backup($backup_name);
|
|
# Standby using the slot
|
my $node_standby = PostgreSQL::Test::Cluster->new('cfs_slot_standby');
|
$node_standby->init_from_backup($node_primary, $backup_name,
|
has_streaming => 1);
|
$node_standby->append_conf('postgresql.conf',
|
"primary_slot_name = 'slot1'");
|
$node_standby->start;
|
|
# Wait for catch-up
|
$node_primary->wait_for_replay_catchup($node_standby);
|
|
# Write more data, then checkpoint (flushes .cfsmap, advances slot
|
# restart_lsn)
|
for my $round (1 .. 3)
|
{
|
$node_primary->safe_psql('postgres',
|
"INSERT INTO cfs_slot VALUES (1000 + $round, md5('round${round}'));"
|
);
|
$node_primary->safe_psql('postgres', 'CHECKPOINT;');
|
$node_primary->wait_for_replay_catchup($node_standby);
|
}
|
|
# Verify the standby sees all the data through CFS decompression
|
my $result =
|
$node_standby->safe_psql('postgres', "SELECT count(*) FROM cfs_slot;");
|
is($result, '203',
|
'Standby via physical slot sees 203 CFS rows after checkpoints');
|
|
my $primary_md5 = $node_primary->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_slot;");
|
my $standby_md5 = $node_standby->safe_psql('postgres',
|
"SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_slot;");
|
is($standby_md5, $primary_md5,
|
'Standby CFS data matches primary across checkpoint/slot cycles');
|
|
# Structural check on standby
|
$result = $node_standby->safe_psql('postgres',
|
"SELECT ok FROM pg_cfs_check('cfs_slot'::regclass, true);");
|
is($result, 't', 'CFS sidecars valid on standby after checkpoint cycles');
|
|
# Verify the slot's restart_lsn advanced (WAL was not retained
|
# unnecessarily)
|
$result = $node_primary->safe_psql('postgres',
|
"SELECT restart_lsn IS NOT NULL FROM pg_replication_slots WHERE slot_name = 'slot1';"
|
);
|
is($result, 't',
|
'Physical slot has a valid restart_lsn after CFS checkpoints');
|
|
$node_standby->stop;
|
$node_primary->stop;
|
};
|
|
# ---------------------------------------------------------------------------
|
# DROP DATABASE must cancel the pending CFS sidecar fsync requests of the
|
# dropped database on a standby, mirroring what ForgetDatabaseSyncRequests()
|
# does for md.c.
|
#
|
# XLOG_DBASE_DROP replay removes the database directory outright, with no
|
# checkpoint in between, while the checkpointer's pendingOps may still hold
|
# the CFS fsync requests of the dropped database — e.g. the ones registered
|
# when the standby replayed the creation of a CFS relation (sidecar
|
# materialization registers .cfp/.cfsmap/.cfsjrn). Without a cancellation
|
# the next restartpoint tries to fsync the already-removed sidecar files and
|
# escalates through data_sync_elevel() to PANIC.
|
#
|
# The primary-side DROP path cannot reproduce this: its forced checkpoint
|
# runs before the files are removed and drains the queue while the files
|
# still exist. fsync is enabled (TAP clusters default to fsync = off,
|
# which makes ProcessSyncRequests skip the fsync stage entirely).
|
# ---------------------------------------------------------------------------
|
{
|
my $primary = PostgreSQL::Test::Cluster->new('dropdb_primary');
|
$primary->init(allows_streaming => 1);
|
$primary->append_conf('postgresql.conf',
|
"checkpoint_timeout = 30s\nfsync = on");
|
$primary->start;
|
|
$primary->backup('dropdb_backup');
|
my $standby = PostgreSQL::Test::Cluster->new('dropdb_standby');
|
$standby->init_from_backup($primary, 'dropdb_backup', has_streaming => 1);
|
$standby->append_conf('postgresql.conf',
|
"checkpoint_timeout = 30s\nfsync = on");
|
$standby->start;
|
|
# A separate database with a CFS table and some dirty pages.
|
$primary->safe_psql('postgres', 'CREATE DATABASE dropdb_cfs');
|
$primary->safe_psql('dropdb_cfs',
|
"CREATE TABLE drop_t (id int, data text) WITH (algorithm = 'lz4')");
|
$primary->safe_psql('dropdb_cfs',
|
"INSERT INTO drop_t SELECT g, repeat('x', 200) "
|
. "FROM generate_series(1, 50) g");
|
|
# Checkpoint the primary so the standby's CHECKPOINT below performs a
|
# real restartpoint, then drain the queue: this restartpoint fsyncs
|
# (through the sync queue) everything the standby has replayed so far.
|
# It doubles as the control case: pending requests for a live database
|
# must fsync fine.
|
$primary->safe_psql('postgres', 'CHECKPOINT');
|
$primary->wait_for_catchup($standby);
|
$standby->safe_psql('postgres', 'CHECKPOINT');
|
pass('restartpoint succeeds for pending CFS requests of a live database');
|
|
# Register fresh CFS fsync requests on the standby: replaying the
|
# creation of another CFS relation materializes its sidecars and
|
# registers them with the checkpointer. These requests are the tail
|
# the next restartpoint would fsync.
|
$primary->safe_psql('dropdb_cfs',
|
"CREATE TABLE late_t (id int) WITH (algorithm = 'lz4')");
|
$primary->wait_for_catchup($standby);
|
|
# Drop the database on the primary. On the standby, XLOG_DBASE_DROP
|
# replay removes the whole database directory (rmtree before any
|
# checkpoint), while the CFS fsync requests of the dropped database are
|
# still queued — the redo path must cancel them.
|
$primary->safe_psql('postgres', 'DROP DATABASE dropdb_cfs');
|
$primary->wait_for_catchup($standby);
|
|
# The next restartpoint: use the non-fatal psql() so a PANIC (which
|
# tears the connection down) does not abort the harness.
|
my ($ret, $stdout, $stderr) = $standby->psql('postgres', 'CHECKPOINT');
|
is($ret, 0,
|
'restartpoint succeeds after DROP DATABASE cancelled CFS sync requests'
|
);
|
|
if ($ret == 0)
|
{
|
my $log = $standby->log_content();
|
|
unlike($log, qr/PANIC/,
|
'no PANIC on a restartpoint after a dropped CFS database');
|
|
is( $standby->safe_psql(
|
'postgres',
|
'SELECT count(*) FROM pg_database WHERE datname = \'dropdb_cfs\''
|
),
|
'0',
|
'dropped database is gone on the standby');
|
|
$standby->stop('fast');
|
}
|
else
|
{
|
# Red branch (the bug this test guards against): the restartpoint
|
# tried to fsync the sidecars of the removed database.
|
like(
|
$standby->log_content(),
|
qr/PANIC: could not fsync file ".*\.cfs/,
|
'the restartpoint tried to fsync the removed CFS sidecars');
|
|
$standby->stop('immediate', fail_ok => 1);
|
}
|
|
$primary->stop('fast');
|
}
|
|
# ---------------------------------------------------------------------------
|
# Session-level default GUCs of the writer never stick to the standby.
|
#
|
# The runtime level resolve happens in the WRITING backend: the level is
|
# applied when the page is compressed and is not recorded anywhere on
|
# disk (the .cfp record header stores the algorithm only; decompression
|
# never needs the level). The WAL policy record carries just the
|
# explicit catalog keys with their set-flags, so the writer session's
|
# cfs_default_*_level value must not leak to the standby: a standby
|
# session resolves the unset fields from its OWN GUCs, and the stored
|
# policy shows the 0 sentinel rather than the writer's value.
|
# ---------------------------------------------------------------------------
|
{
|
my $primary = PostgreSQL::Test::Cluster->new('cfs_guc_leak');
|
$primary->init(allows_streaming => 1);
|
$primary->start;
|
|
# Skip when ZSTD is not compiled in (the block cannot run, and the
|
# TAP plan has already started, so skip quietly instead of skip_all).
|
my $zstd_ok =
|
$primary->psql('postgres',
|
"CREATE TABLE guc_probe_avail (i int) WITH (algorithm = 'zstd')") == 0;
|
|
if ($zstd_ok)
|
{
|
$primary->safe_psql('postgres', 'DROP TABLE guc_probe_avail');
|
|
$primary->backup('guc_leak_backup');
|
my $standby = PostgreSQL::Test::Cluster->new('cfs_guc_leak_standby');
|
$standby->init_from_backup($primary, 'guc_leak_backup',
|
has_streaming => 1);
|
$standby->start;
|
|
# The writer compresses with a non-default session level.
|
$primary->safe_psql('postgres',
|
"CREATE TABLE guc_t (id int, payload text) "
|
. "WITH (algorithm = 'zstd')");
|
$primary->safe_psql('postgres',
|
"SET cfs_default_zstd_level = 19; "
|
. "INSERT INTO guc_t SELECT g, 'row ' || g "
|
. "FROM generate_series(1, 50) g");
|
|
$primary->wait_for_catchup($standby);
|
|
# The replayed data is readable on the standby (the compressed
|
# pages decode without any level knowledge).
|
is($standby->safe_psql('postgres',
|
"SELECT count(*) FILTER (WHERE payload = 'row 7') FROM guc_t"),
|
'1',
|
'pages written under a non-default GUC level replay and read on the standby');
|
|
# The writer's GUC value did not stick: the stored policy keeps
|
# the 0 sentinel for the unset level, and a standby session
|
# resolves the field from its OWN (default) GUCs.
|
is($standby->safe_psql('postgres',
|
"SELECT level FROM pg_cfs_settings WHERE relname = 'guc_t'"),
|
'0',
|
'stored policy carries the 0 sentinel, not the writer GUC level');
|
is($standby->safe_psql('postgres',
|
"SELECT level_effective FROM pg_cfs_relation_info('guc_t')"),
|
'3',
|
'standby session resolves the unset level from its own GUCs');
|
|
$standby->stop('fast');
|
}
|
else
|
{
|
diag 'zstd not available, skipping the GUC-leak block';
|
}
|
|
$primary->stop('fast');
|
}
|
|
done_testing();
|