# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group # # src/test/recovery/t/502_cfs_durability.pl # # Durability and corruption-handling contracts of the CFS storage layer: # * a CRC mismatch on a .cfp block payload raises a regular ERROR by # default, and PANICs the whole cluster with # cfs_checksum_failure = panic; # * every index AM (btree/hash/gin/gist/brin/spgist) can be built and # read back through the CFS storage layer with zstd compression, with # the codec state safely reused across query cycles; # * cfs_recovery_strict turns a corrupt .cfsjrn header discovered during # crash recovery from a tolerable WARNING into a fatal startup error; # * an fsync() failure of a CFS sidecar during a checkpoint escalates to # PANIC (via data_sync_elevel), exactly like md.c treats an fsync # failure of a base relation segment — a checkpoint that "succeeds" # without durable data would let the WAL needed to rebuild the # relation be recycled; # * a checkpoint persists .cfsmap snapshots only for CFS relations # written since the last checkpoint (dirty_checkpoint), not for # every occupied metadata slot. use strict; use warnings FATAL => 'all'; use Config; use PostgreSQL::Test::Cluster; use PostgreSQL::Test::Utils; use Test::More; # True when the server was configured with the given --with- flag; # the codec-specific subtests skip on builds without the codec. sub codec_built { my ($node, $codec) = @_; my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); return $configure =~ /--with-$codec/; } # --------------------------------------------------------------------------- # Checksum failure: ERROR by default, PANIC on demand # # With cfs_checksum_failure = panic, a CRC mismatch on a CFS block payload # must bring the server down (PANIC) rather than just failing the current # query. With the default (error), the same corruption must produce a # regular ERROR and leave the server up. # # The corruption is a single flipped byte deep inside the .cfp payload # (past the block header), so the block parses but its content fails the # post-decompression CRC check routed through cfs_report_corruption(). # --------------------------------------------------------------------------- { my $node = PostgreSQL::Test::Cluster->new('cfs_checksum_panic'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS checksum panic test'; } # Build a CFS table with at least a few compressed pages. $node->safe_psql('postgres', "CREATE TABLE panic_t (id int, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO panic_t SELECT g, repeat('p' || g, 300) " . "FROM generate_series(1, 300) g"); $node->safe_psql('postgres', "CHECKPOINT"); # Resolve the sidecar path while the server is still up, then stop # cleanly. my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('panic_t')"); my $cfp = "$dd/$path.cfp"; ok(-f $cfp, '.cfp sidecar exists for the CFS table'); $node->stop('fast'); # Flip a single byte deep in the payload region (offset 200 is well # past any CompressedBlockHeader at the start of the first record). { open my $fh, '+<:raw', $cfp or die "open $cfp: $!"; seek($fh, 200, 0) or die "seek: $!"; my $b; read($fh, $b, 1); seek($fh, 200, 0) or die "seek: $!"; my $flipped = ord($b) ^ 0xFF; print $fh chr($flipped); close($fh); } pass('flipped one payload byte in the .cfp'); # Default (error): reading the corrupted block fails the query, server # stays. $node->start; # Reading block 0 (the corrupted one) errors out; use the non-fatal # psql() so the ERROR does not abort the test harness. my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT count(*) FROM panic_t"); like( $stderr, qr/corruption|checksum|decompress/i, 'corrupted block reports a CRC/decompression error' ) or note("query rc=$ret stderr=$stderr"); $node->safe_psql('postgres', "SELECT 1"); # server still up in error mode pass('server stays up under cfs_checksum_failure=error'); # panic: reading the corrupted block must force the whole cluster # down. $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_checksum_failure = 'panic'"); $node->safe_psql('postgres', "SELECT pg_reload_conf()"); $node->reload; # Trigger a read of the corrupted block; expect the connection to drop # because the backend PANICs. ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT count(*) FROM panic_t"); isnt($ret, 0, 'read of corrupted block under panic mode fails'); # Under PANIC the whole cluster goes down. init() sets # restart_after_crash = off, so the server stays down and there is no # postmaster to stop any more; use fail_ok so the harness teardown # does not bail out on the missing PID. $node->stop('immediate', fail_ok => 1); } # --------------------------------------------------------------------------- # zstd-compressed indexes of every AM # # Every index AM (btree/hash/gin/gist/brin/spgist) can be built and read # back through the CFS storage layer with zstd compression, both with an # explicit policy and via inheritance from a zstd-compressed table. # # The zstd codec state holds live ZSTD_CCtx / ZSTD_DCtx pointers and is # cached per backend across queries, so it must outlive any per-query # memory context; a state allocated in a transient context would dangle # after the query that created it and crash the next decompress call. # (LZ4 is unaffected because its block API is stateless.) This test # stresses the codec reuse path by building and reading zstd indexes # across multiple query cycles. # --------------------------------------------------------------------------- subtest 'zstd-compressed indexes of every AM' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_zstd_index'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 36000000"); $node->start; if (!codec_built($node, 'zstd')) { plan skip_all => 'Zstd support required, skipping CFS zstd-index test'; } # 1. A zstd-compressed heap. Force a zstd decompression in a # *previous* query (which allocates the codec state), then build # zstd indexes in *later* queries that reuse the cached state. $node->safe_psql('postgres', "CREATE TABLE t_z (id int, data text, tags text[], pt point) " . "WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "INSERT INTO t_z (id, data, tags, pt) " . "SELECT g, md5(g::text), ARRAY[md5(g::text)], point(g, g) " . "FROM generate_series(1, 500) g"); # Heap read in a separate query so the zstd codec state is created and # cached before the index builds below. my $sum = $node->safe_psql('postgres', "SELECT md5(string_agg(data, '' ORDER BY id)) FROM t_z"); is(length($sum), 32, 'zstd heap read round-trips through decompression'); # 2. Build one zstd index per AM with an explicit algorithm and read # it back in a separate query each, exercising cross-query # codec-state reuse. $node->safe_psql('postgres', "CREATE INDEX ix_zbtree ON t_z USING btree (id) " . "WITH (algorithm = 'zstd', level = 3)"); $node->safe_psql('postgres', "CREATE INDEX ix_zhash ON t_z USING hash (data) " . "WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "CREATE INDEX ix_zgin ON t_z USING gin (tags) " . "WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "CREATE INDEX ix_zgist ON t_z USING gist (pt) " . "WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "CREATE INDEX ix_zbrin ON t_z USING brin (id) " . "WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "CREATE INDEX ix_zspgist ON t_z USING spgist (data) " . "WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "SET enable_seqscan = off"); is( $node->safe_psql( 'postgres', "SELECT count(*) FROM t_z WHERE id = 42"), 1, 'zstd btree index lookup'); is( $node->safe_psql( 'postgres', "SELECT count(*) FROM t_z WHERE data = md5('42')"), 1, 'zstd hash index lookup'); is( $node->safe_psql( 'postgres', "SELECT count(*) FROM t_z WHERE tags @> ARRAY[md5('42')]"), 1, 'zstd gin index lookup'); is( $node->safe_psql( 'postgres', "SELECT count(*) FROM t_z WHERE pt <@ box(point(0,0),point(5,5))" ), 5, 'zstd gist index lookup'); is( $node->safe_psql( 'postgres', "SELECT count(*) FROM t_z WHERE id < 10"), 9, 'zstd brin index lookup'); is( $node->safe_psql( 'postgres', "SELECT count(*) FROM t_z WHERE data = md5('42')"), 1, 'zstd spgist index lookup'); # 3. Inherited policy: a zstd index on the zstd table WITHOUT an # explicit algorithm inherits zstd and must round-trip through the # same codec path. Per the explicit-only reloptions contract, the # inheriting index stores the table's algorithm and only its # explicitly stored auxiliary keys (t_z has none, so the algorithm # alone is copied); unset fields resolve from the session GUCs at # write time and the index is independent of the table afterwards. $node->safe_psql('postgres', "CREATE INDEX ix_inh ON t_z USING btree (data)"); is( $node->safe_psql( 'postgres', "SELECT reloptions::text FROM pg_class WHERE oid = 'ix_inh'::regclass" ), '{algorithm=zstd}', 'inheriting zstd index stores the table algorithm and explicit keys'); my $inh_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('ix_inh')"); ok( -f $node->data_dir . "/$inh_path.cfp", 'inheriting zstd index has CFS sidecar files'); is( $node->safe_psql( 'postgres', "SET enable_seqscan = off; SELECT count(*) FROM t_z WHERE data = md5('7')" ), 1, 'inherited zstd index usable'); # 4. Cross-statement codec reuse stress: interleave zstd heap writes # (which compress) and zstd index reads (which decompress) across # many query cycles. Use fresh data values so lookups are # unambiguous. for my $i (1 .. 20) { $node->safe_psql('postgres', "SET enable_seqscan = off"); $node->safe_psql('postgres', "INSERT INTO t_z (id, data, tags, pt) " . "VALUES (9000+$i, 'stress_$i', ARRAY['stress_$i'], " . "point(9000+$i, 9000+$i))"); my $n = $node->safe_psql('postgres', "SELECT count(*) FROM t_z WHERE tags @> ARRAY['stress_$i']"); is($n, 1, "zstd gin lookup after intermixed insert #$i"); } # 5. The zstd-compressed indexes survive a clean restart (on-disk # pages are decompressed correctly by a fresh backend that # allocates a brand-new codec state). $node->safe_psql('postgres', "CHECKPOINT"); $node->restart(); is( $node->safe_psql( 'postgres', "SET enable_seqscan = off; SELECT count(*) FROM t_z WHERE id = 42" ), 1, 'zstd btree index usable after restart'); is( $node->safe_psql( 'postgres', "SET enable_seqscan = off; " . "SELECT count(*) FROM t_z WHERE pt <@ box(point(0,0),point(5,5))" ), 5, 'zstd gist index usable after restart'); is($node->safe_psql('postgres', "SELECT count(*) FROM t_z"), 520, 'row count is correct after restart'); $node->stop('immediate'); }; # --------------------------------------------------------------------------- # A corrupt .cfsjrn header aborts startup in every mode # # The journal header is structural damage: without a valid header the # records cannot be interpreted at all, so no replay decision can be made # safely. Mirror vanilla PostgreSQL, where an invalid WAL record is fatal # in every mode — there is no "treat the journal as empty" escape hatch, # with or without cfs_recovery_strict (the GUC remains meaningful for the # record-level cases: torn and skipped records). # # The corruption zeroes the 4-byte journal magic at offset 0 (header # validation fails on bad magic). The failed startup must leave the # on-disk files untouched — the snapshot is not rewritten, the journal is # not truncated — so the corruption stays diagnosable on disk. # # cfs_recovery_strict is PGC_POSTMASTER, so each direction is flipped with # append_conf() + restart: after the first failed start the server is down # and cannot execute ALTER SYSTEM. # --------------------------------------------------------------------------- subtest 'corrupt .cfsjrn header aborts startup in every mode' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_jrn_fatal'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS journal-header corruption test'; } # Build a CFS table, flush a clean map snapshot via CHECKPOINT, then # write past the checkpoint so the journal holds records at the stop # (the scan only opens a relation for a NON-empty journal). An # immediate stop keeps the journal records on disk; WAL redo recovers # the rows at a later successful start. $node->safe_psql('postgres', "CREATE TABLE jrn_fatal_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO jrn_fatal_t SELECT g, repeat('s' || g, 80) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "INSERT INTO jrn_fatal_t SELECT g, repeat('s' || g, 80) " . "FROM generate_series(501, 600) g"); my $data_dir = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('jrn_fatal_t')"); my $jrn = "$data_dir/$rel_path.cfsjrn"; my $map = "$data_dir/$rel_path.cfsmap"; ok(-f $jrn, '.cfsjrn sidecar exists for the CFS table'); # Crash so the journal keeps its records past the header. $node->stop('immediate'); ok(-s $jrn > 16, 'journal holds records at the stop'); # Zero the 4-byte journal magic at offset 0. Overwriting (not XOR) # keeps the corruption identical across both directions below. { open my $fh, '+<:raw', $jrn or die "open $jrn: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh "\x00\x00\x00\x00"; close($fh); } pass('zeroed the .cfsjrn header magic'); # Remember the exact bytes: neither failed startup may rewrite them. my $map_before = PostgreSQL::Test::Utils::slurp_file($map); my $jrn_before = PostgreSQL::Test::Utils::slurp_file($jrn); # Direction 1: strict = on. The corrupt header must abort recovery. $node->append_conf('postgresql.conf', "cfs_recovery_strict = on"); my $log_off = -s $node->logfile; # restart_after_crash is off (set by init), so a failed startup stays # down and start(fail_ok => 1) returns 0. my $started = $node->start(fail_ok => 1); ok(!$started, 'server does NOT start with cfs_recovery_strict=on and corrupt .cfsjrn' ); # The server must refuse connections. my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT 1"); isnt($ret, 0, 'connection rejected while recovery is aborted'); $node->log_check('strict=on recovery abort message', $log_off, log_like => [qr/corrupt page map journal/i]); # Direction 2: strict = off on the SAME corruption must refuse as # well — the header check is not gated on the GUC anymore. $node->append_conf('postgresql.conf', "cfs_recovery_strict = off"); $log_off = -s $node->logfile; $started = $node->start(fail_ok => 1); ok(!$started, 'server does NOT start with cfs_recovery_strict=off either'); $node->log_check('strict=off recovery abort message', $log_off, log_like => [qr/corrupt page map journal/i]); # Neither failed startup rewrote the sidecars: the evidence is intact. is(PostgreSQL::Test::Utils::slurp_file($map), $map_before, '.cfsmap is left untouched by the failed startups'); is(PostgreSQL::Test::Utils::slurp_file($jrn), $jrn_before, '.cfsjrn is left untouched by the failed startups'); }; # --------------------------------------------------------------------------- # A corrupt per-entry CRC in .cfsmap surfaces at the first read of the block # # Unlike the header (covered above), a bit-rotten map entry is block-local # damage: the startup scan has no reason to walk every entry (the # header-only path exists precisely because a clean journal needs no # replay), so the server starts fine and the corruption surfaces when a # backend first trusts the entry — a WARNING plus CFS_STORAGE_CORRUPT # routed through the shared corruption-reporting path (a regular ERROR by # default). # # The corruption flips one byte of block 0's entry_crc field itself (map # offset CFS_MAP_HEADER_SIZE + offsetof(CfsMapEntry, entry_crc) = 8 + 16), # which deterministically breaks the CRC without touching any other field. # # The corrupt row loads as INVALID and, with an empty # journal (the checkpoint truncated it), the post-replay validation routes # the damage through cfs_report_corruption() - a WARNING during the # recovery scan (strict off) and a client-facing ERROR when a backend # loads the map for the first read. The observable outcome is unchanged: # the server starts, the SELECT fails. # --------------------------------------------------------------------------- subtest 'corrupt .cfsmap entry CRC surfaces at first read' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_map_entry_crc'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS map-entry corruption test'; } $node->safe_psql('postgres', "CREATE TABLE map_entry_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO map_entry_t SELECT g, repeat('e' || g, 80) " . "FROM generate_series(1, 500) g"); # Flush the map snapshot so block 0's entry lives in .cfsmap (not only # in the journal), then crash: the entries stay on disk as written. $node->safe_psql('postgres', "CHECKPOINT"); # Resolve the sidecar path while the server is still up. my $data_dir = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('map_entry_t')"); my $map = "$data_dir/$rel_path.cfsmap"; ok(-f $map, '.cfsmap sidecar exists for the CFS table'); $node->stop('immediate'); # Flip one byte of block 0's entry_crc field (map offset 24: # 8-byte map prologue + 16-byte offsetof(CfsMapEntry, entry_crc)). { open my $fh, '+<:raw', $map or die "open $map: $!"; seek($fh, 24, 0) or die "seek: $!"; my $byte; read($fh, $byte, 1) or die "read: $!"; seek($fh, 24, 0) or die "seek: $!"; print $fh chr(ord($byte) ^ 0xff); close($fh); } pass('flipped block 0 entry_crc in .cfsmap'); my $map_before = PostgreSQL::Test::Utils::slurp_file($map); # The header is intact, so the startup scan must NOT abort: the server # accepts connections and the entry damage stays latent until read. ok($node->start, 'server starts with a corrupt map entry (header intact)'); # The first read of block 0 must refuse to serve it instead of # decompressing through a corrupted entry. The client-facing ERROR # comes from cfs_report_corruption(); the entry-level detail rides as # the DETAIL line of that report (segment path: "invalid page map # entry"; the authoritative-map fallback keeps the load-time wording). my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT count(*) FROM map_entry_t"); isnt($ret, 0, 'SELECT fails on a corrupted map entry'); like( $stderr, qr/checksum or format corruption.*block 0/, 'client-facing corruption error names block 0'); $node->log_check('entry-level corruption detail in the log', 0, log_like => [qr/(checksum or format error in compressed page|invalid page map entry for block 0|page map entry failed its checksum)/]); # The failed read did not rewrite the map. is(PostgreSQL::Test::Utils::slurp_file($map), $map_before, '.cfsmap is left untouched by the failed read'); }; # --------------------------------------------------------------------------- # fsync failure of a CFS sidecar during a checkpoint # # Durability contract: an fsync() failure of a CFS sidecar (.cfp / # .cfsjrn) during a checkpoint must be fatal for the whole cluster (PANIC # via data_sync_elevel), exactly like md.c treats an fsync failure of a # base relation segment. A checkpoint that "succeeds" without durable # data lets the WAL segments needed to rebuild the relation be recycled, # so after the next crash the data is irrecoverable. # # The fsync failure is injected deterministically through the debug GUC # cfs_debug_fail_fsync (default 0, a complete no-op in production): when # it is greater than zero, the CFS fsync wrapper simulates an EIO instead # of doing a real fsync. # --------------------------------------------------------------------------- subtest 'fsync failure of a CFS sidecar' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_ckpt_fsync'); $node->init; # Keep background checkpoints out of the way; the test drives its own. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; if (!codec_built($node, 'zstd')) { plan skip_all => 'zstd support not built, skipping CFS checkpoint fsync test'; } # A dirty CFS relation whose .cfp will be fsync'd by the next # checkpoint. $node->safe_psql('postgres', "CREATE TABLE ckpt_t (id int, data text) WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "INSERT INTO ckpt_t SELECT g, repeat('x', 200) " . "FROM generate_series(1, 50) g"); # Reload the debug injection GUC into the checkpointer, then request a # checkpoint: the checkpointer fsyncs the .cfp/.cfsjrn sidecars, which # now fail synthetically. $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_debug_fail_fsync = 100"); $node->reload; # CHECKPOINT runs in the checkpointer; use the non-fatal psql() so a # PANIC (which tears the connection down) does not abort the harness. my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT'); isnt($ret, 0, 'checkpoint with an injected fsync failure does not succeed'); # Under data_sync_elevel() the failure escalates to PANIC, bringing # the whole cluster down. restart_after_crash defaults to off for a # TAP cluster, so the postmaster is gone; stop() must tolerate the # missing PID. my $log = $node->log_content(); like( $log, qr/CFS: fsync of.*failed/, 'log records the CFS sidecar fsync failure'); like($log, qr/PANIC/, 'fsync failure on a CFS checkpoint escalates to PANIC'); $node->stop('immediate', fail_ok => 1); }; # --------------------------------------------------------------------------- # Write-path and read-path I/O failures of a CFS relation # # A pwrite()/pread() failure of a sidecar (the ENOSPC/EIO class) must fail # the current statement loudly and leave the server up and the relation # usable. The write path is driven through pg_cfs_compact - the compaction # copy goes through the same cfs_pwrite_all() as record appends, but runs # in a user backend, so the failure surfaces as a regular ERROR (an # injected write failure under the buffer manager would fire in the # bgwriter, a different and timing-dependent contract). The read path is # driven through a plain SELECT: both the synchronous and the AIO read # funnel through the injected point. In both cases the live pair must be # untouched, and once the transient condition is gone the next statement # succeeds. Mirror vanilla PostgreSQL, where an I/O error of a base # relation segment errors the query without taking the cluster down. # # The failures are injected deterministically through the debug GUCs # cfs_debug_fail_pwrite / cfs_debug_fail_read (default 0, complete no-ops # in production): when set to N, the next N writes (cfs_pwrite_all - every # CFS write: record appends, journal appends, the compaction copy) or reads # (cfs_read_raw_record) fail with EIO. # # Both GUCs are PGC_SIGHUP, so every process - background ones included - # receives the counter on reload. A background process (bgwriter, # checkpointer, autovacuum) spending the injected failure in the window # between the reload and the target command would leave the subtest # falsely green; the subtest relies on that not happening: the preceding # CHECKPOINT flushed all CFS writes, checkpoint_timeout = 30s keeps the # checkpointer quiet across the window, and the tables are too small for # autovacuum to bother. The window is narrow and the assumption is # accepted deliberately. # --------------------------------------------------------------------------- subtest 'pwrite and pread failures of a CFS relation' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_io_eio'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS I/O failure test'; } # Two flushed versions of every page: dead space, so the compaction # below has something to copy. $node->safe_psql('postgres', "CREATE TABLE io_eio_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO io_eio_t SELECT g, repeat('w' || g, 80) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE io_eio_t SET payload = repeat('z' || id, 80)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $dd = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('io_eio_t')"); my $cfp_file = "$dd/$rel_path.cfp"; my $size_before = -s $cfp_file; my $ck = $node->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t"); # --- Write path: the compaction copy fails on the injected pwrite ----- $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_debug_fail_pwrite = 1"); $node->reload; my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_compact('io_eio_t')"); isnt($ret, 0, 'pg_cfs_compact fails on an injected pwrite failure'); # The failed compaction is a failed transaction: no commit marker, no # candidates, the live pair untouched, the relation still readable. ok(!-f "$cfp_file.cfsswap", 'no commit marker after the failed compaction'); ok(!-f "$cfp_file.new", 'no .cfp.new candidate after the failure'); is(-s $cfp_file, $size_before, 'live .cfp untouched by the failed compaction'); is( $node->safe_psql( 'postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t"), $ck, 'relation still readable after the failed compaction'); # The counter is spent: the next compaction succeeds and reclaims. $node->safe_psql('postgres', "ALTER SYSTEM RESET cfs_debug_fail_pwrite"); $node->reload; like( $node->safe_psql('postgres', "SELECT pg_cfs_compact('io_eio_t')"), qr/reclaimed \d+/, 'next compaction succeeds after the transient write failure'); is( $node->safe_psql( 'postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t"), $ck, 'data unchanged by the successful compaction'); # --- Read path: one injected pread failure ---------------------------- # Evict the table's pages so the read really goes through the CFS smgr # path, then fail the first record read. $node->safe_psql('postgres', 'CHECKPOINT'); $node->restart; $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_debug_fail_read = 1"); $node->reload; ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT count(*) FROM io_eio_t"); isnt($ret, 0, 'SELECT fails on an injected pread failure'); like( $stderr, qr/CFS: could not read block/, 'read failure reported to the client'); # The server stays up and the very next read succeeds. The injection # counter is per-process (every backend starts with the GUC value), so # the follow-up read must run in the SAME session that already spent # it: with on_error_stop disabled psql continues past the failed # statement, and the second statement reads the whole table undisturbed. ($ret, $stdout, $stderr) = $node->psql( 'postgres', "SELECT count(*) FROM io_eio_t; " . "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM io_eio_t", on_error_stop => 0); is($ret, 0, 'psql script with one failed statement completes'); like( $stderr, qr/CFS: could not read block/, 'first statement of the follow-up read failed as spent'); $stdout =~ s/^\s+|\s+$//g; is($stdout, $ck, 'next read in the same session succeeds after the read failure'); $node->safe_psql('postgres', "ALTER SYSTEM RESET cfs_debug_fail_read"); $node->reload; $node->stop('fast'); }; # --------------------------------------------------------------------------- # Journal truncate failure of a CFS checkpoint # # Truncating the .cfsjrn back to its bare header is the last durability # step of the CFS checkpoint protocol; afterwards the relation's # dirty_checkpoint mark is cleared. A truncation that fails must # therefore fail the checkpoint itself (data_sync_elevel, i.e. PANIC # with the default data_sync_retry = off) — a checkpoint that # "succeeds" without the truncation would clear the dirty mark while # the journal keeps growing, silently losing the error on every future # checkpoint, in contrast with every other durability failure around # it (fsync of .cfp/.cfsjrn, journal header rewrite) which is already # fatal. # # The failure is injected deterministically through the debug GUC # cfs_debug_fail_truncate (default 0, a complete no-op in production): # when it is greater than zero, the next journal truncations pretend # pg_truncate() failed with EIO. After the failure the server must # come back with the injection disabled and truncate the journal on # the next checkpoint. # --------------------------------------------------------------------------- subtest 'journal truncate failure of a CFS checkpoint' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_ckpt_truncate'); $node->init; # Keep background checkpoints out of the way; the test drives its own. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; plan skip_all => 'zstd support not built, skipping CFS journal truncate failure test' if !codec_built($node, 'zstd'); # A dirty CFS relation: the next checkpoint persists its map snapshot # and truncates its journal. $node->safe_psql('postgres', "CREATE TABLE ckpt_jrn (id int, data text) WITH (algorithm = 'zstd')" ); $node->safe_psql('postgres', "INSERT INTO ckpt_jrn SELECT g, repeat('x', 200) " . "FROM generate_series(1, 50) g"); # Resolve the sidecar path while the server is up. my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('ckpt_jrn')"); my $cfsjrn = "$dd/$path.cfsjrn"; ok(-f $cfsjrn, '.cfsjrn sidecar exists for the CFS table'); # Load the debug injection into the checkpointer and request a # checkpoint: the journal truncation step now fails synthetically. $node->append_conf('postgresql.conf', 'cfs_debug_fail_truncate = 1'); $node->reload; # CHECKPOINT runs in the checkpointer; use the non-fatal psql() so a # PANIC (which tears the connection down) does not abort the harness. my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT'); isnt($ret, 0, 'checkpoint with an injected journal truncate failure does not succeed' ); # Under data_sync_elevel() the failure escalates to PANIC, bringing # the whole cluster down. restart_after_crash defaults to off for a # TAP cluster, so the postmaster is gone; stop() must tolerate the # missing PID. my $log = $node->log_content(); like( $log, qr/could not truncate journal/, 'log records the journal truncate failure'); like($log, qr/PANIC/, 'journal truncate failure on a CFS checkpoint escalates to PANIC'); # Short-circuit the red case: the steps below assume the server is # down (the checkpoint must have PANIC'd the cluster). return if $ret == 0; # The postmaster may still be shutting down after the PANIC; stop() # tolerates the already-gone PID and waits for the shutdown to finish. $node->stop('immediate', fail_ok => 1); # Disable the injection again (the server is down, so edit the file # directly) and restart: crash recovery replays the table, the # end-of-recovery checkpoint truncates the journal for real and the # server must come up. my $conf = $node->data_dir . '/postgresql.conf'; my $conf_text = PostgreSQL::Test::Utils::slurp_file($conf); $conf_text =~ s/^cfs_debug_fail_truncate = 1$//m; open my $cfh, '>', $conf or die "open $conf: $!"; print $cfh $conf_text; close $cfh; $node->start; ok(-s $cfsjrn < 1024, '.cfsjrn is truncated back to its bare header after recovery'); is($node->safe_psql('postgres', 'SELECT count(*) FROM ckpt_jrn'), '50', 'CFS table survives the crash intact'); }; # --------------------------------------------------------------------------- # Journal truncate failure during crash recovery # # The recovery scan also truncates each replayed journal (after saving # the map snapshot). Unlike the checkpoint's truncation, this one is the # idempotent tail step of an operation the next restart simply repeats, # so a failure must stay a WARNING there: the server comes up, the # journal keeps its records, and a later restart with the failure gone # truncates it. Escalating the recovery path like the checkpoint # (data_sync_elevel, i.e. PANIC with the default data_sync_retry = off) # would kill the startup process and crash-loop the cluster over a # cosmetic failure. # # The failure is injected through cfs_debug_fail_truncate (see the # checkpoint subtest above); the GUC takes effect from postgresql.conf # at startup, so the injection is armed before crash recovery runs. # The counter is per-process, so the freshly forked checkpointer re-arms # the fault for its end-of-recovery checkpoint and the cluster dies # there — that is the checkpoint contract of the subtest above, not the # regression under test. What must NOT happen is the recovery scan # itself escalating: its truncate failure has to stay a WARNING that # recovery runs past (the following "checkpoint starting" and redo lines # prove the scan completed), with the only escalation coming from the # end-of-recovery checkpoint afterwards. # --------------------------------------------------------------------------- subtest 'journal truncate failure during crash recovery' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_recov_truncate'); $node->init; # Keep background checkpoints out of the way so the journal keeps # its records until the crash. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nmax_wal_size = 1GB"); $node->start; plan skip_all => 'zstd support not built, skipping CFS recovery truncate failure test' if !codec_built($node, 'zstd'); # A dirty CFS relation whose journal still holds records when the # server crashes: the recovery scan replays them, saves the map # snapshot and tries to truncate the journal. $node->safe_psql('postgres', "CREATE TABLE recov_jrn (id int, data text) WITH (algorithm = 'zstd')" ); $node->safe_psql('postgres', "INSERT INTO recov_jrn SELECT g, repeat('x', 200) " . "FROM generate_series(1, 50) g"); # Resolve the sidecar path while the server is up. my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('recov_jrn')"); my $cfsjrn = "$dd/$path.cfsjrn"; ok(-f $cfsjrn, '.cfsjrn sidecar exists for the CFS table'); # Crash before any checkpoint truncates the journal. $node->stop('immediate'); # Arm the injection for the recovery scan and start. The start # itself is expected to die: the re-armed fault also fails the # end-of-recovery checkpoint (PANIC), so only tolerate the failure # here — the assertions below read the log either way. $node->append_conf('postgresql.conf', 'cfs_debug_fail_truncate = 1'); $node->start(fail_ok => 1); # The scan's own truncate failure must be a WARNING that recovery # runs past: the end-of-recovery checkpoint only starts afterwards, # and any PANIC about the truncation must belong to that checkpoint, # never to the scan. my $log = $node->log_content(); like( $log, qr/WARNING: CFS: could not truncate journal.*checkpoint starting: end-of-recovery.*PANIC: CFS: could not truncate journal/s, 'recovery scan tolerates its truncate failure; only the end-of-recovery checkpoint escalates' ); # The postmaster may be gone after the checkpoint PANIC; stop() # tolerates the already-gone PID. $node->stop('immediate', fail_ok => 1); # The failure is gone on the next boot: the journal still holds its # records (only the truncation failed), so the recovery scan repeats # the replay, snapshot and truncation for real. my $conf = $node->data_dir . '/postgresql.conf'; my $conf_text = PostgreSQL::Test::Utils::slurp_file($conf); $conf_text =~ s/^cfs_debug_fail_truncate = 1$//m; open my $cfh, '>', $conf or die "open $conf: $!"; print $cfh $conf_text; close $cfh; ok($node->start, 'server starts once the injected truncate failure is cleared'); ok(-s $cfsjrn < 1024, '.cfsjrn is truncated back to its bare header after recovery'); is($node->safe_psql('postgres', 'SELECT count(*) FROM recov_jrn'), '50', 'CFS table survives the crash intact'); }; # --------------------------------------------------------------------------- # Checkpoint persists map snapshots only for dirty CFS relations # # A checkpoint must persist .cfsmap snapshots only for the CFS relations # written since the last checkpoint (dirty_checkpoint), not for every # occupied metadata slot: an idle relation already has a durable snapshot # from the checkpoint that last wrote it, and re-fsync'ing its sidecars # would be wasted work. # # The checkpointer logs "CFS: checkpoint persisted N relation map # snapshot(s)" at DEBUG1, so the test counts real work by reading the # server log. Both tables are written once before the baseline # checkpoint, so both occupy a metadata slot; afterwards only one of # them is written, and a checkpoint must report exactly 1 snapshot, # while a checkpoint with no intervening writes must report nothing. # --------------------------------------------------------------------------- subtest 'checkpoint persists map snapshots only for dirty CFS relations' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_ckpt_dirty_only'); $node->init; # Keep background checkpoints out of the way; the test drives its own. $node->append_conf('postgresql.conf', "log_min_messages = debug1\n" . "checkpoint_timeout = 30min\n" . "max_wal_size = 1GB\n" . "autovacuum = off\n"); $node->start; if (!codec_built($node, 'zstd')) { plan skip_all => 'zstd support not built, skipping CFS checkpoint dirty-filter test'; } # Two CFS tables, int-only so no toast relations muddle the count. One # row each, so that both occupy a metadata slot with a live policy. $node->safe_psql('postgres', "CREATE TABLE cfs_written (id int) WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "CREATE TABLE cfs_idle (id int) WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "INSERT INTO cfs_written VALUES (1)"); $node->safe_psql('postgres', "INSERT INTO cfs_idle VALUES (1)"); # Baseline checkpoint: both relations are snapshotted and both slots are # clean afterwards. $node->safe_psql('postgres', "CHECKPOINT"); my $offset = -s $node->logfile; # Write to one table only; the checkpoint must persist exactly one map # snapshot; the idle table is not re-snapshotted. $node->safe_psql('postgres', "INSERT INTO cfs_written SELECT g FROM generate_series(2, 100) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $offset); like( $log, qr/CFS: checkpoint persisted 1 relation map snapshot/, 'checkpoint after writing one of two CFS tables persists 1 snapshot'); unlike( $log, qr/CFS: checkpoint persisted [02-9]\d* relation map snapshot/, 'idle CFS table is not re-snapshotted'); # No writes at all since the previous checkpoint: no snapshots at all # (the message is emitted only when at least one relation is processed). $offset = -s $node->logfile; $node->safe_psql('postgres', "CHECKPOINT"); $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $offset); unlike( $log, qr/CFS: checkpoint persisted/, 'checkpoint without intervening writes persists nothing'); # The other table is still picked up once it is written. $offset = -s $node->logfile; $node->safe_psql('postgres', "INSERT INTO cfs_idle SELECT g FROM generate_series(2, 100) g"); $node->safe_psql('postgres', "CHECKPOINT"); $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $offset); like( $log, qr/CFS: checkpoint persisted 1 relation map snapshot/, 'previously idle table is snapshotted after a new write'); unlike( $log, qr/CFS: checkpoint persisted [02-9]\d* relation map snapshot/, 'the table not written since the last checkpoint stays untouched'); }; # --------------------------------------------------------------------------- # Corruption surfaced through the AIO read_stream path. # # CFS readv is completed inline: the blocks are decompressed in the # originating backend and the IO result carries either the block count or a # negative failure code, which the completion callback turns into # PGAIO_RS_ERROR and the report callback raises as the query's ERROR. A # read failure must therefore reach a read_stream consumer exactly like a # synchronous one — same ERROR text (the centralised corruption handler, # so the cfs_checksum_failure GUC keeps its meaning), a live session # afterwards, and a reproducible error on retry (the IO accounting is not # stuck after the failure). # # Note: no deterministic RED is possible for the delivery contract itself # (the pre-fix code failed with the same message); this section pins the # contract: error text, session survival and repeatable failure. # --------------------------------------------------------------------------- subtest 'corrupted page delivered through read_stream raises a clean ERROR' => sub { # A tiny shared_buffers so a seq scan of a few MB goes past the buffer # cache and is served through read_stream / startreadv. my $node = PostgreSQL::Test::Cluster->new('cfs_rs_corrupt'); $node->init; $node->append_conf('postgresql.conf', "shared_buffers = 1MB\ncheckpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS read_stream corruption test'; } # A CFS table well past shared_buffers so a seq scan streams reads. $node->safe_psql('postgres', "CREATE TABLE rs_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO rs_t SELECT g, repeat('rs' || g, 300) " . "FROM generate_series(1, 1000) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('rs_t')"); my $cfp = "$dd/$path.cfp"; ok(-f $cfp, '.cfp sidecar exists for the streaming table'); $node->stop('fast'); # Flip one byte deep in the payload region (same technique as the # checksum-panic section above: parses, but fails the post- # decompression CRC). { open my $fh, '+<:raw', $cfp or die "open $cfp: $!"; seek($fh, 200, 0) or die "seek: $!"; my $b; read($fh, $b, 1); seek($fh, 200, 0); print $fh chr(ord($b) ^ 0xFF); close($fh); } pass('flipped one payload byte in the .cfp'); $node->start; # One long-lived session: the first scan fails, the session survives # and a retry fails identically. ON_ERROR_STOP is off so psql keeps # serving after the expected ERRORs. my $bp = $node->background_psql( 'postgres', timeout => 60, on_error_stop => 0); $bp->query_until(qr/FIRST_DONE/, "\\echo FIRST_MARKER\nSELECT count(*) FROM rs_t; \\echo FIRST_DONE\n" ); # The ERROR is raised through the centralised corruption path, keeping # the cfs_checksum_failure GUC semantics and the usual message text. my $log1 = $node->log_content; like( $log1, qr/ERROR:.*CFS: checksum or format corruption in relation/, 'first streaming scan failed with the corruption ERROR'); # The session is alive after the failed IO... $bp->query_until(qr/ALIVE/, "SELECT 'session-alive'; \\echo ALIVE\n"); # ...and a retry reproduces the failure (IO accounting not stuck). $bp->query_until(qr/SECOND_DONE/, "SELECT count(*) FROM rs_t; \\echo SECOND_DONE\n"); my $log2 = $node->log_content; my $corruption_count = () = $log2 =~ /CFS: checksum or format corruption/g; is($corruption_count, 2, 'retried streaming scan reproduces the corruption ERROR'); $bp->quit; # The server itself stays up. is($node->safe_psql('postgres', "SELECT 1"), 1, 'server stays up after the streamed corruption ERROR'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Structural map corruption hit during an AIO read is caught and delivered # through the normal AIO failure path. # # With the shared map pool off (cfs_map_memory = 0) every persistent smgr # handle owns a private map. A long-lived reader therefore keeps a loaded # map; another backend writes, a CHECKPOINT rewrites the snapshot and resets # the journal, the .cfsmap prologue is corrupted out of band, and the next # streaming read has to reload the stale map inside cfs_smgr_startreadv(). # There cfs_read_blocks_status() raises, and the catch must convert the ERROR # into the inline AIO failure code, complete the handle exactly once, and let # the consumer re-report it through cfs_report_corruption() - no crash, no # leaked append lock, no lost session. # --------------------------------------------------------------------------- subtest 'corrupt map prologue is caught inside an AIO read' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_aio_map_corrupt'); $node->init; $node->append_conf('postgresql.conf', "shared_buffers = 1MB\n" . "cfs_map_memory = 0\n" . "checkpoint_timeout = 30min\n" . "log_min_messages = debug1\n"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS AIO map-refresh test'; } # A table well past the 1MB buffer cache, snapshotted by CHECKPOINT so # the .cfsmap has a prologue to corrupt. $node->safe_psql('postgres', "CREATE TABLE aio_map_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO aio_map_t SELECT g, repeat('am' || g, 300) " . "FROM generate_series(1, 1000) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $data_dir = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('aio_map_t')"); my $cfsmap = "$data_dir/$rel_path.cfsmap"; ok(-f $cfsmap, '.cfsmap sidecar exists for the AIO table'); $node->safe_psql('postgres', "VACUUM aio_map_t"); $node->safe_psql('postgres', "CHECKPOINT"); my $vm_before = $node->safe_psql('postgres', "SELECT pg_relation_size('aio_map_t', 'vm')"); diag("VM before reader: $vm_before"); # Long-lived reader: the scan opens the persistent full-map handle and # evicts most pages from the tiny cache. Parallel workers are off so # the handle under test belongs to this session. my $reader = $node->background_psql( 'postgres', timeout => 60, on_error_stop => 0); my $first = $reader->query_until(qr/FIRST_DONE/, "SET max_parallel_workers_per_gather = 0;\n" . "SELECT count(*) FROM aio_map_t; \\echo FIRST_DONE\n"); unlike($first, qr/ERROR:/, 'initial streaming read succeeds'); # A second backend writes to the table, so the next CHECKPOINT has a # dirty relation to fold: it rewrites the .cfsmap snapshot and resets the # journal, bumping the incarnation. The reader's map is then stale by # incarnation, which is what forces a full reload (a mere journal append # would take the delta-replay path and never read the prologue). my $writer = $node->background_psql( 'postgres', timeout => 60, on_error_stop => 0); my $ins = $writer->query_until(qr/INS_DONE/, "INSERT INTO aio_map_t " . "SELECT g, repeat('b' || g, 300) FROM generate_series(1001, 1100) g; " . "\\echo INS_DONE\n"); unlike($ins, qr/ERROR:/, 'journal append before corruption succeeds'); my $vm_after = $node->safe_psql('postgres', "SELECT pg_relation_size('aio_map_t', 'vm')"); diag("VM after writer: $vm_after"); cmp_ok($vm_before, '>', 0, 'VM precreated before opening reader'); is($vm_after, $vm_before, 'writer did not extend VM'); $node->safe_psql('postgres', "CHECKPOINT"); # Zero the 4-byte map magic of the freshly written snapshot, as in the # fatal-header test above. { open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh "\x00\x00\x00\x00"; close($fh); } pass('zeroed the .cfsmap prologue magic'); my $failed_off = -s $node->logfile; $reader->query_until(qr/READ_DONE/, "SELECT count(*) FROM aio_map_t; \\echo READ_DONE\n"); # psql sends the ERROR to stderr, so assert on the server log: the AIO # consumer reports the converted failure through cfs_report_corruption(). $node->log_check( 'streaming read fails through the AIO report', $failed_off, log_like => [qr/ERROR:.*CFS: checksum or format corruption in relation/]); # The DEBUG1 line proves the ERROR was raised inside the synchronous # read and converted by the catch, not raised directly by the loader. $node->log_check( 'caught prologue ERROR is logged at DEBUG1', $failed_off, log_like => [qr/synchronous AIO read failed:.*checksum or format corruption/]); # The session survives the converted failure. my $alive = $reader->query_until(qr/ALIVE/, "SELECT 'session-alive'; \\echo ALIVE\n"); like($alive, qr/session-alive/, 'reader session survives the failure'); # A retry takes the same path instead of hanging on a leaked append lock. my $retry_off = -s $node->logfile; $reader->query_until(qr/RETRY_DONE/, "SELECT count(*) FROM aio_map_t; \\echo RETRY_DONE\n"); $node->log_check( 'retry reports the corruption again', $retry_off, log_like => [qr/ERROR:.*CFS: checksum or format corruption in relation/]); $node->log_check('retry also went through the caught AIO ERROR path', $retry_off, log_like => [qr/synchronous AIO read failed/]); $reader->quit; $writer->quit; is($node->safe_psql('postgres', "SELECT 1"), 1, 'server stays up after the AIO map-refresh failure'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Structural map corruption caught in the pool-miss path. # # With a one-segment pool, streaming a second relation evicts the first # relation's segment. Corrupting the first relation's .cfsmap prologue and # reading it again forces cfs_shared_map_ensure() to load the segment inside # the shared append-lock window; the loader raises, and the catch must # release the append lock before rethrowing into cfs_smgr_startreadv(), which # converts the error into the normal AIO failure. A leaked lock would make # the retry hang. # --------------------------------------------------------------------------- subtest 'corrupt map prologue is caught on a pool miss' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_aio_pool_miss'); $node->init; $node->append_conf('postgresql.conf', "shared_buffers = 1MB\n" . "cfs_map_memory = 1\n" . "checkpoint_timeout = 30min\n" . "log_min_messages = debug1\n"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS pool-miss corruption test'; } $node->safe_psql('postgres', "CREATE TABLE pool_miss_a (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "CREATE TABLE pool_miss_b (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO pool_miss_a SELECT g, repeat('pa' || g, 300) " . "FROM generate_series(1, 1000) g"); $node->safe_psql('postgres', "INSERT INTO pool_miss_b SELECT g, repeat('pb' || g, 300) " . "FROM generate_series(1, 1000) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $data_dir = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('pool_miss_a')"); my $cfsmap = "$data_dir/$rel_path.cfsmap"; ok(-f $cfsmap, '.cfsmap sidecar exists for the pool-miss table'); # The tiny pool has one segment: scanning B evicts A's segment. my $reader = $node->background_psql( 'postgres', timeout => 60, on_error_stop => 0); my $first = $reader->query_until(qr/A_DONE/, "SET max_parallel_workers_per_gather = 0;\n" . "SELECT count(*) FROM pool_miss_a; \\echo A_DONE\n"); unlike($first, qr/ERROR:/, 'first relation read succeeds'); my $second = $reader->query_until(qr/B_DONE/, "SELECT count(*) FROM pool_miss_b; \\echo B_DONE\n"); unlike($second, qr/ERROR:/, 'second relation evicts the first segment'); { open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh "\x00\x00\x00\x00"; close($fh); } pass('zeroed the .cfsmap prologue magic'); my $failed_off = -s $node->logfile; $reader->query_until(qr/READ_DONE/, "SELECT count(*) FROM pool_miss_a; \\echo READ_DONE\n"); $node->log_check( 'pool-miss read fails through the AIO report', $failed_off, log_like => [qr/ERROR:.*CFS: checksum or format corruption in relation/]); $node->log_check( 'caught pool-miss ERROR is logged at DEBUG1', $failed_off, log_like => [qr/synchronous AIO read failed:.*checksum or format corruption/]); # The append lock was released: this retry would hang on a leaked lock. my $retry_off = -s $node->logfile; $reader->query_until(qr/RETRY_DONE/, "SELECT count(*) FROM pool_miss_a; \\echo RETRY_DONE\n"); $node->log_check( 'retry reports the pool-miss corruption again', $retry_off, log_like => [qr/ERROR:.*CFS: checksum or format corruption in relation/]); $reader->quit; is($node->safe_psql('postgres', "SELECT 1"), 1, 'server stays up after the pool-miss failure'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Corrupt .cfsmap header is fatal regardless of cfs_recovery_strict # # The .cfsmap header is a synchronisation point: the data of every block # below the last checkpoint lives only in the .cfp + .cfsmap pair, WAL does # not cover it. A corrupt header must therefore be a hard error in every # mode — substituting an empty map (the old non-strict behaviour) and # replaying the journal on top of it would silently lose all # pre-checkpoint blocks and then overwrite the snapshot, destroying the # evidence, exactly like vanilla PostgreSQL treats an invalid WAL record # as FATAL in every mode. # # The table is written past a checkpoint before an immediate stop, so the # journal holds records: the startup scan has to open the sidecars and # thus trips over the corrupt header regardless of the journal size. # --------------------------------------------------------------------------- subtest 'corrupt .cfsmap header is fatal regardless of strict' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_map_hdr'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS map-header corruption test'; } # Fill the snapshot via CHECKPOINT, then write past it so the journal # holds records at the stop (the immediate stop takes no checkpoint). $node->safe_psql('postgres', "CREATE TABLE map_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO map_t SELECT g, repeat('m' || g, 80) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "INSERT INTO map_t SELECT g, repeat('m' || g, 80) " . "FROM generate_series(501, 600) g"); my $data_dir = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('map_t')"); my $cfsmap = "$data_dir/$rel_path.cfsmap"; ok(-f $cfsmap, '.cfsmap sidecar exists for the CFS table'); # Crash (no shutdown checkpoint: the journal keeps its records). $node->stop('immediate'); # Zero the 4-byte map magic at offset 0 so the header validation fails # on bad magic. Overwriting (not XOR) keeps the helper idempotent. { open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh "\x00\x00\x00\x00"; close($fh); } pass('zeroed the .cfsmap header magic'); # Remember the exact bytes of the whole triple: the failed startup must # leave it untouched (no snapshot rewrite, no journal truncation), so # the corruption stays diagnosable on disk. my $cfsjrn = "$data_dir/$rel_path.cfsjrn"; my $cfp = "$data_dir/$rel_path.cfp"; my $cfsmap_before = PostgreSQL::Test::Utils::slurp_file($cfsmap); my $cfsjrn_before = PostgreSQL::Test::Utils::slurp_file($cfsjrn); my $cfp_before = PostgreSQL::Test::Utils::slurp_file($cfp); # strict = off is the default, but pin it so the assertion cannot ride # on a future default change (the GUC is PGC_POSTMASTER). $node->append_conf('postgresql.conf', "cfs_recovery_strict = off"); # The server must refuse to start: the corrupt map header is a hard # error in every mode. my $log_off = -s $node->logfile; my $started = $node->start(fail_ok => 1); ok(!$started, 'server does NOT start with a corrupt .cfsmap header (strict=off)'); my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT 1"); isnt($ret, 0, 'connection rejected after the corrupt .cfsmap header'); $node->log_check('corrupt map header is reported', $log_off, log_like => [qr/corrupt page map snapshot/i]); # The failed startup rewrote nothing: the corrupt header is still on # disk byte for byte, and no half-written snapshot temp file remains. is(PostgreSQL::Test::Utils::slurp_file($cfsmap), $cfsmap_before, '.cfsmap is left untouched by the failed startup'); is(PostgreSQL::Test::Utils::slurp_file($cfsjrn), $cfsjrn_before, '.cfsjrn is left untouched by the failed startup'); is(PostgreSQL::Test::Utils::slurp_file($cfp), $cfp_before, '.cfp is left untouched by the failed startup'); ok(!-f "$cfsmap.tmp", 'no leftover .cfsmap.tmp from a snapshot rewrite'); }; # --------------------------------------------------------------------------- # Corrupt sidecar headers are fatal even with an empty journal # # The startup scan skips relations whose journal holds only its 16-byte # header (the clean post-checkpoint state), so their sidecars are not # opened and the headers are not validated on the normal open path. A # corrupt .cfsmap/.cfsjrn header must still abort the startup scan: # otherwise the "fatal in every mode" contract only holds for relations # with un-checkpointed journal records, and the corruption of a clean # relation surfaces at the first backend access (or never) instead of at # startup. # # The corruption zeroes the 4-byte header magic at offset 0 of one # sidecar at a time; the bytes are restored between scenarios so a # single node covers both files and a final healthy start. # --------------------------------------------------------------------------- subtest 'corrupt sidecar headers are fatal even with an empty journal' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_empty_jrn_hdr'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS empty-journal header corruption test'; } # Two CFS tables with a saved snapshot and an EMPTY journal: the # CHECKPOINT flushes the map snapshots and truncates the journals to # their bare headers, and nothing is written past it (the immediate # stop takes no checkpoint). $node->safe_psql('postgres', "CREATE TABLE map_empty_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO map_empty_t SELECT g, repeat('p' || g, 80) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CREATE TABLE jrn_empty_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO jrn_empty_t SELECT g, repeat('q' || g, 80) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $data_dir = $node->data_dir; my $map_rel = $node->safe_psql('postgres', "SELECT pg_relation_filepath('map_empty_t')"); my $jrn_rel = $node->safe_psql('postgres', "SELECT pg_relation_filepath('jrn_empty_t')"); my $map = "$data_dir/$map_rel.cfsmap"; my $jrn = "$data_dir/$jrn_rel.cfsjrn"; ok(-f $map, '.cfsmap sidecar exists for the first CFS table'); ok(-f $jrn, '.cfsjrn sidecar exists for the second CFS table'); # Crash with the journals holding only their headers. $node->stop('immediate'); cmp_ok(-s $map, '>', 24, 'map snapshot is non-empty'); cmp_ok(-s $jrn, '<=', 16, 'journal holds only its header'); # strict = off is the default, but pin it (the GUC is PGC_POSTMASTER): # the header check must not depend on it. $node->append_conf('postgresql.conf', "cfs_recovery_strict = off"); # Scenario A: a corrupt .cfsmap header must abort the startup. my $map_before = PostgreSQL::Test::Utils::slurp_file($map); { open my $fh, '+<:raw', $map or die "open $map: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh "\x00\x00\x00\x00"; close($fh); } pass('zeroed the .cfsmap header magic'); my $log_off = -s $node->logfile; my $started = $node->start(fail_ok => 1); ok(!$started, 'server does NOT start with a corrupt .cfsmap header and empty journal' ); $node->log_check('corrupt map header is reported at startup', $log_off, log_like => [qr/corrupt page map snapshot/i]); # Scenario B: restore the map, corrupt the .cfsjrn header instead. my $jrn_before = PostgreSQL::Test::Utils::slurp_file($jrn); { open my $fh, '+<:raw', $map or die "open $map: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh substr($map_before, 0, 4); close($fh); } { open my $fh, '+<:raw', $jrn or die "open $jrn: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh "\x00\x00\x00\x00"; close($fh); } pass('restored the .cfsmap magic and zeroed the .cfsjrn magic'); $log_off = -s $node->logfile; $started = $node->start(fail_ok => 1); ok(!$started, 'server does NOT start with a corrupt .cfsjrn header and empty journal' ); $node->log_check('corrupt journal header is reported at startup', $log_off, log_like => [qr/corrupt page map journal/i]); # Healthy headers must not trip the check: the same node starts. { open my $fh, '+<:raw', $jrn or die "open $jrn: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh substr($jrn_before, 0, 4); close($fh); } pass('restored the .cfsjrn magic'); $started = $node->start(); ok($started, 'server starts with valid headers and empty journals'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Orphan sidecar set left by an interrupted drop # # Removing a CFS relation's sidecars at commit time (DROP / VACUUM FULL / # REINDEX) walks .cfp -> .cfsmap -> .cfsjrn; a crash inside that window # leaves a partial set on disk. The startup scan must treat a partial set # as an orphan of a *committed* drop: log a WARNING naming what was found, # remove the leftovers and continue — a leftover from a legal crash must # never abort startup (mirrors RemovePgTempFiles and vanilla's idempotent # redo-unlink, which tolerate ENOENT instead of failing). # # The emulation removes only the .cfp while the server is down, which is # byte-for-byte the state a crash between the first and second unlink # produces. # --------------------------------------------------------------------------- subtest 'orphan sidecar set left by an interrupted drop' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_orphan'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS orphan sidecar set test'; } $node->safe_psql('postgres', "CREATE TABLE orph_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO orph_t SELECT g, repeat('o' || g, 80) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('orph_t')"); my $cfp = "$dd/$path.cfp"; my $cfsmap = "$dd/$path.cfsmap"; my $cfsjrn = "$dd/$path.cfsjrn"; ok( -f $cfp && -f $cfsmap && -f $cfsjrn, 'full sidecar set exists for the CFS table'); $node->stop('fast'); # Emulate the crash-inside-the-drop-window state: .cfp already gone, # .cfsmap and .cfsjrn still present. unlink($cfp); ok( !-f $cfp && -f $cfsmap && -f $cfsjrn, 'partial sidecar set in place (.cfp removed)'); my $log_off = -s $node->logfile; my $started = $node->start(fail_ok => 1); ok($started, 'server starts over an orphan sidecar set'); $node->log_check('orphan set warning', $log_off, log_like => [qr/incomplete sidecar set/i]); # The leftovers are gone: the set was removed completely. ok( !-f $cfp && !-f $cfsmap && !-f $cfsjrn, 'orphaned sidecar files are removed by recovery'); is($node->safe_psql('postgres', "SELECT 1"), 1, 'server fully operational after the orphan cleanup'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # cfs_recovery_strict escalates journal record corruption # # The GUC promises that torn or skipped journal records are fatal in strict # mode. Two corruptions exercise the two record-level cases: # # * skip: every journal UPDATE references .cfp data past a truncation, so # replay skips the records (the referenced data is missing). Strict # must abort startup through the centralised corruption handler; # non-strict must start and log the skip WARNING. # # * torn mid-file: one flipped byte in the middle of the journal body # breaks a record's CRC while more records follow it — unlike a torn # TAIL (the normal crash artifact, covered by the crash tests), data # exists past the damage. Strict must abort startup; non-strict must # start and log the torn-record WARNING. # # The data itself is not asserted afterwards: the .cfp truncation of the # skip scenario deliberately damages pre-checkpoint records, so only the # startup behaviour and the log are pinned here. # --------------------------------------------------------------------------- subtest 'cfs_recovery_strict escalates journal record corruption' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_strict_records'); $node->init; # A tiny shared_buffers forces page evictions during the second # INSERT, so the journal holds real UPDATE records (a page that only # lives in the buffer cache dies with the crash and never reaches the # journal — the RESIZE-only case skips nothing). $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nshared_buffers = 128kB"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS strict journal records test'; } # --- skip scenario: journal records without durable .cfp data --------- $node->safe_psql('postgres', "CREATE TABLE skip_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO skip_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "INSERT INTO skip_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 700) g"); my $dd = $node->data_dir; my $skip_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('skip_t')"); my $skip_cfp = "$dd/$skip_path.cfp"; my $skip_jrn = "$dd/$skip_path.cfsjrn"; ok(-s $skip_cfp > 65536, '.cfp is large enough for the truncation'); $node->stop('immediate'); ok(-s $skip_jrn > 512, 'journal holds UPDATE records from the evicted pages'); # Truncate the .cfp to its bare lead-in (8 bytes): every journal UPDATE # now points past EOF, so replay must skip each one. { open my $fh, '+<:raw', $skip_cfp or die "open $skip_cfp: $!"; truncate($fh, 8) or die "truncate $skip_cfp: $!"; close($fh); } pass('truncated the .cfp below every journal-referenced offset'); # Direction 1: strict = on must abort startup. $node->append_conf('postgresql.conf', "cfs_recovery_strict = on"); my $log_off = -s $node->logfile; my $started = $node->start(fail_ok => 1); ok(!$started, 'strict=on: skipped journal record aborts startup'); $node->log_check('strict=on skip escalation message', $log_off, log_like => [qr/checksum or format corruption/i]); # Direction 2: strict = off starts and logs the skip WARNING. $node->append_conf('postgresql.conf', "cfs_recovery_strict = off"); $log_off = -s $node->logfile; $started = $node->start(fail_ok => 1); ok($started, 'strict=off: server starts over skipped journal records'); $node->log_check('strict=off skip warning', $log_off, log_like => [qr/skipping journal UPDATE for block/i]); $node->stop('fast'); # --- torn mid-file scenario ------------------------------------------- $node->start; $node->safe_psql('postgres', "CREATE TABLE torn_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO torn_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "INSERT INTO torn_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 700) g"); my $torn_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('torn_t')"); my $torn_jrn = "$dd/$torn_path.cfsjrn"; $node->stop('immediate'); ok(-s $torn_jrn > 4096, 'journal holds many records'); # Flip one byte in the middle of the journal body: the record covering # that offset fails its CRC while later records still follow it. { my $pos = 16 + int(((-s $torn_jrn) - 16) / 2); open my $fh, '+<:raw', $torn_jrn or die "open $torn_jrn: $!"; seek($fh, $pos, 0) or die "seek: $!"; my $b; read($fh, $b, 1); seek($fh, $pos, 0); print $fh chr(ord($b) ^ 0xFF); close($fh); } pass('flipped one byte in the middle of the journal body'); # Direction 1: strict = on must abort startup. $node->append_conf('postgresql.conf', "cfs_recovery_strict = on"); $log_off = -s $node->logfile; $started = $node->start(fail_ok => 1); ok(!$started, 'strict=on: mid-journal torn record aborts startup'); $node->log_check('strict=on torn escalation message', $log_off, log_like => [qr/checksum or format corruption/i]); # Direction 2: strict = off starts and logs the torn WARNING. $node->append_conf('postgresql.conf', "cfs_recovery_strict = off"); $log_off = -s $node->logfile; $started = $node->start(fail_ok => 1); ok($started, 'strict=off: server starts over a mid-journal torn record'); $node->log_check('strict=off torn warning', $log_off, log_like => [qr/torn record/i]); $node->stop('fast'); }; # Flip one byte inside the payload of the journal record starting at $pos. # The byte sits after the record's magic/op/blocknum and inside the CRC # coverage, so the record parses but its entry_crc no longer matches. sub flip_journal_byte { my ($jrn, $pos) = @_; open my $fh, '+<:raw', $jrn or die "open $jrn: $!"; seek($fh, $pos, 0) or die "seek: $!"; my $b; read($fh, $b, 1); seek($fh, $pos, 0) or die "seek: $!"; print $fh chr(ord($b) ^ 0xFF); close($fh); } # --------------------------------------------------------------------------- # Mid-journal corruption aborts the checkpoint and preserves the tail # # A record that cannot be interpreted while valid records still follow it # cannot come from a legal append (appends only ever happen at EOF), so it is # corruption, not a crash artifact. The records behind it are the only # durable trace of their changes: folding the journal up to the damage and # resetting would drop them for good. The checkpoint must abort instead and # leave the journal untouched, so a later checkpoint (after the damage is # repaired) folds the whole valid journal. The error is raised in the # checkpointer, so it is asserted through the server log. # --------------------------------------------------------------------------- subtest 'mid-journal corruption aborts the checkpoint and keeps the tail' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_mid_journal'); $node->init; # Tiny shared_buffers force page evictions, so the journal holds real # UPDATE records (the same trick as the strict subtest above). No shared # map pool: every process owns a full map. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nshared_buffers = 128kB\n" . "autovacuum = off\ncfs_map_memory = 0"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built'; } $node->safe_psql('postgres', "CREATE TABLE mid_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO mid_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "INSERT INTO mid_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(501, 1200) g"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('mid_t')"); my $jrn = "$dd/$path.cfsjrn"; my $jrn_before = -s $jrn; ok($jrn_before > 512, 'the journal holds records to corrupt'); # Corrupt the FIRST record (journal header 16 bytes + 16 into the # 48-byte entry): valid records still follow it, so the stop is mid-file. flip_journal_byte($jrn, 16 + 16); # CHECKPOINT itself only reports "checkpoint request failed" to the # client; the ERROR that matters is emitted by the checkpointer. my $log_off = -s $node->logfile; $node->psql('postgres', 'CHECKPOINT'); $node->wait_for_log(qr/middle of .*\.cfsjrn/, $log_off); pass('the checkpoint aborts on mid-journal corruption'); is(-s $jrn, $jrn_before, 'the journal is not reset: the valid tail survives'); # The tail must survive a restart too: startup recovery used to truncate # the journal at the first torn record. Crash-restart before the repair # so the recovery scan sees the same mid-file stop. WAL redo re-writes # the pages lost from shared_buffers and appends their journal records at # EOF, so the journal may grow; what matters is that recovery did not cut # it back to the torn offset (a truncation would leave 16 bytes). $node->stop('immediate'); $node->start; cmp_ok(-s $jrn, '>=', $jrn_before, 'recovery does not truncate the journal at a mid-file torn record'); # Repair the byte: nothing else touched the journal, so the next # checkpoint must fold every record and reset the journal. flip_journal_byte($jrn, 16 + 16); $node->safe_psql('postgres', 'CHECKPOINT'); is(-s $jrn, 16, 'the repaired journal is folded and reset'); is($node->safe_psql('postgres', 'SELECT count(*) FROM mid_t'), '1200', 'no row is lost'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A torn journal TAIL is still tolerated # # The last record of the file being uninterpretable is the normal artifact # of a crash in the middle of an append: nothing follows it, so no valid # record is at risk. The checkpoint folds the records before it, drops the # torn one with the journal reset and succeeds. # --------------------------------------------------------------------------- subtest 'torn journal tail does not abort the checkpoint' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_torn_tail'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nshared_buffers = 128kB\n" . "autovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built'; } $node->safe_psql('postgres', "CREATE TABLE tail_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO tail_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "INSERT INTO tail_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(501, 700) g"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('tail_t')"); my $jrn = "$dd/$path.cfsjrn"; my $jrn_before = -s $jrn; ok($jrn_before > 512, 'journal holds UPDATE records from the evicted pages'); # The last record starts at (size - 48); corrupt a byte of its payload. flip_journal_byte($jrn, $jrn_before - 48 + 16); # A torn tail must not fail the checkpoint: safe_psql dies otherwise. $node->safe_psql('postgres', 'CHECKPOINT'); is(-s $jrn, 16, 'the torn tail is dropped with the journal reset'); my $count = $node->safe_psql('postgres', 'SELECT count(*) FROM tail_t'); cmp_ok($count, '>=', 500, 'the relation is readable after the drop'); is($node->safe_psql('postgres', 'SELECT count(*) FROM tail_t'), $count, 'the row set is stable across reads'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Recovery opens a relation's sidecars only when its journal holds records # # The startup scan walks the names on every start, but loading a map is # real work; after a clean shutdown every journal is truncated to its bare # header by the last checkpoint, so the scan must load no maps at all # (only the sidecar headers are read for validation). # After a crash with journal records pending, the relation is opened and # the counter in the completion LOG reflects it. # --------------------------------------------------------------------------- subtest 'recovery opens sidecars only for non-empty journals' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_empty_jrn'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS empty-journal scan test'; } $node->safe_psql('postgres', "CREATE TABLE gate_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO gate_t SELECT g, repeat('g' || g, 80) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CHECKPOINT"); # Clean restart: the checkpoint truncated the journal, so the scan # must load no relation map at all (only the headers are read). $node->stop('fast'); my $log_off = -s $node->logfile; $node->start; $node->log_check('clean restart opens no journals', $log_off, log_like => [qr/journals opened 0/]); # Crash with journal records pending (extension RESIZE records reach # the journal even when the pages themselves stay in the buffer # cache): the relation is opened and replayed. $node->safe_psql('postgres', "INSERT INTO gate_t SELECT g, repeat('g' || g, 80) " . "FROM generate_series(201, 400) g"); $node->stop('immediate'); $log_off = -s $node->logfile; $node->start; $node->log_check('crash with pending records opens the journal', $log_off, log_like => [qr/journals opened [1-9]\d*/]); is($node->safe_psql('postgres', "SELECT count(*) FROM gate_t"), '400', 'data is intact after the crash restart'); $node->stop('fast'); }; # The checkpointer's VmRSS, in kB, from /proc. sub vm_rss_kb { my ($pid) = @_; my $status = PostgreSQL::Test::Utils::slurp_file("/proc/$pid/status"); die "no VmRSS in /proc/$pid/status" unless $status =~ /^VmRSS:\s+(\d+) kB$/m; return int($1); } # --------------------------------------------------------------------------- # The checkpoint's journal fold does not leak its reader buffer # # cfs_journal_fold() runs in the checkpointer - a long-lived process that # holds no per-relation memory context a reset would reclaim - so every # allocation the fold leaves behind accumulates across checkpoints. Its # chunked journal reader holds a 256 KiB buffer; a missing release leaks # one per folded relation per checkpoint. The checkpointer's VmRSS must # stay flat across a series of forced checkpoints, each folding at least # one journal record. # --------------------------------------------------------------------------- subtest 'checkpointer does not leak the journal fold reader' => sub { # The measurement reads /proc; skip on platforms without it. plan skip_all => 'requires procfs (/proc)' unless -r '/proc/self/status'; my $node = PostgreSQL::Test::Cluster->new('cfs_fold_leak'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'zstd')) { plan skip_all => 'zstd support not built, skipping CFS fold leak test'; } $node->safe_psql('postgres', "CREATE TABLE leak_t (id int, data text) WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "INSERT INTO leak_t SELECT g, repeat('x', 200) " . "FROM generate_series(1, 50) g"); # Two warmup checkpoints settle the checkpointer's one-off allocations # before the baseline sample is taken. $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "CHECKPOINT"); my $ckpt_pid = $node->safe_psql('postgres', "SELECT pid FROM pg_stat_activity WHERE backend_type = 'checkpointer'" ); my $before = vm_rss_kb($ckpt_pid); # Sixty dirty checkpoints: each flushes the updated page, appends its # journal record and folds the journal. A per-round leak of 256 KiB # would total ~15 MB, far above the noise margin below. for my $i (1 .. 60) { $node->safe_psql('postgres', "UPDATE leak_t SET data = repeat('y', 200) WHERE id = 1"); $node->safe_psql('postgres', "CHECKPOINT"); } my $after = vm_rss_kb($ckpt_pid); cmp_ok($after - $before, '<', 6144, 'checkpointer RSS stays flat across 60 journal-folding checkpoints'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Unhealed map corruption found by a no-pool backend read is an ERROR, not # a recovery-grade WARNING # # cfs_map_load() used its repair_torn_tail flag as the "am I the recovery # scan" context of cfs_report_corruption(), but non-recovery callers pass # repair=true as well: every full-map refresh under the append lock (the # no-pool read path, nblocks, immedsync). With the pool off, a map row # corrupted on disk after the session's handle was opened produced only a # WARNING when the post-checkpoint journal reset forced the full reload, # and the read went on to serve a zero page for the block; an immedsync # would silently snapshot the INVALID row. The context is a separate flag # now: only the startup recovery scan follows cfs_recovery_strict; every # backend path escalates through cfs_checksum_failure. # # The stale-handle window lives inside one explicit transaction (smgr # handles are released at transaction end), the 6 MB table cannot stay in # the 1 MB buffer cache (so the second scan really reads through smgr), # and the corruption lands after the checkpoint - its own full-handle open # must not see the damaged row. # --------------------------------------------------------------------------- subtest 'no-pool read reports unhealed corruption as an error' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_nopool_corrupt'); $node->init; $node->append_conf('postgresql.conf', "cfs_map_memory = 0\nshared_buffers = 1MB\n" . "checkpoint_timeout = 30min\nautovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS no-pool corruption test'; } # ~763 pages: the INSERT itself flushes pages through the CFS write # path (journal records exist) and no scan can hold the table in the # 1 MB buffer cache. $node->safe_psql('postgres', "CREATE TABLE noc_t (id int, payload text) WITH (algorithm = 'lz4'); " . "INSERT INTO noc_t SELECT g, repeat('n' || g, 300) " . "FROM generate_series(1, 4000) g;"); my $a = $node->background_psql('postgres', timeout => 120); $a->query_until(qr/IN_TX/, "BEGIN;\nSELECT count(*) FROM noc_t;\n\\echo IN_TX\n"); # The checkpoint folds the journal and resets it (incarnation bumped); # its own full-handle open happens before the corruption, so nothing # notices the damaged row yet. $node->safe_psql('postgres', "CHECKPOINT"); # Flip one byte of block 0's row (row 0 starts right after the 8-byte # prologue): the entry CRC no longer matches, the row reads as INVALID. my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('noc_t')"); my $cfsmap = "$dd/$path.cfsmap"; { open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!"; seek($fh, 8, 0) or die "seek: $!"; my $b; read($fh, $b, 1); seek($fh, 8, 0); print $fh chr(ord($b) ^ 0xFF); close($fh); } pass('flipped one byte of block 0 map row'); # The second SELECT of the still-open transaction sees the journal # reset and does a full reload under the append lock (repair=true): # block 0 fails its CRC and the bare journal holds no covering record. # This must be the backend ERROR policy, never the recovery WARNING. my $log_off = -s $node->logfile; $a->query_until(qr/READ_DONE/, "SELECT count(*) FROM noc_t;\nCOMMIT;\n\\echo READ_DONE\n"); $node->log_check( 'no-pool read escalates unhealed corruption', $log_off, log_like => [qr/ERROR: CFS: checksum or format corruption/], log_unlike => [qr/WARNING: CFS: checksum or format corruption/]); $a->quit; $node->stop('fast'); }; # The generation watermark stamped in a .cfsjrn header, from its 16 bytes: # magic u32, version u16, incarnation u16, max_generation u32, crc u32. sub jrn_header_max_gen { my ($path) = @_; my $conf = $Config{byteorder}; my $fmt = ($conf =~ /^(1234|4321)/ || $conf eq '12345678') ? 'L sub { my $node = PostgreSQL::Test::Cluster->new('cfs_wm_delete'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nautovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS watermark test'; } # Small payloads keep every row in the main fork (no TOAST), so the # watermark of 'wm_t' itself covers every generation the scenario # issues: ~25 heap pages, generations 1..N from the insert, more from # the rewrites below. $node->safe_psql('postgres', "CREATE TABLE wm_t (id int, payload text) WITH (algorithm = 'lz4'); " . "INSERT INTO wm_t SELECT g, repeat('w', 400) " . "FROM generate_series(1, 300) g;"); # Set hint bits / the visibility map while the whole relation is still # low-generation, so the later vacuum has nothing left to write on the # surviving pages. $node->safe_psql('postgres', "VACUUM wm_t;"); # Rewrite rounds grow the generations of the upper half well past the # lower half's. $node->safe_psql('postgres', "UPDATE wm_t SET payload = repeat('x', 400) WHERE id > 150;"); $node->safe_psql('postgres', "UPDATE wm_t SET payload = repeat('y', 400) WHERE id > 150;"); $node->safe_psql('postgres', "CHECKPOINT"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('wm_t')"); my $jrn = "$dd/$path.cfsjrn"; my $w1 = jrn_header_max_gen($jrn); cmp_ok($w1, '>', 1, 'the first checkpoint stamps a real watermark'); # Shrink the relation to ZERO valid rows: delete everything and let # VACUUM truncate in place (same relfilenode). The rewrite noise of # the delete/vacuum itself only touches rows that the truncation then # removes, so after it no valid row is left to carry the high # generations - a summary-following-the-map stamp would drop to 0. # (A partial delete does NOT construct that state deterministically: # the vacuum dirties the new boundary page, whose row then re-raises # the summary on its own.) $node->safe_psql('postgres', "DELETE FROM wm_t;"); $node->safe_psql('postgres', "VACUUM wm_t;"); $node->safe_psql('postgres', "CHECKPOINT"); cmp_ok(jrn_header_max_gen($jrn), '>=', $w1, 'the watermark does not regress after the shrink'); # The relation stays fully usable on top of the preserved watermark. $node->safe_psql('postgres', "INSERT INTO wm_t SELECT g, repeat('z', 400) " . "FROM generate_series(1, 10) g;"); is($node->safe_psql('postgres', 'SELECT count(*) FROM wm_t'), '10', 'the relation accepts new rows after the shrink'); $node->safe_psql('postgres', "CHECKPOINT"); cmp_ok(jrn_header_max_gen($jrn), '>=', $w1, 'the watermark still holds after the next checkpoint'); $node->stop('fast'); }; # Flip one byte of a map row, 'field_off' bytes into its 24-byte CfsMapEntry: # the row keeps its non-zero content but fails its entry_crc. The .cfsmap # prologue is 8 bytes; inside the entry physical_offset is at 0, # compressed_size at 8, generation at 12 and entry_crc at 16. The default 0 # damages a role field; 16 damages only the checksum, so the row is corrupt by # its entry_crc alone. sub flip_map_row_byte { my ($cfsmap, $blocknum, $field_off) = @_; my $off = 8 + $blocknum * 24 + ($field_off // 0); open my $fh, '+<:raw', $cfsmap or die "open $cfsmap: $!"; seek($fh, $off, 0) or die "seek: $!"; my $b; read($fh, $b, 1); seek($fh, $off, 0); print $fh chr(ord($b) ^ 0xFF); close($fh); } # --------------------------------------------------------------------------- # A pool-served corrupt map row is an error on EVERY read # # A row whose entry_crc fails and that no journal record covers must never # be served as a zero page. The pool path used to report the corruption # once (through a handler that throws) but left the segment published and # journal-synced: the FIRST reader of the block got an ERROR, every # following one silently read a zeroed page. The segment now stays # unpublished while it holds an unhealed row, so each read re-detects the # corruption and fails again. # --------------------------------------------------------------------------- subtest 'pool read of an unhealed map row is an error, repeatedly' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_pool_corrupt'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nautovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS pool corruption test'; } $node->safe_psql('postgres', "CREATE TABLE pl_t (id int, payload text) WITH (algorithm = 'lz4'); " . "INSERT INTO pl_t SELECT g, repeat('p', 400) " . "FROM generate_series(1, 200) g; " . "VACUUM pl_t;"); $node->safe_psql('postgres', "CHECKPOINT"); # The journal is empty after the checkpoint, so nothing can heal the # corrupted row. Restart so the scan really reads through CFS instead # of the warm shared buffers (the empty journal also means recovery # skips this relation - the corrupt row survives the restart). my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('pl_t')"); flip_map_row_byte("$dd/$path.cfsmap", 0); pass('flipped one byte of the block 0 map row'); $node->restart; # Each read must fail: the entry point raises the checksum-failure # ERROR; a returning count means the block came back as a zero page. for my $round (1, 2) { my ($ret, $stdout, $stderr) = $node->psql('postgres', "SET statement_timeout = '30s'; SELECT count(*) FROM pl_t;"); isnt($ret, 0, "read $round of the corrupted block is an error"); like( $stderr // '', qr/checksum or format corruption/, "read $round reports the corruption"); } $node->stop('fast'); }; # --------------------------------------------------------------------------- # The corruption report never leaks the append lock # # The unhealed-corruption report of the pool path throws (ERROR/PANIC per # cfs_checksum_failure). It used to fire inside the reader's SHARED # append-lock section (the pool ensure/sync of a cache miss): the longjmp # ran past the inline release and left the lock held - every writer of the # relation then waited on it forever. The corruption is now returned to # the smgr entry point as a status code instead, and the ERROR is raised # only after the lock is released, so a writer completes even though the # reading session - which holds no lock anymore - stays connected after # the error. # # The pool is sized to exactly one segment (cfs_map_memory = 1 MB), so # reading the second table evicts the first table's segment and forces the # corrupted reload on the next read. # --------------------------------------------------------------------------- subtest 'segment corruption report does not leak the append lock' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_seg_leak'); $node->init; $node->append_conf('postgresql.conf', "cfs_map_memory = 1\nshared_buffers = 1MB\n" . "checkpoint_timeout = 30min\nautovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS segment leak test'; } # lk_a and lk_b: ~470 blocks each, cannot stay in the 1 MB buffer # cache, so their scans really read through smgr and the pool - and # reading lk_b evicts lk_a's segment from the one-slot pool. The # VACUUMs set every hint/visibility bit BEFORE the checkpoint, so the # later scans write nothing through CFS and cannot heal the corrupted # row from the journal. $node->safe_psql('postgres', "CREATE TABLE lk_a (payload text) WITH (algorithm = 'lz4'); " . "INSERT INTO lk_a SELECT repeat('a' || g, 300) " . "FROM generate_series(1, 3000) g; " . "CREATE TABLE lk_b (payload text) WITH (algorithm = 'lz4'); " . "INSERT INTO lk_b SELECT repeat('b' || g, 300) " . "FROM generate_series(1, 3000) g; " . "VACUUM lk_a; VACUUM lk_b;"); $node->safe_psql('postgres', "CHECKPOINT"); my $dd = $node->data_dir; my $path_a = $node->safe_psql('postgres', "SELECT pg_relation_filepath('lk_a')"); # Load lk_a's segment, then let lk_b's read take the only pool slot. $node->safe_psql('postgres', "SELECT count(*) FROM lk_a"); $node->safe_psql('postgres', "SELECT count(*) FROM lk_b"); # Corrupt lk_a's block 0 row on disk (after the checkpoint, so the # checkpointer's own full-map open never sees it). flip_map_row_byte("$dd/$path_a.cfsmap", 0); # The reading session must SURVIVE its ERROR: a backend that exits # releases its LWLocks, and the leak would be invisible. my $r3 = $node->background_psql( 'postgres', timeout => 120, on_error_stop => 0); my $log_off = -s $node->logfile; $r3->query_until(qr/READ_SENT/, "SELECT count(*) FROM lk_a;\n\\echo READ_SENT\n"); $node->log_check('segment reload reports unhealed corruption', $log_off, log_like => [qr/ERROR: CFS: checksum or format corruption/]); # The session is still alive and holds NO lock: a writer of the same # relation must complete. TRUNCATE is the probe: it takes the CFS # append lock exclusively without reading any heap page (an INSERT # would consult the FSM and could touch the corrupted block for its # own reason). With the leaked lock it waits past the statement # timeout instead. my ($ret, $stdout, $stderr) = $node->psql('postgres', "SET statement_timeout = '3s'; TRUNCATE lk_a;"); is($ret, 0, 'a writer completes while the corrupted reader is alive'); $r3->quit; $node->stop('fast'); }; # --------------------------------------------------------------------------- # Recovery does not launder unhealed corruption # # The startup fold rewrites exactly the rows its journal records name; it # never scans the rest of the map. A corrupt row that no journal record # covers therefore survives the scan byte-identically - nothing replaces # it with a fabricated INVALID - while the covered rows around it are # legitimately folded and the journal is reset. The damage is not # reported by the scan itself anymore (the scan loads no map at startup, # QDB-1515); it surfaces one step later, when WAL redo opens the map for # the first time and fails loudly - the server does not come up until the # relation is repaired, the same fail-loud contract as before. # --------------------------------------------------------------------------- subtest 'recovery does not launder unhealed corruption' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_recov_launder'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nautovacuum = off\n" . "shared_buffers = 1MB"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS recovery launder test'; } # ~470 blocks: bigger than the buffer cache, so the UPDATE below # flushes its pages through CFS and the journal really holds records # when the crash happens. $node->safe_psql('postgres', "CREATE TABLE rc_t (id int, payload text) " . "WITH (algorithm = 'lz4'); " . "INSERT INTO rc_t SELECT g, repeat('r', 400) " . "FROM generate_series(1, 3000) g; VACUUM rc_t;"); $node->safe_psql('postgres', "CHECKPOINT"); # Journal records for the tail blocks only: crash-relevant pages # flushed by a cold full scan; block 0 stays untouched. $node->safe_psql('postgres', "UPDATE rc_t SET payload = repeat('s', 400) WHERE id > 2900;"); $node->safe_psql('postgres', "SELECT count(*) FROM rc_t"); $node->safe_psql('postgres', "SELECT count(*) FROM rc_t"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('rc_t')"); my $jrn = "$dd/$path.cfsjrn"; my $map = "$dd/$path.cfsmap"; cmp_ok(-s $jrn, '>', 16, 'the journal holds flushed records'); # Corrupt block 0's row (flip a byte): non-zero content, bad # entry_crc, and no journal record covers it. flip_map_row_byte($map, 0); $node->stop('immediate'); my $row_before = substr(PostgreSQL::Test::Utils::slurp_file($map), 8, 24); # QDB-1516 made the startup size path lazy (stat(.cfsmap) + journal # RESIZE records, no full map open), and the WAL redo of the flushed # updates does not read block 0, so the unhealed damage no longer # aborts the start: the server comes up, the corrupt row survives # byte-identically, the journal folds, and the damage still refuses # the first read instead of being laundered or served. $node->stop('fast'); ok($node->start, 'server starts with an unhealed corrupt map row'); # THE regression asserts: the corrupt row was not replaced by a # laundered INVALID (the fold rewrites only the rows the journal # names), and the covered rows were folded with the journal reset - # the scan did its full job around the damage. my $row_after = substr(PostgreSQL::Test::Utils::slurp_file($map), 8, 24); is($row_after, $row_before, 'the corrupt map row survived the recovery scan byte-identically'); cmp_ok(-s $jrn, '<=', 16, 'the covered rows were folded and the journal reset'); # The latent damage still surfaces loudly at the first read of the # block: the read refuses to decompress through the corrupted entry. my ($ret2, $stdout2, $stderr2) = $node->psql('postgres', "SELECT count(*) FROM rc_t"); isnt($ret2, 0, 'first read fails on the unhealed corrupt row'); like( $stderr2, qr/checksum or format corruption .* block 0/, 'first-read corruption error names block 0'); }; # --------------------------------------------------------------------------- # The write path accounts no dead space between checkpoints # # dead_bytes is a durable checkpoint stamp: the fold counts superseded # rows, compaction resets the counters, and nothing on the write path # touches them. Between two checkpoints the published value must stay # exactly zero even while the relation is being rewritten. # --------------------------------------------------------------------------- subtest 'dead_bytes stays zero between checkpoints' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_dead_between'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nautovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS dead-byte test'; } $node->safe_psql( 'postgres', q{ CREATE TABLE db_t (g int, payload text) WITH (algorithm = 'lz4'); INSERT INTO db_t SELECT g, repeat(md5(g::text), 20) FROM generate_series(1, 400) g; CHECKPOINT; }); is( $node->safe_psql( 'postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'db_t'"), '0', 'a fresh checkpoint publishes no dead space'); $node->safe_psql('postgres', "UPDATE db_t SET payload = repeat(md5(g::text || 'x'), 20)"); is( $node->safe_psql( 'postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'db_t'"), '0', 'rewrites between checkpoints account nothing'); $node->safe_psql('postgres', 'CHECKPOINT'); cmp_ok( $node->safe_psql( 'postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'db_t'"), '>', 0, 'the checkpoint publishes the accumulated dead space'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Durability order with fsync=on: after a checkpoint, an immediate stop # must not lose anything the checkpoint reported durable. # --------------------------------------------------------------------------- subtest 'fsync=on crash after checkpoint keeps every row' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_fsync_on'); $node->init; $node->append_conf('postgresql.conf', "fsync = on\ncheckpoint_timeout = 30min\nautovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS fsync-on test'; } $node->safe_psql( 'postgres', q{ CREATE TABLE fo_t (g int, payload text) WITH (algorithm = 'lz4'); INSERT INTO fo_t SELECT g, repeat(md5(g::text), 20) FROM generate_series(1, 300) g; }); $node->safe_psql( 'postgres', "UPDATE fo_t SET payload = repeat(md5(g::text || 'd'), 20) WHERE g % 3 = 1"); $node->safe_psql('postgres', 'CHECKPOINT'); my $expect = $node->safe_psql('postgres', "SELECT md5(string_agg(md5(payload), '' ORDER BY g)) FROM fo_t"); $node->stop('immediate'); $node->start; is($node->safe_psql('postgres', 'SELECT count(*) FROM fo_t'), '300', 'all rows survive the immediate stop'); is( $node->safe_psql( 'postgres', "SELECT md5(string_agg(md5(payload), '' ORDER BY g)) FROM fo_t"), $expect, 'checkpointed payloads are byte-identical after the crash'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A partial trailing .cfsmap row is a crash artifact, not damage # # A torn positional pwrite can leave the map file one byte short of a whole # row. The loader ignores it and the next snapshot rewrites the file, so # pg_cfs_check must report clean, not an error. # --------------------------------------------------------------------------- subtest 'fsck ignores a partial trailing map row' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_map_partial'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\nautovacuum = off"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS partial-map-row test'; } $node->safe_psql( 'postgres', q{ CREATE TABLE partial_t (g int, payload text) WITH (algorithm = 'lz4'); INSERT INTO partial_t SELECT g, repeat(md5(g::text), 10) FROM generate_series(1, 200) g; CHECKPOINT; }); my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('partial_t')"); my $map = $node->data_dir . "/$path.cfsmap"; $node->stop('fast'); my $size = -s $map; truncate($map, $size - 1) or die "truncate $map: $!"; $node->start; my ($ok, $errors) = split qr/\|/, $node->safe_psql('postgres', "SELECT ok, errors FROM pg_cfs_check('partial_t')"); is($ok, 't', 'pg_cfs_check stays clean after a partial map row'); is($errors, '0', 'the partial row is not counted as an error'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A 1-7 byte .cfsmap is a truncated prologue, not an empty map # # An empty map file is legal and means "no blocks yet"; a file that is # shorter than its 8-byte header can only be a torn write or external # damage. Treating it as empty would replay the journal onto a blank map # and silently lose every pre-checkpoint block, and the next snapshot save # would overwrite the evidence. The file and the journal must survive the # failed open unchanged. # # cfs_map_memory = 0 forces the private-map load path, so the corruption is # hit on the open of a fresh backend, not served from a shared pool segment. # --------------------------------------------------------------------------- subtest 'a short page map prologue is corruption, not an empty map' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_short_prologue'); $node->init; $node->append_conf('postgresql.conf', "cfs_map_memory = 0\nautovacuum = off\ncheckpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS short-prologue test'; } $node->safe_psql('postgres', "CREATE TABLE sp_t (id int) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO sp_t SELECT generate_series(1, 100)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('sp_t')"); my $map = $node->data_dir . "/$path.cfsmap"; my $jrn = $node->data_dir . "/$path.cfsjrn"; truncate($map, 4) or die "truncate $map: $!"; my $jrn_before = -s $jrn; my ($ret, $stdout, $stderr) = $node->psql('postgres', 'SELECT count(*) FROM sp_t'); isnt($ret, 0, 'opening the relation fails on a short prologue'); like($stderr, qr/checksum or format corruption/, 'the error names the map (centralised corruption report)'); is(-s $map, 4, 'the short file is not overwritten'); is(-s $jrn, $jrn_before, 'the journal is not reset'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A corrupt map row covered by a journal record is healable, not damage # # The checkpoint fold rewrites .cfsmap rows with lock-free positional pwrites # while the journal record covering each block is still there (the journal is # reset only after the map fsync). A torn row therefore loads as INVALID and # the journal replay heals it - the engine never reports damage. pg_cfs_check # must reach the same verdict: a corrupt row the journal covers is healed, not # counted in crc_failures/errors. # # shared_buffers = 128kB forces the UPDATE's heap pages out through CFS, so # the journal really holds an UPDATE record for block 0 when the row is # damaged; checkpoint_timeout = 30min keeps a fold from racing the check. # --------------------------------------------------------------------------- subtest 'a corrupt row covered by the journal is healable' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_healable'); $node->init; $node->append_conf('postgresql.conf', "shared_buffers = 128kB\nautovacuum = off\ncheckpoint_timeout = 30min" ); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS healable-row test'; } $node->safe_psql('postgres', "CREATE TABLE heal_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO heal_t SELECT g, repeat(md5(g::text), 40) " . "FROM generate_series(1, 300) g"); $node->safe_psql('postgres', 'CHECKPOINT'); # Flushed UPDATE records: the journal covers block 0 while the .cfsmap # row still holds the post-checkpoint version. $node->safe_psql('postgres', "UPDATE heal_t SET payload = repeat('x', 40)"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('heal_t')"); my $map = "$dd/$path.cfsmap"; my $jrn = "$dd/$path.cfsjrn"; cmp_ok(-s $jrn, '>', 16, 'the journal holds the UPDATE records'); flip_map_row_byte($map, 0, 16); my ($ok, $errors, $msg) = split qr/\|/, $node->safe_psql('postgres', "SELECT ok, errors, details FROM pg_cfs_check('heal_t')"); is($ok, 't', 'a covered corrupt row is not an error'); is($errors, '0', 'no error is counted'); like($msg, qr/healed_entries=[1-9]/, 'the healed row is reported'); # Deep mode cross-checks the map against .cfp; the healed row must not # leak into that verdict. my ($deep_ok, $deep_errors) = split qr/\|/, $node->safe_psql('postgres', "SELECT ok, errors FROM pg_cfs_check('heal_t', true)"); is($deep_ok, 't', 'the deep check stays clean on a healed row'); is($deep_errors, '0', 'the deep check counts no error'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A corrupt map row without a covering journal record is damage # # The checkpoint after the last write truncates the journal, so nothing can # heal block 0: the row's data exists nowhere else. pg_cfs_check must keep # reporting the corruption. # --------------------------------------------------------------------------- subtest 'a corrupt row without a covering record is an error' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_uncovered'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\ncheckpoint_timeout = 30min"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS uncovered-row test'; } $node->safe_psql('postgres', "CREATE TABLE heal_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO heal_t SELECT g, repeat(md5(g::text), 40) " . "FROM generate_series(1, 300) g"); $node->safe_psql('postgres', 'CHECKPOINT'); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('heal_t')"); my $map = "$dd/$path.cfsmap"; my $jrn = "$dd/$path.cfsjrn"; ok(-e $jrn && -s _ <= 16, 'the journal holds no records after the checkpoint'); flip_map_row_byte($map, 0, 16); my ($ok, $errors) = split qr/\|/, $node->safe_psql('postgres', "SELECT ok, errors FROM pg_cfs_check('heal_t')"); is($ok, 'f', 'an uncovered corrupt row is an error'); cmp_ok($errors, '>', 0, 'the error is counted'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # An unreadable journal size must not let a checkpoint reset the journal. # # The fold boundary IS the sampled journal size: when the stat fails (the # fstat error class), silently clamping the boundary to the bare header # would let phase 2 reset the journal without folding it - destroying # records that were never proven durable in the map. The checkpoint must # instead fail the relation (the journal is preserved; the next # checkpoint retries), the same contract the torn-tail classification # already upholds. # # The failure is injected with the injection point cfs-fail-jrn-fstat, # placed inside cfs_state_capture(). # --------------------------------------------------------------------------- subtest 'a checkpoint with an unreadable journal size preserves the journal' => sub { if ($ENV{enable_injection_points} ne 'yes') { plan skip_all => 'Injection points not supported by this build'; } my $node = PostgreSQL::Test::Cluster->new('cfs_jrn_stat'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n"); $node->start; if (!$node->check_extension('injection_points')) { plan skip_all => 'Extension injection_points not installed'; } $node->safe_psql( 'postgres', q{ CREATE TABLE jstat_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO jstat_t SELECT g, repeat('s' || g, 80) FROM generate_series(1, 500) g; CHECKPOINT; }); $node->safe_psql('postgres', "UPDATE jstat_t SET payload = repeat('u' || id, 80)"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('jstat_t')"); my $jrn = "$dd/$path.cfsjrn"; ok(-s $jrn > 16, 'the journal holds unfolded records before the checkpoint'); $node->safe_psql('postgres', 'CREATE EXTENSION injection_points'); $node->safe_psql('postgres', "SELECT injection_points_attach('cfs-fail-jrn-fstat', 'notice')"); # The checkpoint must refuse the relation: the ERROR unwinds the # checkpointer's relation loop, and the CHECKPOINT command reports # the failed request. Use the non-fatal psql() so the harness keeps # running; the journal is what matters - the reset never ran, so # every record survives untouched. my $log_off = -s $node->logfile; my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT'); isnt($ret, 0, 'checkpoint with an unreadable journal size fails'); ok( $node->log_contains( qr/CFS: could not determine the journal size/, $log_off), 'the checkpoint reports the unreadable journal size'); ok(-s $jrn > 16, 'the journal is preserved when its size cannot be proven'); $node->safe_psql('postgres', "SELECT injection_points_detach('cfs-fail-jrn-fstat')"); $node->safe_psql('postgres', 'CHECKPOINT'); is(-s $jrn, 16, 'the retry checkpoint folds and resets the journal'); is($node->safe_psql('postgres', 'SELECT count(*) FROM jstat_t'), '500', 'the data is intact'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('jstat_t', true)"), 't', 'pg_cfs_check is clean after the retry'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A journal header already unreadable at the capture must fail the # checkpoint, not skip it forever. # # The HEADER_STALE skip arm of phase 2 describes the window "the header was # readable at the capture and became unreadable while phase 1 ran". A # header already torn at the capture is not that window: the incarnation # cannot be compared, but the journal identity (dev/ino/size) is intact, # so every checkpoint would fold the whole growing journal, phase 2 would # skip the reset through the stale-header arm, the dirty mark would never # clear and the journal would grow without converging - a silent # degradation with no report louder than DEBUG1. The checkpoint must # instead fail the relation (a plain ERROR, the journal preserved; the # next checkpoint retries), matching the signal every other consumer of # the same state already raises (replay: ERROR, verify: ERROR). # # The corruption is injected by flipping the first header byte (the # magic) of the on-disk journal between checkpoints; the original header # is restored afterwards to prove the retry converges once the damage is # repaired. # --------------------------------------------------------------------------- subtest 'a checkpoint with a corrupted journal header fails loudly' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_jrn_hdr'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS journal header test'; } $node->safe_psql( 'postgres', q{ CREATE TABLE jhdr_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO jhdr_t SELECT g, repeat('s' || g, 80) FROM generate_series(1, 500) g; CHECKPOINT; }); $node->safe_psql('postgres', "UPDATE jhdr_t SET payload = repeat('u' || id, 80)"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('jhdr_t')"); my $jrn = "$dd/$path.cfsjrn"; ok(-s $jrn > 16, 'the journal holds unfolded records before the checkpoint'); # Break the header in place: flip the magic byte, keep the records. my $orig_hdr; { open my $fh, '+<:raw', $jrn or die "open $jrn: $!"; seek($fh, 0, 0) or die "seek: $!"; read($fh, $orig_hdr, 16) == 16 or die "short header read"; seek($fh, 0, 0) or die "seek: $!"; print $fh chr(ord(substr($orig_hdr, 0, 1)) ^ 0xFF); close($fh) or die "close: $!"; } # The checkpoint must refuse the relation: phase 1 raises before any # reset, so the header stays broken and the journal keeps every record # (its size may still grow: the buffer flush of the same checkpoint # legitimately appends the pending page records before the CFS phase # runs). Use the non-fatal psql() so the harness keeps running. my $log_off = -s $node->logfile; my ($ret, $stdout, $stderr) = $node->psql('postgres', 'CHECKPOINT'); isnt($ret, 0, 'checkpoint over a corrupted journal header fails'); ok( $node->log_contains( qr/CFS: journal .* has an unreadable header/, $log_off), 'the checkpoint reports the unreadable journal header'); { open my $fh, '<:raw', $jrn or die "open $jrn: $!"; seek($fh, 0, 0) or die "seek: $!"; read($fh, my $now, 16) == 16 or die "short header read"; close($fh) or die "close: $!"; isnt( ord(substr($now, 0, 1)), ord(substr($orig_hdr, 0, 1)), 'the failed checkpoint did not rewrite the journal header'); } ok(-s $jrn > 16, 'the journal is preserved: the reset never ran'); # Repair the header: the retry must converge - fold, reset, data intact. { open my $fh, '+<:raw', $jrn or die "open $jrn: $!"; seek($fh, 0, 0) or die "seek: $!"; print $fh $orig_hdr; close($fh) or die "close: $!"; } $node->safe_psql('postgres', 'CHECKPOINT'); is(-s $jrn, 16, 'the retry checkpoint folds and resets the journal'); is($node->safe_psql('postgres', 'SELECT count(*) FROM jhdr_t'), '500', 'the data is intact'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('jhdr_t', true)"), 't', 'pg_cfs_check is clean after the retry'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Startup folds journals row by row and never materializes the map # # After a crash with journal records pending, the startup scan must fold the # journal into the .cfsmap in place (lazy handle, row-by-row rewrites) and # reset the journal - never load the whole map into memory (the old path, # whose cost tracked the table) and never rewrite a full snapshot. With # log_min_messages = debug1 this is observable in the scan's own log slice, # between the "recovery init starting" and "recovery init complete" LOG # lines: the slice must carry the fold reports and neither a "map loaded:" # full-map load nor a "saving map snapshot:" rewrite. (Outside that slice # WAL redo may still open a full map through a cold nblocks slot - a # pre-existing, out-of-scope path the scan does not own.) # --------------------------------------------------------------------------- subtest 'startup fold does not materialize the map' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_startup_fold'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n" . "max_wal_size = 1GB\n" . "log_min_messages = debug1\n" . "autovacuum = off\n" . "shared_buffers = 128kB"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS startup-fold test'; } # A CFS table with a flushed baseline, then writes past the checkpoint: # the journal holds UPDATE/RESIZE records at the crash (the tiny # shared_buffers forces page evictions, so real UPDATE records reach it). $node->safe_psql('postgres', "CREATE TABLE fold_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO fold_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "INSERT INTO fold_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(501, 700) g"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('fold_t')"); my $jrn = "$dd/$path.cfsjrn"; # Crash before any checkpoint folds the journal. $node->stop('immediate'); cmp_ok(-s $jrn, '>', 16, 'journal holds records at the crash'); my $log_off = -s $node->logfile; ok($node->start, 'server starts after the crash'); # The fold completed: the journal is reset to its bare header and the # data is intact (WAL redo re-applies whatever the crash window lost). ok(-s $jrn < 64, 'journal is truncated back to its bare header'); is($node->safe_psql('postgres', 'SELECT count(*) FROM fold_t'), '700', 'all rows survive the crash restart'); # The scan's own slice: everything the recovery scan logged between its # starting and completion LOG lines. my $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $log_off); ok($log =~ qr/CFS: recovery init starting(.*CFS: recovery init complete[^\n]*)/s, 'the recovery scan starting/completion lines bracket the slice'); my $slice = $1 // ''; like($slice, qr/folded \d+ row\(s\)/, 'the completion LOG reports folded rows'); like($slice, qr/row\(s\) folded into the page map/, 'the per-relation fold is logged at DEBUG1'); # THE regression asserts, scoped to the scan's slice: no private # full-map load (the old path logged "map loaded:" at DEBUG1) and no # whole-file snapshot rewrite ("saving map snapshot:"). unlike($slice, qr/map loaded:/, 'the scan does not materialize the page map'); unlike($slice, qr/saving map snapshot:/, 'the scan does not rewrite a full map snapshot'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Mid-file torn journal record during startup # # A zeroed record in the middle of the journal (valid records still follow # it) cannot be produced by a legal append: the records behind it are the # only durable trace of their changes, so the startup fold must stop and # preserve the journal instead of resetting it. Non-strict mode keeps this # a WARNING and the server comes up (the next restart repeats the fold); # cfs_recovery_strict = on makes the same damage fatal to startup. # # The corruption flips a payload byte of the SECOND record (offset # 16 + 48 + 16; CFS_JOURNAL_HEADER_SIZE is 16, a record is 48 bytes), so # the fold first applies record one and then stops mid-file with one row # already written - the exact "rows folded, journal kept" window the # next restart must complete idempotently. # --------------------------------------------------------------------------- subtest 'mid-file torn journal record during startup' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_startup_torn'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n" . "autovacuum = off\n" . "shared_buffers = 128kB"); $node->start; if (!codec_built($node, 'lz4')) { plan skip_all => 'LZ4 support not built, skipping CFS startup torn-record test'; } # Journal with real UPDATE records past the checkpoint (the tiny # shared_buffers evicts the rewritten pages through CFS). $node->safe_psql('postgres', "CREATE TABLE torn2_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO torn2_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "INSERT INTO torn2_t SELECT g, repeat(md5(g::text), 50) " . "FROM generate_series(501, 700) g"); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('torn2_t')"); my $jrn = "$dd/$path.cfsjrn"; $node->stop('immediate'); my $jrn_size = -s $jrn; ok($jrn_size > 512, 'journal holds many records at the crash'); # Flip a byte of the second record: it fails validation while the # records behind it stay valid, so the fold classifies the stop as # mid-file damage (after folding the first record's row). flip_journal_byte($jrn, 16 + 48 + 16); pass('flipped a payload byte of the second journal record'); # Non-strict (default): the scan engine's torn classification reports # the stop as a WARNING with the "recovery" role and the server comes # up; the journal is NOT truncated (WAL redo appends its own records at # EOF, so it may have grown - what matters is that the scan did not cut # it back). Reads through the still-torn journal are deliberately not # probed here: the map is missing every row covered by a record behind # the torn one, so a read may legitimately ERROR - the loud, non-silent # behaviour the whole contract exists for (the repair below restores # and verifies the data). my $log_off = -s $node->logfile; ok($node->start, 'non-strict startup survives a mid-file torn record'); $node->log_check('non-strict torn-record warning', $log_off, log_like => [qr/WARNING: CFS: stopping journal recovery at offset \d+ \(torn record\)/] ); cmp_ok(-s $jrn, '>=', $jrn_size, 'the journal is not truncated by the non-strict startup'); # Strict: the same damage must refuse the startup - the engine routes # the mid-file report through the recovery channel, which is fatal # under cfs_recovery_strict. $node->stop('fast'); $node->append_conf('postgresql.conf', "cfs_recovery_strict = on"); $log_off = -s $node->logfile; my $started = $node->start(fail_ok => 1); ok(!$started, 'strict startup aborts on a mid-file torn record'); $node->log_check('strict torn-record failure', $log_off, log_like => [qr/checksum or format corruption/, qr/torn journal record at offset/] ); # Back to non-strict, repair the byte and converge: the next startup # folds every record (the original ones and those WAL redo appended at # the restarts above), the journal resets and all 700 rows read back. $node->append_conf('postgresql.conf', "cfs_recovery_strict = off"); ok($node->start, 'non-strict startup works again once strict is off'); $node->stop('fast'); flip_journal_byte($jrn, 16 + 48 + 16); ok($node->start, 'server starts after the repair'); is($node->safe_psql('postgres', 'SELECT count(*) FROM torn2_t'), '700', 'every row is back after the repair restart'); $node->safe_psql('postgres', 'CHECKPOINT'); is(-s $jrn, 16, 'the repaired journal is folded and reset'); $node->stop('fast'); }; done_testing();