# Copyright (c) 2026, QDB Development Group # # src/test/modules/test_cfs/t/010_cfs_nblocks_journal.pl # # QDB-1516 T6: the smgrnblocks() cache-miss path measures the size from # stat(.cfsmap) plus the journal's last RESIZE (cfs_journal_measure_nblocks) # and must handle a damaged journal exactly like the design says: # * Scenario A, crash-torn tail - a full-size garbage record at the end # of the journal is the crash artifact the scanner classifies as # TORN_TAIL: startup recovery folds and heals it, and the measured # size afterwards is exact; # * Scenario A, live torn tail - the same damage arriving while the # server runs (no restart, nothing heals it) must be tolerated by the # measurement itself: the RESIZEs in front of it stand and the # measured size is exact; # * Scenario B, mid-file corruption - a torn record with valid records # behind it is corruption: no journal-derived size can be trusted, # and the measurement REPORTS the damage for the caller to escalate # by context. A normal backend keeps the runtime contract (the CFS # corruption ERROR through cfs_checksum_failure); the startup # process - WAL redo of any post-checkpoint write consults the size # there - mirrors the recovery-fold severity contract instead: # non-strict WARNINGs and falls back to the old full-map # measurement (the cluster must boot over a damaged journal), # cfs_recovery_strict=on refuses to start. # * Scenario C, externally damaged sidecar set - the .cfsmap and # .cfsjrn deleted while the .cfp data file survives: cfs_exists() # stays true, and the size path must refuse the half-deleted set # loudly (the deterministic refusal point is the sidecar handle # open) - never answer a silent zero. # # cfs_map_cache_rels_per_partition = 2 keeps the metadata cache small so # the nblocks cache-miss path is easy to reach; the test helper # cfs_test_smgr_size_full_opens() additionally forces it deterministically # (it invalidates the relation's metadata slot and calls smgrnblocks) and # proves the path opens no full map. use strict; use warnings FATAL => 'all'; use PostgreSQL::Test::Cluster; use PostgreSQL::Test::Utils; use Test::More; # Journal layout constants (cfs_format.h): a 16-byte header followed by # 48-byte records. my $JRN_HEADER = 16; my $JRN_RECORD = 48; my $node = PostgreSQL::Test::Cluster->new('cfs_nblocks_jrn'); $node->init; $node->append_conf( 'postgresql.conf', "autovacuum = off\n" . "checkpoint_timeout = 30min\n" . "log_min_messages = warning\n" . "cfs_map_cache_rels_per_partition = 2\n" . "cfs_recovery_strict = off"); $node->start; if (!check_pg_config("#define USE_LZ4")) { plan skip_all => 'LZ4 support not built, skipping CFS nblocks journal test'; } $node->safe_psql('postgres', 'CREATE EXTENSION test_cfs'); $node->safe_psql('postgres', 'CREATE EXTENSION pg_buffercache'); sub jrn_path { my ($rel) = @_; return $node->data_dir . "/" . $node->safe_psql('postgres', "SELECT pg_relation_filepath('$rel')") . ".cfsjrn"; } # --------------------------------------------------------------------------- # Scenario A, part 1: a crash-torn journal tail heals at startup and the # measured size is exact afterwards. # --------------------------------------------------------------------------- $node->safe_psql( 'postgres', q{ CREATE TABLE nb_a (id int, payload text) WITH (algorithm = 'lz4'); CREATE TABLE nb_a_plain (id int, payload text); INSERT INTO nb_a SELECT g, repeat('na', 150) FROM generate_series(1, 3000) g; INSERT INTO nb_a_plain SELECT g, repeat('na', 150) FROM generate_series(1, 3000) g; CHECKPOINT; INSERT INTO nb_a SELECT 3000 + g, repeat('na', 150) FROM generate_series(1, 1000) g; INSERT INTO nb_a_plain SELECT 3000 + g, repeat('na', 150) FROM generate_series(1, 1000) g; }); # Flush the extension so the journal really holds records (RESIZEs) past # the checkpoint fold. $node->safe_psql('postgres', "SELECT buffers_evicted > 0 FROM pg_buffercache_evict_relation('nb_a')"); $node->safe_psql('postgres', "SELECT buffers_evicted > 0 FROM pg_buffercache_evict_relation('nb_a_plain')"); my $jrn_a = jrn_path('nb_a'); cmp_ok(-s $jrn_a, '>', $JRN_HEADER, 'the journal holds records past the fold'); # Torn tail: a full-size record of zeroes at the end of the journal - a # record whose magic/CRC fail with nothing but itself behind, exactly the # crash artifact the scanner classifies as TORN_TAIL (16 trailing bytes # would be classified as a clean partial-record EOF, an even milder case). $node->stop('immediate'); PostgreSQL::Test::Utils::append_to_file($jrn_a, "\0" x $JRN_RECORD); $node->start; # Non-strict recovery heals: the fold consumed the valid records, applied # the last RESIZE and reset the journal to its bare header. is(-s $jrn_a, $JRN_HEADER, 'startup recovery healed the torn tail'); # Churn metadata slots (128 in total) and force the nblocks cache-miss # deterministically: the helper invalidates the slot, measures the size # and reports the full maps the path opened (none allowed). for my $g (1 .. 30) { $node->safe_psql('postgres', "CREATE TABLE nb_churn_a$g (i int) WITH (algorithm = 'lz4');\n" . "INSERT INTO nb_churn_a$g VALUES ($g);\n"); } is($node->safe_psql('postgres', "SELECT cfs_test_smgr_size_full_opens('nb_a')"), '0', 'the healed size measurement opened no full map'); is($node->safe_psql('postgres', 'SELECT count(*) FROM nb_a'), '4000', 'scenario A row count is exact after the heal'); is($node->safe_psql('postgres', "SELECT (pg_cfs_relation_size('nb_a')).logical_size" . " = pg_relation_size('nb_a_plain')"), 't', 'scenario A measured size matches the plain-table oracle'); # --------------------------------------------------------------------------- # Scenario B: mid-file corruption. A journal record with valid records # behind it is corruption: the unreachable records may hold the real last # RESIZE, so no journal-derived size can be trusted. The damage is # applied to a crashed cluster with WAL pending (the post-checkpoint # inserts), because that is the regression route: WAL redo of those # writes consults the size in the STARTUP PROCESS, which must mirror the # recovery-fold severity contract - never a backend-severity escalation # there. # --------------------------------------------------------------------------- $node->safe_psql( 'postgres', q{ CREATE TABLE nb_b (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO nb_b SELECT g, repeat('nb', 150) FROM generate_series(1, 3000) g; CHECKPOINT; INSERT INTO nb_b SELECT 3000 + g, repeat('nb', 150) FROM generate_series(1, 1000) g; }); $node->safe_psql('postgres', "SELECT buffers_evicted > 0 FROM pg_buffercache_evict_relation('nb_b')"); my $jrn_b = jrn_path('nb_b'); cmp_ok(-s $jrn_b, '>=', $JRN_HEADER + 4 * $JRN_RECORD, 'the journal holds at least four records'); # Crash without a checkpoint: the post-checkpoint inserts live only in # WAL, so the next startup replays them and redo extends the relation # (every extension consults the size in the startup process). $node->stop('immediate'); # Zero the third record while the server is down: the header and two # records stay intact, a valid record space follows, so the scanner must # classify the stop as TORN_MIDFILE. { my $off = $JRN_HEADER + 2 * $JRN_RECORD; open(my $fh, '+<', $jrn_b) or BAIL_OUT("could not open $jrn_b: $!"); binmode($fh); seek($fh, $off, 0) or BAIL_OUT("could not seek $jrn_b: $!"); print $fh "\0" x $JRN_RECORD or BAIL_OUT("could not write $jrn_b: $!"); close($fh) or BAIL_OUT("could not close $jrn_b: $!"); } # Non-strict startup (cfs_recovery_strict = off, pinned above): the # cluster MUST boot over the damaged journal. The startup's size # measurement WARNINGs and falls back to the full map - the # pre-QDB-1516 behaviour, never more than a WARNING from the size path # during recovery. my $log_off = -s $node->logfile; ok($node->start, 'non-strict startup boots over the damaged journal'); $node->log_check('startup falls back to the full map', $log_off, log_like => [qr/CFS: size measurement for relation .* stopped at a torn journal record, falling back to the full map/]); # Fresh WAL behind the tear for the strict direction below. The # metadata slot is warm from recovery, so the extension consults the # fast path and the session never touches the damaged measurement. $node->safe_psql('postgres', "INSERT INTO nb_b SELECT 5000 + g, repeat('nb', 150) FROM generate_series(1, 200) g"); # The size measurement on the damaged journal in a NORMAL session must # fail with the corruption error instead of answering from the # unreachable records behind the tear. The helper invalidates the # metadata slot first, so the measurement always takes the slow path. my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT cfs_test_smgr_size_full_opens('nb_b')"); isnt($ret, 0, 'the size of the mid-file-corrupted relation fails'); like($stderr, qr/CFS:/, 'the failure went through the CFS corruption channel'); like($stderr, qr/torn record/, 'the error names the torn record as the cause'); # Strict mode must refuse the same damage. The fatal report may come # from the recovery fold or from the redo-time size measurement (both # route through the same recovery channel under cfs_recovery_strict); # the observable contract - a mid-file-damaged journal never boots # strict - is what is pinned here. The GUC is PGC_POSTMASTER, so the # directions flip with append_conf + restart. $node->stop('immediate'); $node->append_conf('postgresql.conf', 'cfs_recovery_strict = on'); $log_off = -s $node->logfile; my $started = $node->start(fail_ok => 1); ok(!$started, 'strict=on: a mid-file-torn journal aborts the startup'); $node->log_check('strict startup refusal', $log_off, log_like => [qr/checksum or format corruption/i]); # Back to non-strict: the same cluster must come up again (the WARNING + # full-map fallback answers the redo-time consults). $node->append_conf('postgresql.conf', 'cfs_recovery_strict = off'); $log_off = -s $node->logfile; ok($node->start, 'strict=off: server starts over the damaged journal'); # Remove the damaged relation: no checkpoint may ever fold its journal. $node->safe_psql('postgres', 'DROP TABLE nb_b'); # --------------------------------------------------------------------------- # Scenario C (review Н-2): an externally damaged sidecar set - the .cfsmap # and .cfsjrn deleted while the .cfp data file survives, so cfs_exists() # (any of the three) keeps the relation CFS-visible. A drop removes the # whole triple, so this is external damage, and the size path must refuse # it loudly; the deterministic refusal point is the sidecar handle open # ("could not open sidecar files"), which runs before the measurement. # The pin guards the observable contract - never a silent zero for a # half-deleted set - whatever layer fires first (the racy in-measurement # window is additionally hardened by the .cfp third witness, see # cfs_journal_measure_nblocks). # --------------------------------------------------------------------------- $node->safe_psql( 'postgres', q{ CREATE TABLE nb_c (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO nb_c SELECT g, repeat('nc', 150) FROM generate_series(1, 500) g; CHECKPOINT; }); my $relpath_c = $node->safe_psql('postgres', "SELECT pg_relation_filepath('nb_c')"); my $map_c = $node->data_dir . "/$relpath_c.cfsmap"; my $jrn_c = $node->data_dir . "/$relpath_c.cfsjrn"; my $cfp_c = $node->data_dir . "/$relpath_c.cfp"; ok(-f $cfp_c && -f $map_c && -f $jrn_c, 'the sidecar triple is complete before the damage'); # A fast stop checkpoints cleanly (no WAL replay will touch nb_c at the # next startup), and the damage is the external deletion of two of the # three sidecar files while the server is down. $node->stop('fast'); unlink($map_c) or BAIL_OUT("could not unlink $map_c: $!"); unlink($jrn_c) or BAIL_OUT("could not unlink $jrn_c: $!"); ok(-f $cfp_c, 'the .cfp data file survived the external damage'); ok($node->start, 'the cluster boots over the half-deleted sidecar set'); my ($ret_c, $stdout_c, $stderr_c) = $node->psql('postgres', "SELECT cfs_test_smgr_size_full_opens('nb_c')"); isnt($ret_c, 0, 'the size path refuses the half-deleted sidecar set'); like($stderr_c, qr/could not open sidecar files/, 'the refusal is loud, naming the sidecar open failure'); # Cleanup: remove the damaged relation before the later scenarios. $node->safe_psql('postgres', 'DROP TABLE nb_c'); # --------------------------------------------------------------------------- # Scenario A, part 2: a torn tail arriving while the server runs (no # restart, nothing heals it) must be tolerated by the measurement itself. # --------------------------------------------------------------------------- $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql( 'postgres', q{ INSERT INTO nb_a SELECT 4000 + g, repeat('na', 150) FROM generate_series(1, 500) g; INSERT INTO nb_a_plain SELECT 4000 + g, repeat('na', 150) FROM generate_series(1, 500) g; }); $node->safe_psql('postgres', "SELECT buffers_evicted > 0 FROM pg_buffercache_evict_relation('nb_a')"); $node->safe_psql('postgres', "SELECT buffers_evicted > 0 FROM pg_buffercache_evict_relation('nb_a_plain')"); cmp_ok(-s $jrn_a, '>', $JRN_HEADER, 'the live journal holds fresh records'); PostgreSQL::Test::Utils::append_to_file($jrn_a, "\0" x $JRN_RECORD); # Force the measure path on the damaged journal: the torn tail must be # tolerated and the answer must still be the post-extension size. is($node->safe_psql('postgres', "SELECT cfs_test_smgr_size_full_opens('nb_a')"), '0', 'the live torn tail did not fail the measurement'); is($node->safe_psql('postgres', 'SELECT count(*) FROM nb_a'), '4500', 'scenario A row count is exact with a live torn tail'); is($node->safe_psql('postgres', "SELECT (pg_cfs_relation_size('nb_a')).logical_size" . " = pg_relation_size('nb_a_plain')"), 't', 'the live-torn-tail size matches the plain-table oracle'); # Stop without a checkpoint: nb_a's journal still carries the live torn # tail, and a checkpoint that flushes nb_a's hint-dirtied pages would # append records behind the garbage, turn it mid-file, and fail. $node->stop('immediate'); done_testing();