# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group # # src/test/recovery/t/503_cfs_compaction.pl # # Correctness and crash-safety of CFS compaction. # # pg_cfs_compact() rewrites the (.cfp, .cfsmap) sidecar pair of a CFS # relation and swaps the new pair in atomically; a background worker does # the same automatically for relations with enough dead space. This test # covers the dangerous windows of that design: # # * the swap must be atomic: a crash during it can never leave a new # .cfp paired with a stale .cfsmap, and the data must survive a crash # both before and after the swap commit point; # * a crash between the durable swap and the journal reset must not # replay a stale journal on top of the freshly swapped-in map; # * a checkpointer/bgwriter flushing dirty pages of the same relation # concurrently with the compaction must neither lose pages nor # corrupt the new map; # * a compaction failure of one relation must not kill the background # worker, must not leak its file descriptors, and must not stop the # worker from compacting the remaining candidates. # * the background worker must react to shutdown requests and cluster # barriers without waiting out its inter-candidate pauses or dropping # the rest of a whole pass. use strict; use warnings FATAL => 'all'; use File::Copy (); use PostgreSQL::Test::Utils; use PostgreSQL::Test::Cluster; use Test::More; # Create $dst as a byte copy of $src (like cp). sub copy_file { my ($src, $dst) = @_; File::Copy::copy($src, $dst) or die "could not copy \"$src\" to \"$dst\": $!"; } # Create an empty file (like touch). sub touch_file { my ($path) = @_; open(my $fh, '>', $path) or die "could not create \"$path\": $!"; close($fh); } # md5 over all payloads of a (id, payload) table, in id order. sub table_checksum { my ($node, $tbl) = @_; return $node->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM $tbl"); } # --------------------------------------------------------------------------- # Crash-safe compaction swap. # # Verifies that the (.cfp, .cfsmap) pair switches atomically during # compaction, so a crash during the swap can never leave a new .cfp paired # with a stale .cfsmap: # * a normal compaction reclaims dead space and keeps the data # byte-identical; # * an interrupted-after-commit swap (commit marker present + .new # candidates) is finished at the next restart, data intact; # * an interrupted-before-commit swap (orphan .new candidates, no # marker) is rolled back to the old pair, data intact. # --------------------------------------------------------------------------- { # Initialize a single node. my $node = PostgreSQL::Test::Cluster->new('cfs_swap'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS compaction swap test'; } # Create a CFS table and generate real dead space (two flushed versions # of every page) so compaction has something to reclaim. $node->safe_psql('postgres', "CREATE TABLE cfs_s (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO cfs_s SELECT g, repeat('a' || g, 200) " . "FROM generate_series(1, 2000) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE cfs_s SET payload = repeat('b' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $rel = $node->safe_psql('postgres', "SELECT pg_relation_filepath('cfs_s')"); my $data_dir = $node->data_dir; my $cfp_file = "$data_dir/$rel.cfp"; my $map_file = "$data_dir/$rel.cfsmap"; my $cfp_before_compact = -s $cfp_file; my $ck_before_compact = table_checksum($node, 'cfs_s'); ok(length($ck_before_compact) == 32, 'table populated before compaction'); # Run compaction: dead space must shrink and the data must be unchanged. my $compact_result = $node->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_s')"); like( $compact_result, qr/reclaimed \d+/, 'compaction produced a reclaim summary'); my $cfp_after_compact = -s $cfp_file; my $ck_after_compact = table_checksum($node, 'cfs_s'); cmp_ok($cfp_after_compact, '<', $cfp_before_compact, 'compaction reclaimed dead space in .cfp'); is($ck_after_compact, $ck_before_compact, 'data is byte-identical after compaction'); # No leftover swap artefacts after a clean compaction. ok(!-f "$cfp_file.cfsswap", 'no leftover commit marker after clean compaction'); ok(!-f "$cfp_file.new", 'no leftover .cfp.new after clean compaction'); ok(!-f "$map_file.new", 'no leftover .cfsmap.new after clean compaction'); # Simulate a crash AFTER the commit point of a new compaction swap: the # candidate pair (.cfp.new / .cfsmap.new) is fully written and the commit # marker (.cfp.cfsswap) is on disk, but the activation renames did not # happen. Recovery must finish the activation and keep the data intact. $node->safe_psql('postgres', 'CHECKPOINT'); $ck_before_compact = table_checksum($node, 'cfs_s'); # Snapshot the current (post-compaction) pair as the "new candidate". copy_file($cfp_file, "$cfp_file.new"); copy_file($map_file, "$map_file.new"); touch_file("$cfp_file.cfsswap"); ok(-f "$cfp_file.cfsswap", 'commit marker created for interrupted swap'); ok(-f "$cfp_file.new", '.cfp.new candidate present'); # Crash and restart: recovery completes the activation. $node->stop('immediate'); $node->start; ok(!-f "$cfp_file.cfsswap", 'commit marker consumed by recovery'); ok(!-f "$cfp_file.new", '.cfp.new consumed by recovery'); ok(!-f "$map_file.new", '.cfsmap.new consumed by recovery'); my $ck_after_swap_crash = table_checksum($node, 'cfs_s'); is($ck_after_swap_crash, $ck_before_compact, 'data intact after interrupted-after-commit swap recovery'); # Simulate a crash BEFORE the commit point: orphan candidate files exist # but no commit marker. Recovery must discard the orphans and keep using # the old (current) pair, with data intact. $node->safe_psql('postgres', 'CHECKPOINT'); $ck_before_compact = table_checksum($node, 'cfs_s'); my $cfp_pre_orphan = -s $cfp_file; copy_file($cfp_file, "$cfp_file.new"); copy_file($map_file, "$map_file.new"); # Deliberately NO commit marker. ok(-f "$cfp_file.new", 'orphan .cfp.new created (no marker)'); $node->stop('immediate'); $node->start; ok(!-f "$cfp_file.new", 'orphan .cfp.new discarded by recovery'); ok(!-f "$map_file.new", 'orphan .cfsmap.new discarded by recovery'); my $ck_after_orphan = table_checksum($node, 'cfs_s'); is($ck_after_orphan, $ck_before_compact, 'data intact after interrupted-before-commit swap recovery'); is(-s $cfp_file, $cfp_pre_orphan, 'old .cfp preserved when swap was not committed'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # An interrupted swap must activate the compacted pair, not the old map # # The crafted-marker scenarios above copy the CURRENT pair into the .new # candidates, so a wrong activation (renaming the new .cfp over the old # .cfsmap, or keeping the old map) would be invisible: both halves are # byte-identical. This scenario builds a candidate pair that really # differs from the live pair: the fragmented pre-compaction pair is put # aside, the relation is compacted (a genuinely smaller .cfp + the map that # matches it), then the fragmented pair is written back over the live names # and the compacted pair is staged as .new with a commit marker — the exact # on-disk state of a compaction interrupted after its commit point. # # Recovery must activate the compacted pair TOGETHER: the live .cfp shrinks # to the compacted size (an old-map activation would keep the fragmented # size or break reads through mismatched offsets) and the data is intact. # --------------------------------------------------------------------------- subtest 'interrupted swap activates the compacted pair, not the old map' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_swap_real'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping real-candidate swap test'; } # Two flushed versions of every page: dead space for the compactor. $node->safe_psql('postgres', "CREATE TABLE cfs_real_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO cfs_real_t SELECT g, repeat('r' || g, 200) " . "FROM generate_series(1, 2000) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE cfs_real_t SET payload = repeat('u' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $data_dir = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('cfs_real_t')"); my $cfp_file = "$data_dir/$rel_path.cfp"; my $map_file = "$data_dir/$rel_path.cfsmap"; my $ck = table_checksum($node, 'cfs_real_t'); my $size_fragmented = -s $cfp_file; # Put the fragmented pair aside (outside the database directories, so # the startup cleanup does not look at it), then compact for real. $node->stop('fast'); copy_file($cfp_file, "$data_dir/aside.cfp"); copy_file($map_file, "$data_dir/aside.cfsmap"); $node->start; $node->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_real_t')"); my $size_compacted = -s $cfp_file; cmp_ok($size_compacted, '<', $size_fragmented, 'compaction really shrank the .cfp (candidate differs from live)'); is(table_checksum($node, 'cfs_real_t'), $ck, 'data intact after the real compaction'); # Stage the interrupted-after-commit state: the compacted pair as .new # candidates, then the fragmented pair back over the live names, then # the commit marker. $node->stop('fast'); copy_file($cfp_file, "$cfp_file.new"); copy_file($map_file, "$map_file.new"); copy_file("$data_dir/aside.cfp", $cfp_file); copy_file("$data_dir/aside.cfsmap", $map_file); touch_file("$cfp_file.cfsswap"); # Recovery must complete the activation of the compacted pair. $node->start; ok(!-f "$cfp_file.cfsswap", 'commit marker consumed by recovery'); ok(!-f "$cfp_file.new", '.cfp.new consumed by recovery'); ok(!-f "$map_file.new", '.cfsmap.new consumed by recovery'); is(-s $cfp_file, $size_compacted, 'live .cfp is the compacted one, not the fragmented pair'); isnt(-s $cfp_file, $size_fragmented, 'activation did not keep the old fragmented .cfp'); is(table_checksum($node, 'cfs_real_t'), $ck, 'data intact after the real-candidate swap recovery'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('cfs_real_t', deep => true)"), 't', 'pg_cfs_check ok after the real-candidate swap'); unlink("$data_dir/aside.cfp", "$data_dir/aside.cfsmap"); $node->stop('fast'); }; # --------------------------------------------------------------------------- # ALTER SYSTEM RESET ALL with a registered CFS background worker. # # Resetting all GUCs while the background compaction worker is registered # must not crash or hang the server. Also records a diagnostic baseline of # pg_relation_size() of a CFS table after dead-byte accumulation: the exact # growth semantics are intentionally not asserted, only that the value is # sane and the table stays readable. (pg_relation_size() of a CFS relation # currently reports 0 for the main fork because the data lives in # sidecars.) # --------------------------------------------------------------------------- subtest 'ALTER SYSTEM RESET ALL with a CFS background worker' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bgworker_reset'); $node->init; # Short bg period so the worker cycles during the test. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->start; my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS bgworker reset test'; } $node->safe_psql('postgres', "CREATE TABLE rst_t (id int, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO rst_t SELECT g, repeat('r' || g, 200) " . "FROM generate_series(1, 500) g"); # Force some dead bytes so the worker has candidates if it cycles. $node->safe_psql('postgres', "UPDATE rst_t SET data = repeat('u', 200)"); $node->safe_psql('postgres', "CHECKPOINT"); # Let the bgworker run a cycle, then reset everything. $node->safe_psql('postgres', "SELECT pg_sleep(0.6)"); $node->safe_psql('postgres', "ALTER SYSTEM RESET ALL"); $node->safe_psql('postgres', "SELECT pg_reload_conf()"); $node->safe_psql('postgres', "SELECT pg_sleep(0.6)"); # Server still alive and serving queries -- the worker did not # crash/hang. my $alive = $node->safe_psql('postgres', "SELECT count(*) FROM rst_t"); is($alive, 500, 'server alive and serving after ALTER SYSTEM RESET ALL'); # cfs_bg_period_ms still parses and is served (the value comes from # postgresql.conf here, since ALTER SYSTEM RESET ALL only undoes ALTER # SYSTEM edits, not the config file -- the point is that the worker does # not crash or hang, not a specific numeric value). my $bg_period_now = $node->safe_psql('postgres', "SHOW cfs_bg_period_ms"); like($bg_period_now, qr/^\d+$/, 'cfs_bg_period_ms is a valid integer after RESET ALL'); # Data still readable after the reset dust settled. my $ck = $node->safe_psql('postgres', "SELECT md5(string_agg(data, chr(10) ORDER BY id)) FROM rst_t"); ok(length($ck) == 32, 'rst_t payload readable after RESET ALL'); # pg_relation_size baseline after dead-byte accumulation (diagnostic # only, not asserted against an expected growth model). $node->safe_psql('postgres', "CREATE TABLE sz_t (id serial, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO sz_t (data) SELECT repeat('x', 4000) " . "FROM generate_series(1, 2000)"); my $s0 = $node->safe_psql('postgres', "SELECT pg_relation_size('sz_t')"); like($s0, qr/^-?\d+$/, 'pg_relation_size is a number before the UPDATE'); # UPDATE in place grows dead bytes in the append-only .cfp. $node->safe_psql('postgres', "UPDATE sz_t SET data = repeat('y', 4000)"); $node->safe_psql('postgres', "CHECKPOINT"); my $s1 = $node->safe_psql('postgres', "SELECT pg_relation_size('sz_t')"); like($s1, qr/^-?\d+$/, 'pg_relation_size is a number after dead-byte accumulation'); note("pg_relation_size diagnostic: S0=$s0, S1=$s1; not asserted"); # The table stays readable regardless of the size interpretation. my $sz_count = $node->safe_psql('postgres', "SELECT count(*) FROM sz_t"); is($sz_count, 2000, 'sz_t readable after dead-byte accumulation'); my $sz_sum = $node->safe_psql('postgres', "SELECT count(*) FROM sz_t WHERE data = repeat('y', 4000)"); is($sz_sum, 2000, 'sz_t rows reflect the UPDATE (dead bytes do not corrupt)'); $node->stop('immediate'); }; # --------------------------------------------------------------------------- # Compaction durability / quiesce. # # Covers the two crash-safety windows of the compaction swap: # # A. Durable journal reset: a crash between the durable (.cfp,.cfsmap) # swap and the .cfsjrn reset must not replay a stale journal (offsets # into the old, replaced .cfp) on top of the freshly swapped-in map. # Simulated by restoring a pre-compaction journal next to the commit # marker and crashing; recovery must finish the journal reset before # the new map is used. # # B. Quiesce during copy+swap: a checkpointer flushing dirty buffers of # the same relation concurrently with pg_cfs_compact() must neither # lose the flushed pages nor corrupt the new map. Reproduced with a # throttled checkpoint whose buffer flush overlaps the compaction. # --------------------------------------------------------------------------- subtest 'compaction durability and quiesce' => sub { # Initialize a single node. full_page_writes is disabled so that WAL # redo must read the CFS pages (rather than restore full-page images), # which makes a stale page map fatal to recovery instead of silently # healed. my $node = PostgreSQL::Test::Cluster->new('cfs_quiesce'); $node->init; $node->append_conf( 'postgresql.conf', qq{ shared_buffers = 16MB checkpoint_timeout = 30s checkpoint_completion_target = 0.9 bgwriter_delay = 10ms bgwriter_lru_maxpages = 1000 full_page_writes = off autovacuum = off }); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS quiesce test'; } my $data_dir = $node->data_dir; # Scenario A: crash between the durable swap and the journal reset. # # Build a non-empty journal (flushed v2 pages after the last checkpoint), # compact, then restore the stale journal next to a commit marker. This # is exactly the on-disk state a crash leaves when the journal reset did # not become durable before the swap. Recovery must reset the journal # as part of finishing the interrupted swap, otherwise the stale offsets # are replayed on top of the new map and every read fails. $node->safe_psql('postgres', "CREATE TABLE cfs_q (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO cfs_q SELECT g, repeat('a' || g, 100) " . "FROM generate_series(1, 4000) g"); $node->safe_psql('postgres', 'CHECKPOINT'); my $rel = $node->safe_psql('postgres', "SELECT pg_relation_filepath('cfs_q')"); my $cfp_file = "$data_dir/$rel.cfp"; my $map_file = "$data_dir/$rel.cfsmap"; my $jrn_file = "$data_dir/$rel.cfsjrn"; my $jrn_size_after_ckpt = -s $jrn_file; # Dirty every page with a new version; the buffers stay in the pool. $node->safe_psql('postgres', "UPDATE cfs_q SET payload = repeat('b' || id, 100)"); # Evict the dirty pages through the normal write path (no checkpoint!) # so that the journal accumulates UPDATE records pointing into the old # .cfp. $node->safe_psql('postgres', "CREATE TABLE churn (id int, payload text)"); $node->safe_psql('postgres', "INSERT INTO churn SELECT g, repeat('x', 200) " . "FROM generate_series(1, 200000) g"); my $jrn_size_stale = -s $jrn_file; cmp_ok($jrn_size_stale, '>', $jrn_size_after_ckpt, 'journal accumulated records from the forced flush'); # Save the stale journal aside, then compact. copy_file($jrn_file, "$jrn_file.stale"); my $hash_v2 = table_checksum($node, 'cfs_q'); my $compact_result = $node->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_q')"); like($compact_result, qr/reclaimed \d+/, 'compaction of cfs_q succeeded'); is(table_checksum($node, 'cfs_q'), $hash_v2, 'data intact right after compaction'); # Simulate the crash window: the swap is durable (commit marker left # behind) but the journal reset is not — the stale journal is back. copy_file("$jrn_file.stale", $jrn_file); touch_file("$cfp_file.cfsswap"); $node->stop('immediate'); $node->start; ok(!-f "$cfp_file.cfsswap", 'commit marker consumed by recovery'); is(table_checksum($node, 'cfs_q'), $hash_v2, 'stale journal not replayed over the compacted map after crash'); is($node->safe_psql('postgres', "SELECT count(*) FROM cfs_q"), '4000', 'row count preserved after crash during swap'); $node->safe_psql('postgres', "DROP TABLE churn"); # Scenario B: background flush racing pg_cfs_compact(). # # Every round leaves the whole table dirty in the buffer pool and # compacts immediately, while the (aggressively configured) bgwriter # flushes the dirty pages concurrently. Without a quiesce barrier the # flush writes pages through its own stale CfsRelation handle while the # compaction swaps the files underneath it, silently losing the flushed # versions. After the compaction a churn insert evicts the (now clean) # buffers, so the verification hash is read back from disk: a lost flush # shows up as stale page contents without any crash being needed. $node->safe_psql('postgres', "CREATE TABLE cfs_q2 (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO cfs_q2 SELECT g, repeat('c' || g, 100) " . "FROM generate_series(1, 40000) g"); $node->safe_psql('postgres', "CREATE TABLE churn2 (id int, payload text)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $hash_round; for my $round (1 .. 5) { # New version of every row: dead space for the compactor, dirty # pages for the bgwriter. $node->safe_psql('postgres', "UPDATE cfs_q2 SET payload = repeat('r$round-' || id, 60)"); $hash_round = table_checksum($node, 'cfs_q2'); # Compact while the bgwriter is busy flushing the dirty pages. $node->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_q2')"); # Evict the clean cfs_q2 buffers so the hash below is served from # disk, not from the (correct) in-memory copies. $node->safe_psql('postgres', "TRUNCATE churn2"); $node->safe_psql('postgres', "INSERT INTO churn2 SELECT g, repeat('y', 200) " . "FROM generate_series(1, 100000) g"); is( table_checksum($node, 'cfs_q2'), $hash_round, "no page lost by background flush racing compaction (round $round)" ); } # Crash-recovery cross-check after the concurrent rounds. $node->stop('immediate'); $node->start; is(table_checksum($node, 'cfs_q2'), $hash_round, 'data intact after crash following concurrent compaction'); is($node->safe_psql('postgres', "SELECT count(*) FROM cfs_q2"), '40000', 'row count preserved after crash following concurrent compaction'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Background worker error isolation. # # A compaction failure of one candidate relation must not kill the CFS # background compaction worker: the error has to be logged, the failed # candidate recorded in the attempt history, and the cycle must continue # with the remaining candidates. Otherwise an ereport(ERROR) from the # per-relation compaction propagates out of the worker main loop and kills # the whole worker, after which the same broken candidate -- always first # in the dead-bytes order -- kills it again on every restart, silently # stopping automatic compaction for the entire cluster. # # The deterministic failure trigger is a *directory* placed where the # compaction expects to create its ".cfp.tmp" work file: # BasicOpenFile() on it fails with EISDIR every time. The open-path swap # recovery only warns when it cannot unlink the obstacle, so the relation # stays readable and stays a valid candidate. # --------------------------------------------------------------------------- subtest 'background worker error isolation' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bgworker_error_isolation'); $node->init; # Fast worker cycles, no per-relation backoff, low candidate threshold. # The 2000 ms inter-candidate pause gives the fd sampling below a # deterministic idle window after every failed candidate: 800 ms left # the window too tight on a loaded machine, where the worker could # finish the pass before the second sample. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 10"); $node->append_conf('postgresql.conf', "cfs_bg_delay_ms = 2000"); $node->start; my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS bgworker error isolation test'; } # Pause and let any in-flight pass drain (the pause only stops new # passes): the tables must appear for the worker all at once, with the # obstacles already in place. An early pass would compact the # not-yet-broken tables and they would never become failing candidates. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); wait_for($node, 'postgres', "SELECT last_cycle_started_at IS NULL " . "OR last_cycle_finished_at >= last_cycle_started_at " . "FROM pg_cfs_bgworker_status()") or die "background worker did not quiesce after pause"; # bad_t gets more dead bytes than good_t so it is always the first # candidate in the dead-bytes-descending order. $node->safe_psql('postgres', "CREATE TABLE bad_t (id int, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "CREATE TABLE bad2_t (id int, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "CREATE TABLE bad3_t (id int, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "CREATE TABLE good_t (id int, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO bad_t SELECT g, repeat('b' || g, 300) " . "FROM generate_series(1, 1000) g"); $node->safe_psql('postgres', "INSERT INTO bad2_t SELECT g, repeat('c' || g, 300) " . "FROM generate_series(1, 600) g"); $node->safe_psql('postgres', "INSERT INTO bad3_t SELECT g, repeat('d' || g, 300) " . "FROM generate_series(1, 400) g"); $node->safe_psql('postgres', "INSERT INTO good_t SELECT g, repeat('g' || g, 300) " . "FROM generate_series(1, 200) g"); # Flush the first versions BEFORE rewriting: dead space only appears # when a rewrite supersedes already-durable records (an INSERT and its # UPDATE flushed together leave no dead bytes at all, and the worker # would see no candidates until much later hint-bit rewrites). $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE bad_t SET data = repeat('B' || id, 300)"); $node->safe_psql('postgres', "UPDATE bad2_t SET data = repeat('C' || id, 300)"); $node->safe_psql('postgres', "UPDATE bad3_t SET data = repeat('D' || id, 300)"); $node->safe_psql('postgres', "UPDATE good_t SET data = repeat('G' || id, 300)"); $node->safe_psql('postgres', "CHECKPOINT"); my $good_oid = $node->safe_psql('postgres', "SELECT 'good_t'::regclass::oid"); my $bad_oid = $node->safe_psql('postgres', "SELECT 'bad_t'::regclass::oid"); # Break compaction deterministically: a directory where the compaction # wants to create its work file makes BasicOpenFile() fail with EISDIR # on every attempt. my $dd = $node->data_dir; my $bad_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('bad_t')"); ok(mkdir("$dd/$bad_path.cfp.tmp"), 'planted a directory obstacle at the .cfp.tmp path of bad_t'); foreach my $t ('bad2_t', 'bad3_t') { my $p = $node->safe_psql('postgres', "SELECT pg_relation_filepath('$t')"); mkdir("$dd/$p.cfp.tmp") or die "could not plant obstacle: $!"; } my $log_offset = -s $node->logfile; $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume()"); # The worker picks bad_t first and the compaction errors out. $node->wait_for_log(qr/CFS: compaction: could not create ".*\.cfp\.tmp"/, $log_offset); pass('bgworker logged the compaction failure of bad_t'); # The descriptor-leak window is ONE pass of the short-lived # per-database worker: it opens a candidate's sidecars before hitting # the obstacle, and the error handling must release them -- a failed # candidate must not leave descriptors behind for the remaining # candidates of the same pass. Across passes the process is replaced, # so the check samples the SAME worker between two failed candidates # of one pass (the old check polled the launcher, which never opens # sidecars, and so could never fail). The sampling happens a quarter # into the 800 ms inter-candidate pause, where the worker is idle and # holds nothing but whatever a failed attempt failed to release. SKIP: { skip 'counting open fds requires Linux /proc', 3 if ($^O ne 'linux'); # The log offset goes first: the second failure of the current # pass must still be ahead of us when the pid poll returns. $log_offset = -s $node->logfile; my $worker_pid; my $pid_deadline = time() + 10; while (time() < $pid_deadline) { $worker_pid = $node->safe_psql('postgres', "SELECT pid FROM pg_stat_activity " . "WHERE backend_type LIKE 'CFS background compaction worker for database%'" ); last if $worker_pid =~ /^\d+$/; $node->safe_psql('postgres', "SELECT pg_sleep(0.1)"); } ok($worker_pid =~ /^\d+$/, 'found the per-database worker pid'); my $count_fds = sub { opendir(my $dh, "/proc/$worker_pid/fd") or die "opendir /proc/$worker_pid/fd: $!"; my $n = grep { /^\d+$/ } readdir($dh); closedir($dh); return $n; }; my $sample_in_pause = sub { # A quarter into the 800 ms inter-candidate pause. $node->safe_psql('postgres', "SELECT pg_sleep(0.2)"); return $count_fds->(); }; $node->wait_for_log( qr/CFS: compaction: could not create ".*\.cfp\.tmp"/, $log_offset); my $fds_mid = $sample_in_pause->(); $log_offset = -s $node->logfile; $node->wait_for_log( qr/CFS: compaction: could not create ".*\.cfp\.tmp"/, $log_offset); my $fds_late = $sample_in_pause->(); my $pid_again = $node->safe_psql('postgres', "SELECT pid FROM pg_stat_activity " . "WHERE backend_type LIKE 'CFS background compaction worker for database%'" ); is($pid_again, $worker_pid, 'both samples were taken by the same worker process'); cmp_ok($fds_late, '<=', $fds_mid, "failed candidates do not leak descriptors within one pass " . "($fds_mid mid-pass, $fds_late later)"); } # The worker survives the error and proceeds to the next candidate: # good_t is compacted after bad_t failed. $node->wait_for_log(qr/CFS: compaction complete for relation $good_oid:/, $log_offset); pass('bgworker continued the cycle and compacted good_t'); # The worker process itself never exited. my $log = slurp_file($node->logfile); unlike( $log, qr/background worker "CFS background compaction worker" \(PID \d+\) exited with exit code/, 'bgworker process survived the per-relation compaction error'); # The server as a whole is unaffected and the broken table stays # readable. my $alive = $node->safe_psql('postgres', "SELECT count(*) FROM good_t"); is($alive, 200, 'server alive and good_t intact after the failed cycles'); # Manual compaction of the broken relation must still report the error # to the calling SQL client (the isolation only applies to the automatic # worker path). my ($ret, undef, $stderr) = $node->psql('postgres', "SELECT pg_cfs_compact('bad_t')"); isnt($ret, 0, 'manual pg_cfs_compact on the broken relation fails'); like( $stderr, qr/could not create ".*\.cfp\.tmp"/, 'manual compaction error reaches the SQL client'); # Once the obstacle is removed, automatic compaction of bad_t succeeds # on a later cycle -- the failure did not wedge the candidate # permanently. rmdir("$dd/$bad_path.cfp.tmp") or die "rmdir obstacle: $!"; $node->wait_for_log(qr/CFS: compaction complete for relation $bad_oid:/, $log_offset); pass('bad_t compacts automatically after the obstacle is removed'); $node->stop('immediate'); }; # --------------------------------------------------------------------------- # Background worker candidate selection. # # The worker must compact a relation only while its dead-space ratio # reaches cfs_bg_threshold, and a successful compaction must reset the # relation's dead_bytes counter, so that: # * with the threshold above the actual dead-space ratio the relation is # never touched; # * lowering the threshold below the ratio makes the relation a # candidate exactly once; # * right after the compaction pg_stat_cfs.dead_bytes of the relation # is 0; # * without new fragmentation the same relation is not re-compacted on # subsequent worker cycles. # The threshold is driven through ALTER SYSTEM + pg_reload_conf() to prove # the worker honours the GUC at runtime. # --------------------------------------------------------------------------- subtest 'background worker candidate selection' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_candidate'); $node->init; # Fast worker cycles, no per-relation backoff. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "autovacuum = off"); $node->start; my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS candidate selection test'; } # Threshold far above any reachable dead-space ratio. Set it before # the table exists so no worker cycle can ever see the default # threshold together with dead bytes. $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_bg_threshold = 90"); $node->safe_psql('postgres', "SELECT pg_reload_conf()"); $node->safe_psql('postgres', "SELECT pg_sleep(1)"); # Real dead space: two flushed versions of every row (~50% of the # total bytes, well below 90%). $node->safe_psql('postgres', "CREATE TABLE thr_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO thr_t SELECT g, repeat('a' || g, 200) " . "FROM generate_series(1, 2000) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE thr_t SET payload = repeat('b' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $thr_oid = $node->safe_psql('postgres', "SELECT 'thr_t'::regclass::oid"); my $ck_before_compact = table_checksum($node, 'thr_t'); # A few worker cycles at the high threshold: no compaction of thr_t # may be logged. Three periods of cfs_bg_period_ms = 1000. my $log_offset = -s $node->logfile; sleep(3); my $log = slurp_file($node->logfile, $log_offset); my $compactions = () = $log =~ /CFS: compaction complete for relation $thr_oid:/g; is($compactions, 0, 'worker ignores thr_t while its dead-space ratio is below cfs_bg_threshold' ); # Drop the threshold below the actual ratio: the worker must pick the # table up on a later cycle. $log_offset = -s $node->logfile; $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_bg_threshold = 1"); $node->safe_psql('postgres', "SELECT pg_reload_conf()"); $node->safe_psql('postgres', "SELECT pg_sleep(1)"); $node->wait_for_log(qr/CFS: compaction complete for relation $thr_oid:/, $log_offset); pass( 'worker compacted thr_t once the threshold dropped below its dead-space ratio' ); # A successful compaction reclaims all dead space, so the relation's # dead_bytes counter must be reset to zero. is( $node->safe_psql( 'postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'thr_t'"), '0', 'dead_bytes of thr_t is reset after its compaction'); # No new writes, so no new fragmentation: the relation must stop being # a candidate and no further compactions of thr_t may be logged over # the next few worker cycles. $log_offset = -s $node->logfile; sleep(4); $log = slurp_file($node->logfile, $log_offset); $compactions = () = $log =~ /CFS: compaction complete for relation $thr_oid:/g; is($compactions, 0, 'worker does not re-compact thr_t without new fragmentation'); # The data survived the background compaction(s). is(table_checksum($node, 'thr_t'), $ck_before_compact, 'data intact after background compaction of thr_t'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # The inter-candidate pause is a visible latch wait. # # The worker pauses cfs_bg_delay_ms between the candidates of one pass. # That pause must be a latch wait reported through pg_stat_activity, the # way every daemon-scale wait of vanilla is (the autovacuum launcher nap); # a blind pg_usleep is invisible to pg_stat_activity and silently loses its # remainder on any signal, which pgsleep.c itself calls out as bad # practice. A fast shutdown during the pause must also stay prompt # (nanosleep wakes on EINTR today; the latch wait must keep it so). # --------------------------------------------------------------------------- subtest 'the inter-candidate pause is a visible latch wait' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_sleep'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 10"); # The whole point of the test: an 8 s pause between candidates. $node->append_conf('postgresql.conf', "cfs_bg_delay_ms = 8000"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS shutdown-latency test'; } # Keep the worker out of the picture while the tables are being # created: an early pass that sees only the first finished table would # compact it alone and never enter the inter-candidate pause. After # the resume the next pass sees both candidates together, so the first # completed compaction is deterministically followed by the pause. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); fragment_table($node, 'postgres', 'sleep_a', 'sa'); fragment_table($node, 'postgres', 'sleep_b', 'sb'); $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume()"); # The first candidate of the pass completes, then the worker enters the # 8 s inter-candidate pause: during it the worker must be observable # with the CfsBgworkerDelay wait event. my $log_offset = -s $node->logfile; $node->wait_for_log(qr/compaction complete for relation \d+:/, $log_offset); my $delay_seen = 0; my $deadline = time() + 6; while (time() < $deadline) { my $ev = $node->safe_psql('postgres', "SELECT wait_event FROM pg_stat_activity " . "WHERE backend_type LIKE 'CFS background compaction worker for database%'" ); if ($ev eq 'CfsBgworkerDelay') { $delay_seen = 1; last; } $node->safe_psql('postgres', "SELECT pg_sleep(0.1)"); } ok($delay_seen, 'inter-candidate pause is reported as the CfsBgworkerDelay wait event' ); # A fast shutdown issued during the pause must stay prompt. my $t0 = time(); $node->stop('fast'); my $elapsed = time() - $t0; cmp_ok($elapsed, '<', 5, "fast shutdown during the inter-candidate pause stays prompt (${elapsed}s)" ); }; # --------------------------------------------------------------------------- # A procsignal barrier does not abort a whole pass. # # DROP DATABASE broadcasts a cluster-wide procsignal barrier # (SMGRRELEASE) and waits until every process has absorbed it. The worker # used to treat a merely pending barrier as a reason to throw away the rest # of the pass and restart a full cfs_bg_period_ms later, instead of # absorbing the barrier in place and continuing, the way vanilla processes # do (ProcessMainLoopInterrupts / CHECK_FOR_INTERRUPTS in their hot loops, # e.g. autovacuum). With a long period the dropped pass is observable as # the second candidate staying un-compacted for the whole period. # --------------------------------------------------------------------------- subtest 'a procsignal barrier does not abort the compaction pass' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_barrier'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); # Long period: a dropped pass must not be retried for a while, which is # exactly how the old barrier handling shows up. $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 10000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 10"); $node->append_conf('postgresql.conf', "cfs_bg_delay_ms = 3000"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS barrier test'; } # barrier_src has four times the rows of barrier_t, so it always has # more dead bytes and is always the FIRST candidate of the pass; # barrier_t is compacted right after the pause that follows it. $node->safe_psql('postgres', "CREATE TABLE barrier_src (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO barrier_src SELECT g, repeat('a' || g, 200) " . "FROM generate_series(1, 800) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE barrier_src SET payload = repeat('A' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "CREATE TABLE barrier_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO barrier_t SELECT g, repeat('b' || g, 200) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE barrier_t SET payload = repeat('B' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $oid_first = $node->safe_psql('postgres', "SELECT 'barrier_src'::regclass::oid"); my $oid_second = $node->safe_psql('postgres', "SELECT 'barrier_t'::regclass::oid"); # A throwaway database whose DROP is only needed for its cluster-wide # barrier broadcast. $node->safe_psql('postgres', 'CREATE DATABASE cfs_barrier_drop'); # Wait for the first candidate of a pass, then broadcast the barrier # while the worker is in the 3 s pause before barrier_t. The log # offset is taken BEFORE the drop: with the barrier absorbed in place # the pause is cut short by the barrier's own wake-up, so the second # candidate may legitimately complete while the DROP statement is # still waiting for the barrier to be absorbed. my $log_offset = -s $node->logfile; $node->wait_for_log(qr/compaction complete for relation $oid_first:/, $log_offset); $log_offset = -s $node->logfile; $node->safe_psql('postgres', 'DROP DATABASE cfs_barrier_drop WITH (FORCE)'); # The pass must continue: barrier_t is compacted within the same pass, # long before the 10 s period could restart it. my $second_compacted = 0; my $deadline = time() + 6; while (time() < $deadline) { my $log = slurp_file($node->logfile, $log_offset); if ($log =~ /compaction complete for relation $oid_second:/) { $second_compacted = 1; last; } $node->safe_psql('postgres', "SELECT pg_sleep(0.1)"); } ok($second_compacted, 'pass continues through a procsignal barrier'); is($node->safe_psql('postgres', "SELECT count(*) FROM barrier_t"), 200, 'barrier_t intact after the pass'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Lock acquisition polling is a visible latch wait. # # While the worker waits out its cfs_bg_respond_time_s window for the # AccessExclusiveLock of a contended candidate, it polls in 200 ms ticks. # Those ticks must be latch waits reported through pg_stat_activity with # the CfsBgworkerLock wait event -- a blind pg_usleep tick is invisible, # like any daemon-scale sleep that is not a WaitLatch. # --------------------------------------------------------------------------- subtest 'lock acquisition polling is a visible latch wait' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_locktick'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); # Keep the worker retrying the lock long enough to observe it. $node->append_conf('postgresql.conf', "cfs_bg_respond_time_s = 60"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS lock-tick test'; } # One candidate, created while the worker is paused and locked by a # separate session before the worker resumes, so the very first # candidate of the next pass blocks on the lock. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); fragment_table($node, 'postgres', 'lock_t', 'lk'); my $locker = $node->background_psql('postgres', on_error_stop => 1); $locker->query_until(qr/LOCK-READY/m, "BEGIN;\nLOCK TABLE lock_t IN ACCESS EXCLUSIVE MODE;\nSELECT 'LOCK-READY';\n" ); $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume()"); # While the worker polls for the lock it must be observable with the # CfsBgworkerLock wait event. my $lock_seen = 0; my $deadline = time() + 10; while (time() < $deadline) { my $ev = $node->safe_psql('postgres', "SELECT wait_event FROM pg_stat_activity " . "WHERE backend_type LIKE 'CFS background compaction worker for database%'" ); if ($ev eq 'CfsBgworkerLock') { $lock_seen = 1; last; } $node->safe_psql('postgres', "SELECT pg_sleep(0.1)"); } ok($lock_seen, 'lock acquisition polling is reported as the CfsBgworkerLock wait event' ); # Release the lock: the worker acquires it on a later tick and the # contended candidate is compacted normally. $locker->query_until(qr/UNLOCKED/m, "ROLLBACK;\nSELECT 'UNLOCKED';\n"); $locker->quit; my $log_offset = -s $node->logfile; $node->wait_for_log(qr/compaction complete for relation \d+:/, $log_offset); is($node->safe_psql('postgres', "SELECT count(*) FROM lock_t"), 500, 'lock_t intact after the contended pass'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Fast shutdown interrupts a running compaction. # # The autovacuum worker reference: "SIGINT is used to signal canceling the # current table's vacuum; SIGTERM means abort and exit cleanly" -- SIGTERM # is handled by die() and the hot loop checks for interrupts per page # ("CHECK_FOR_INTERRUPTS is supposed to be used in certain spots in order # not to ignore shutdown commands for too long", do_autovacuum). The CFS # worker instead played a started compaction out to the end after the # shutdown request (delaying a fast shutdown by the whole copy loop) and # left its lock wait with a silent DEBUG1 skip instead of the standard # "terminating background worker due to administrator command" FATAL. # # The copy phase is stretched deterministically with the existing debug GUC # cfs_debug_compact_delay_ms. # --------------------------------------------------------------------------- subtest 'fast shutdown interrupts a running compaction' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_stopcopy'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 10"); # Stretch the copy phase to ~16 s (about 165 live blocks * 100 ms). $node->append_conf('postgresql.conf', "cfs_debug_compact_delay_ms = 100"); # Keep the lock wait of phase 2 observable. $node->append_conf('postgresql.conf', "cfs_bg_respond_time_s = 3600"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS shutdown-interrupt test'; } # --- Phase 1: the shutdown lands inside the copy phase --------------- $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); fragment_table($node, 'postgres', 'stop_t', 'sp'); my $stop_oid = $node->safe_psql('postgres', "SELECT 'stop_t'::regclass::oid"); $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume()"); ok( wait_for( $node, 'postgres', "SELECT phase = 'copying live blocks' " . "FROM pg_stat_progress_cfs_compact WHERE relid = $stop_oid"), 'automatic compaction of stop_t reached its copy phase'); # The progress row must identify the database the worker is working # in (vanilla pg_stat_progress_* columns: pid, datid, datname, relid). is( $node->safe_psql( 'postgres', "SELECT datid = (SELECT oid FROM pg_database WHERE datname = 'postgres'), datname " . "FROM pg_stat_progress_cfs_compact WHERE relid = $stop_oid"), "t|postgres", 'progress row reports the database of the compaction'); # started_at must be the correct absolute moment regardless of the # session zone (param4 is a TimestampTz, microseconds since # 2000-01-01 UTC). is( $node->safe_psql( 'postgres', "SET TimeZone='Europe/Moscow'; " . "SELECT started_at <= clock_timestamp(), " . "started_at > now() - interval '1 hour' " . "FROM pg_stat_progress_cfs_compact WHERE relid = $stop_oid"), "t|t", 'started_at is a sane absolute time in a non-UTC session'); my $log_offset = -s $node->logfile; my $t0 = time(); $node->stop('fast'); my $elapsed = time() - $t0; cmp_ok($elapsed, '<', 5, "fast shutdown does not wait out the copy loop (${elapsed}s)"); my $log = slurp_file($node->logfile, $log_offset); unlike( $log, qr/compaction complete for relation $stop_oid:/, 'no compaction completion is logged after the shutdown request'); like( $log, qr/terminating background worker ".*" due to administrator command/, 'worker aborted with the administrator-command FATAL'); # --- Phase 2: the shutdown lands inside the lock-wait loop ----------- $node->start; # Pause before any pass can pick stop_t up again (its interrupted # compaction left the dead bytes in place, and its 16 s stretched copy # would delay the phase) and retire it. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); $node->safe_psql('postgres', 'DROP TABLE stop_t'); fragment_table($node, 'postgres', 'stop2_t', 'sq'); my $locker = $node->background_psql('postgres', on_error_stop => 1); $locker->query_until(qr/LOCK2-READY/m, "BEGIN;\nLOCK TABLE stop2_t IN ACCESS EXCLUSIVE MODE;\nSELECT 'LOCK2-READY';\n" ); $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume()"); # The worker polls for the lock (its wait event proves it), so the # shutdown below lands inside the lock-wait loop. my $lock_seen = 0; my $deadline = time() + 10; while (time() < $deadline) { my $ev = $node->safe_psql('postgres', "SELECT wait_event FROM pg_stat_activity " . "WHERE backend_type LIKE 'CFS background compaction worker for database%'" ); if ($ev eq 'CfsBgworkerLock') { $lock_seen = 1; last; } $node->safe_psql('postgres', "SELECT pg_sleep(0.1)"); } ok($lock_seen, 'worker is polling for the lock of the contended candidate'); $log_offset = -s $node->logfile; $t0 = time(); $node->stop('fast'); $elapsed = time() - $t0; cmp_ok($elapsed, '<', 5, "fast shutdown during the lock wait is prompt (${elapsed}s)"); $log = slurp_file($node->logfile, $log_offset); like( $log, qr/terminating background worker ".*" due to administrator command/, 'lock-waiting worker exits with the administrator-command FATAL'); # The locker session dies with the node; quitting it afterwards is # best-effort only. eval { $locker->quit; }; }; # --------------------------------------------------------------------------- # A config reload storm must not postpone the worker schedule. # # The autovacuum launcher stores the time of the next scheduled run and, # after any signal wake, sleeps only the REMAINING part of the nap ("We # sleep until the next scheduled vacuum", launcher_determine_sleep). The # CFS launcher restarted the whole cfs_bg_period_ms after every # non-timeout wake, so a config-reloading observer (an HA agent re-reading # the config every few seconds) could postpone automatic compaction # indefinitely. # --------------------------------------------------------------------------- subtest 'a reload storm does not postpone the worker schedule' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_schedule'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 5000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS schedule test'; } # Baseline: wait for the first completed cycle. ok( wait_for( $node, 'postgres', "SELECT last_cycle_finished_at IS NOT NULL " . "FROM pg_cfs_bgworker_status()"), 'first worker cycle completed'); my $finished_at = $node->safe_psql('postgres', "SELECT last_cycle_finished_at::text FROM pg_cfs_bgworker_status()"); # Reload storm: 8 reloads ~1.5 s apart over ~12 s, each interval well # inside the 5 s period. The schedule is watched while the storm is # still running: a broken launcher only re-arms the full period, so its # first post-storm cycle lands after the storm ends and must not be # counted. my $advanced = 0; foreach (1 .. 8) { $node->safe_psql('postgres', "SELECT pg_reload_conf()"); $node->safe_psql('postgres', "SELECT pg_sleep(1.5)"); my $now = $node->safe_psql('postgres', "SELECT last_cycle_finished_at::text FROM pg_cfs_bgworker_status()" ); $advanced = 1 if $now ne '' && $now ne $finished_at; } ok($advanced, 'worker cycles keep completing through a config reload storm'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A paused launcher must sleep out the period, not spin. # # The reload-storm fix above taught the launcher to wait only the REMAINDER # of the period after a stray wake. The paused pass, however, left the # schedule in the past: the remainder was 0, WaitLatch(0) returned # instantly, and the launcher entered a busy loop -- a full transactional # iteration with the exclusive cfs_bg_lock taken at machine speed for the # whole (possibly indefinite) pause, pinning one CPU core. Vanilla never # spins: the canlaunch == false branch of launcher_determine_sleep() # assigns the FULL autovacuum_naptime instead of any remainder. A paused # pass must therefore re-arm the full cfs_bg_period_ms, exactly like that # branch. # --------------------------------------------------------------------------- subtest 'a paused launcher sleeps out the period instead of spinning' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_pause_sleep'); $node->init; # A long period keeps the sampling window below deterministic. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 8000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS paused-launcher test'; } # Baseline: the first scheduled cycle completes and stamps # last_cycle_started_at. ok( wait_for( $node, 'postgres', "SELECT last_cycle_started_at IS NOT NULL " . "FROM pg_cfs_bgworker_status()"), 'first worker cycle completed'); my $baseline = $node->safe_psql('postgres', "SELECT last_cycle_started_at::text FROM pg_cfs_bgworker_status()"); # Indefinite pause: the next scheduled pass becomes a paused pass -- # wait for it to happen (at most one period plus polling away). $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); ok( wait_for( $node, 'postgres', "SELECT last_cycle_started_at::text <> '$baseline' " . "AND last_cycle_started_at IS NOT NULL " . "FROM pg_cfs_bgworker_status()"), 'paused pass observed'); # While paused, the launcher sits out the full period in its main # sleep: the wait event must be CfsBgworkerMain (Activity), like the # autovacuum launcher's AutoVacuumMain, not the semantically wrong # BgWorkerShutdown it used to borrow. Sampled through a wait_for # because the paused pass itself takes only milliseconds. ok( wait_for( $node, 'postgres', "SELECT wait_event = 'CfsBgworkerMain' " . "AND wait_event_type = 'Activity' " . "FROM pg_stat_activity " . "WHERE backend_type = 'CFS background compaction worker'"), 'paused launcher waits with CfsBgworkerMain'); # From the paused pass on, the launcher must sit in its full-period # sleep: last_cycle_started_at is frozen until the next period # boundary, which is a whole cfs_bg_period_ms away. A spinning # launcher refreshes the stamp within milliseconds. my $sample1 = $node->safe_psql('postgres', "SELECT last_cycle_started_at::text FROM pg_cfs_bgworker_status()"); $node->safe_psql('postgres', 'SELECT pg_sleep(3)'); my $sample2 = $node->safe_psql('postgres', "SELECT last_cycle_started_at::text FROM pg_cfs_bgworker_status()"); is($sample2, $sample1, 'paused launcher sleeps out the period instead of spinning'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # The candidate ratio measures current fragmentation, not lifetime writes. # # The autovacuum threshold divides the dead-tuple count by the CURRENT # table size (reltuples), never by "every row ever inserted", so a heavily # rewritten table keeps being vacuumed. The CFS worker divided dead_bytes # by the lifetime sum of everything ever written (only the numerator # resets on compaction), so the ratio decayed towards the steady dead # share of writes: an actively written table whose dead share of writes is # below the threshold never crossed it again, its dead space grew without # bound, and automatic compaction silently stopped picking it up. # --------------------------------------------------------------------------- subtest 'candidate ratio measures current fragmentation' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_decay'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 10"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS decay test'; } # Run up the lifetime denominator with compaction cycles: every round # rewrites the table and compacts it, so the cumulative counters keep # growing while the payload file stays about one version large. The # threshold is then derived from the MEASURED current fragmentation # (dead bytes from pg_stat_cfs, payload chain size from the file # system), five points below it: compaction must trigger at that # threshold, while the lifetime-based ratio -- the cumulative counters # over eight written versions -- sits far below it. Measuring instead # of assuming fixed ratios keeps the test independent of how the # payload data happens to compress. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); $node->safe_psql('postgres', "CREATE TABLE decay_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO decay_t SELECT g, repeat('DC' || g, 200) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', 'CHECKPOINT'); foreach (1 .. 7) { $node->safe_psql('postgres', "UPDATE decay_t SET payload = repeat('DC' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "SELECT pg_cfs_compact('decay_t')"); } # One more full rewrite, left un-compacted: this is the fragmentation # the worker must act on. $node->safe_psql('postgres', "UPDATE decay_t SET payload = repeat('DC' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $dead = $node->safe_psql('postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'decay_t'"); my $relpath = $node->safe_psql('postgres', "SELECT pg_relation_filepath('decay_t')"); my $datadir = $node->data_dir; my $cfp_size = 0; for (my $seg = 0;; $seg++) { my $path = $seg == 0 ? "$datadir/$relpath.cfp" : "$datadir/$relpath.cfp.$seg"; last unless -e $path; $cfp_size += -s $path; } die "unexpected zero dead bytes or payload size" if $dead <= 0 || $cfp_size <= 0; my $ratio_now = int($dead * 100 / $cfp_size); my $threshold = $ratio_now > 6 ? $ratio_now - 5 : 1; note( "dead=$dead cfp=$cfp_size ratio=${ratio_now}% " . "threshold=$threshold%"); $node->safe_psql('postgres', "ALTER SYSTEM SET cfs_bg_threshold = $threshold"); $node->safe_psql('postgres', "SELECT pg_reload_conf()"); $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume()"); my $oid = $node->safe_psql('postgres', "SELECT 'decay_t'::regclass::oid"); my $log_offset = -s $node->logfile; my $compacted = 0; my $deadline = time() + 8; while (time() < $deadline) { my $log = slurp_file($node->logfile, $log_offset); if ($log =~ /compaction complete for relation $oid:/) { $compacted = 1; last; } $node->safe_psql('postgres', "SELECT pg_sleep(0.2)"); } ok($compacted, 'worker compacts a table whose payload is a quarter dead while its lifetime share is far below the threshold' ); is($node->safe_psql('postgres', "SELECT count(*) FROM decay_t"), 500, 'decay_t intact after the compaction'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Dead-space counters survive a clean restart. # # Since PG15 vanilla persists its statistics at a regular shutdown and # restores them at startup (pgstat_before_server_shutdown / # pgstat_restore_stats), an autovacuum-relevant counter survives a # maintenance restart. The CFS counters lived in shared memory only, so # fragmentation accumulated before a restart was invisible forever: # dead_bytes came back as 0 and the worker dropped the candidate before # even looking at the threshold. # --------------------------------------------------------------------------- subtest 'dead-space counters survive a clean restart' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_restart'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 10"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS restart test'; } # Fragment while the automatic worker is paused: the fragmentation may # only be picked up after the restart. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); fragment_table($node, 'postgres', 'restart_t', 'rs'); my $oid = $node->safe_psql('postgres', "SELECT 'restart_t'::regclass::oid"); my $log_offset = -s $node->logfile; # A clean restart (the pause flag lives in shared memory and does not # survive it either). $node->stop('fast'); $node->start; # The worker must see the pre-restart fragmentation and compact it. my $compacted = 0; my $deadline = time() + 10; while (time() < $deadline) { my $log = slurp_file($node->logfile, $log_offset); if ($log =~ /compaction complete for relation $oid:/) { $compacted = 1; last; } $node->safe_psql('postgres', "SELECT pg_sleep(0.2)"); } ok($compacted, 'worker compacts fragmentation accumulated before a restart'); is($node->safe_psql('postgres', "SELECT count(*) FROM restart_t"), 500, 'restart_t intact after the compaction'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A crash restart must not leave the worker blind to fragmentation that # predated the crash (QDB-1507, U1). # # The stats file is written only on a clean shutdown, so a crash restores the # snapshot from the previous clean stop. Recovery folds the journal into the # map (publishing no statistics by design), and the first checkpoint then # republishes the stale base with an empty delta: dead_bytes stays at its # pre-crash value (0 here) and the worker drops the candidate before even # looking at the threshold. The first measurement after a crash restart must # resync dead_bytes from the map instead. # --------------------------------------------------------------------------- subtest 'worker compacts fragmentation that predates a crash restart' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_crash'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 10"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS crash test'; } # Phase 1: a CFS table with no dead space yet. The clean stop below # persists a stats snapshot with dead_bytes = 0. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); $node->safe_psql('postgres', "CREATE TABLE crash_t (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO crash_t SELECT g, repeat('cr' || g, 200) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->stop('fast'); # Phase 2: fragment while the (restarted, still paused) worker cannot # see it, checkpoint the churn into the map, then crash. The stats # file on disk keeps the phase-1 snapshot with dead_bytes = 0. $node->start; $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); $node->safe_psql('postgres', "UPDATE crash_t SET payload = repeat('CR' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); my $dead_before = $node->safe_psql('postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relid = 'crash_t'::regclass"); ok($dead_before > 0, 'dead space is live in shared memory before the crash'); # crash_t2: created after the phase-1 clean stop, so it has no entry # in the restored stats file at all (its slot will be created fresh # after the restart). The checkpoints after its INSERT and UPDATE # are required: a relation whose Storage/CREATE WAL record stays # after the last checkpoint has its sidecars wiped and rebuilt by the # redo of that record, so without them the recovery fold would leave # no dead space at all and there would be nothing to resync. $node->safe_psql('postgres', "CREATE TABLE crash_t2 (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO crash_t2 SELECT g, repeat('c2' || g, 200) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE crash_t2 SET payload = repeat('C2' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->stop('immediate'); # Phase 3: the crash restart restores the stale snapshot (dead_bytes = 0 # in the file); the resumed worker must resync from the map and compact # both the restored relation and the one absent from the file. $node->start; my $oid = $node->safe_psql('postgres', "SELECT 'crash_t'::regclass::oid"); my $oid2 = $node->safe_psql('postgres', "SELECT 'crash_t2'::regclass::oid"); my $log_offset = -s $node->logfile; my $compacted = 0; my $compacted2 = 0; my $deadline = time() + 15; while (time() < $deadline && (!$compacted || !$compacted2)) { my $log = slurp_file($node->logfile, $log_offset); if (!$compacted && $log =~ /compaction complete for relation $oid:/) { $compacted = 1; } if (!$compacted2 && $log =~ /compaction complete for relation $oid2:/) { $compacted2 = 1; } last if ($compacted && $compacted2); $node->safe_psql('postgres', "SELECT pg_sleep(0.2)"); } ok($compacted, 'worker compacts fragmentation that predates a crash restart'); ok($compacted2, 'worker resyncs a relation absent from the restored stats file'); is($node->safe_psql('postgres', "SELECT count(*) FROM crash_t"), 500, 'crash_t intact after the compaction'); is($node->safe_psql('postgres', "SELECT count(*) FROM crash_t2"), 200, 'crash_t2 intact after the compaction'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # The compaction history throttles every relation, not a fixed ring. # # Vanilla keeps per-relation "last autovacuum time" entries without any # count cap (PgStat_StatTabEntry.last_autovac_time in a shared hash). The # CFS worker kept a ring of 128 entries that overwrote slot 0 regardless # of recency, so with more relations than slots the cfs_bg_min_interval_s # guarantee silently did not hold for the evicted ones. 130 relations # with deterministic compaction failures exceed the ring by two: the two # evicted entries are retried on the next cycle, a per-relation hash # retries none. # --------------------------------------------------------------------------- subtest 'compaction history throttles every relation' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_history'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 2000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 86400"); $node->append_conf('postgresql.conf', "cfs_bg_threshold = 1"); $node->append_conf('postgresql.conf', "cfs_bg_max_relations = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_delay_ms = 1"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS history test'; } # 130 fragmented CFS tables, created while the worker is paused, each # with a directory obstacle at its .cfp.tmp path: every compaction # attempt fails deterministically, and failures are throttled by the # history exactly like successes. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause()"); $node->safe_psql('postgres', <<'SQL'); DO $do$ DECLARE i int; BEGIN FOR i IN 1..130 LOOP EXECUTE format('CREATE TABLE hist_%s (id int, payload text) WITH (algorithm = ''lz4'')', i); EXECUTE format('INSERT INTO hist_%s SELECT g, repeat(''h'' || g, 50) FROM generate_series(1, 20) g', i); END LOOP; END $do$ SQL $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', <<'SQL'); DO $do$ DECLARE i int; BEGIN FOR i IN 1..130 LOOP EXECUTE format('UPDATE hist_%s SET payload = repeat(''H'' || id, 50)', i); END LOOP; END $do$ SQL $node->safe_psql('postgres', 'CHECKPOINT'); my $dd = $node->data_dir; foreach my $i (1 .. 130) { my $p = $node->safe_psql('postgres', "SELECT pg_relation_filepath('hist_$i')"); mkdir("$dd/$p.cfp.tmp") or die "could not plant obstacle for hist_$i: $!"; } my $log_offset = -s $node->logfile; $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume()"); # Cycle 1: every relation is attempted exactly once. my $deadline = time() + 30; my $count = 0; while (time() < $deadline) { my $log = slurp_file($node->logfile, $log_offset); $count = () = $log =~ /CFS: compaction: could not create/g; last if $count >= 130; $node->safe_psql('postgres', "SELECT pg_sleep(0.2)"); } cmp_ok($count, '>=', 130, 'first pass attempted all 130 relations'); # Later cycles within the 86400 s interval must attempt none of them # again. Wait out two full periods before judging. $node->safe_psql('postgres', "SELECT pg_sleep(5)"); my $log = slurp_file($node->logfile, $log_offset); $count = () = $log =~ /CFS: compaction: could not create/g; is($count, 130, 'no relation is retried within the minimum interval'); $node->stop('fast'); }; # Fragment a CFS table: two flushed versions of every row leave about half # of the bytes dead, far above the default cfs_bg_threshold of 10%. sub fragment_table { my ($node, $dbname, $tbl, $tag) = @_; $node->safe_psql($dbname, "CREATE TABLE $tbl (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql($dbname, "INSERT INTO $tbl SELECT g, repeat('$tag' || g, 200) " . "FROM generate_series(1, 500) g"); $node->safe_psql($dbname, 'CHECKPOINT'); my $tag_uc = uc($tag); $node->safe_psql($dbname, "UPDATE $tbl SET payload = repeat('$tag_uc' || id, 200)"); $node->safe_psql($dbname, 'CHECKPOINT'); } # poll_query_until() of this fork takes no per-call timeout argument and # polls for $timeout_default seconds; give the asynchronous compaction a # generous fixed budget of 120 s. sub wait_for { my ($node, $dbname, $query) = @_; local $PostgreSQL::Test::Utils::timeout_default = 120; return $node->poll_query_until($dbname, $query); } # --------------------------------------------------------------------------- # Background worker coverage of every database of the cluster. # # The compaction worker connects to a single database at a time, so the # automatic compaction must not stop at the first database it looks at: # a fragmented CFS table in any database must be auto-compacted, not only # one living in the bootstrap "postgres" database, and dropping a database # must not kill the worker -- the remaining databases must keep being # compacted afterwards. # --------------------------------------------------------------------------- subtest 'background worker covers every database of the cluster' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_multidb'); $node->init; # Fast worker cycles, no per-relation backoff. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping multi-database CFS bgworker test'; } fragment_table($node, 'postgres', 'ctl_t', 'ctl'); $node->safe_psql('postgres', 'CREATE DATABASE cfs_bg_db1'); $node->safe_psql('postgres', 'CREATE DATABASE cfs_bg_db2'); fragment_table($node, 'cfs_bg_db1', 't1', 'd1'); fragment_table($node, 'cfs_bg_db2', 't2', 'd2'); my $ck_ctl = table_checksum($node, 'ctl_t'); my $ck_t1 = $node->safe_psql('cfs_bg_db1', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t1"); my $ck_t2 = $node->safe_psql('cfs_bg_db2', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t2"); ok( wait_for( $node, 'postgres', "SELECT last_compaction IS NOT NULL FROM pg_stat_cfs " . "WHERE relname = 'ctl_t'"), 'auto-compaction reached ctl_t in postgres'); ok( wait_for( $node, 'cfs_bg_db1', "SELECT last_compaction IS NOT NULL FROM pg_stat_cfs " . "WHERE relname = 't1'"), 'auto-compaction reached t1 in cfs_bg_db1'); ok( wait_for( $node, 'cfs_bg_db2', "SELECT last_compaction IS NOT NULL FROM pg_stat_cfs " . "WHERE relname = 't2'"), 'auto-compaction reached t2 in cfs_bg_db2'); is($node->safe_psql('postgres', 'SELECT count(*) FROM ctl_t'), 500, 'ctl_t kept all rows after auto-compaction'); is(table_checksum($node, 'ctl_t'), $ck_ctl, 'ctl_t data intact after auto-compaction'); is($node->safe_psql('cfs_bg_db1', 'SELECT count(*) FROM t1'), 500, 't1 kept all rows after auto-compaction'); is( $node->safe_psql( 'cfs_bg_db1', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t1"), $ck_t1, 't1 data intact after auto-compaction'); is($node->safe_psql('cfs_bg_db2', 'SELECT count(*) FROM t2'), 500, 't2 kept all rows after auto-compaction'); is( $node->safe_psql( 'cfs_bg_db2', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t2"), $ck_t2, 't2 data intact after auto-compaction'); # A freshly fragmented database is dropped right away -- the race with # the worker cycle is natural, and whichever way it goes the cluster # must stay alive and keep compacting the remaining databases. $node->safe_psql('postgres', 'CREATE DATABASE cfs_bg_db3'); fragment_table($node, 'cfs_bg_db3', 't3', 'd3'); # WITH (FORCE) keeps the outcome deterministic: the drop must succeed # even when a compaction worker is momentarily connected to the # database, and the worker must survive the drop either way. $node->safe_psql('postgres', 'DROP DATABASE cfs_bg_db3 WITH (FORCE)'); is($node->safe_psql('postgres', 'SELECT 1'), '1', 'server responds after DROP DATABASE'); # Re-fragment t1: cfs_bg_min_interval_s is 0, so a second compaction # is allowed, and dead_bytes only returns to 0 once the worker # actually compacts the relation again. $node->safe_psql('cfs_bg_db1', "UPDATE t1 SET payload = repeat('x1' || id, 200)"); $node->safe_psql('cfs_bg_db1', 'CHECKPOINT'); my $ck_t1_second = $node->safe_psql('cfs_bg_db1', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t1"); ok( wait_for( $node, 'cfs_bg_db1', "SELECT dead_bytes = 0 FROM pg_stat_cfs WHERE relname = 't1'"), 'auto-compaction of cfs_bg_db1 continued after the drop'); is($node->safe_psql('cfs_bg_db1', 'SELECT count(*) FROM t1'), 500, 't1 kept all rows after the second auto-compaction'); is( $node->safe_psql( 'cfs_bg_db1', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t1"), $ck_t1_second, 't1 data intact after the second auto-compaction'); $node->stop('immediate'); }; # --------------------------------------------------------------------------- # Worker survives in a cluster without the postgres database. # # After postgres itself is dropped, every access goes through keeper and # workdb only; the automatic compaction must still reach a fragmented CFS # table in workdb. # --------------------------------------------------------------------------- subtest 'background worker survives a cluster without the postgres database' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_bg_nopg'); $node->init; # Fast worker cycles, no per-relation backoff. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 1000"); $node->append_conf('postgresql.conf', "cfs_bg_min_interval_s = 0"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping no-postgres-database bgworker test'; } $node->safe_psql('postgres', 'CREATE DATABASE keeper'); $node->safe_psql('postgres', 'CREATE DATABASE workdb'); # A short-lived per-database compaction worker may be momentarily # connected to postgres when the drop lands, so WITH (FORCE) keeps the # outcome deterministic; the drop itself is issued from keeper # (postgres cannot drop itself), and after it every access goes through # keeper/workdb only. $node->safe_psql('keeper', 'DROP DATABASE postgres WITH (FORCE)'); is($node->safe_psql('keeper', 'SELECT 1'), '1', 'server responds via keeper after postgres was dropped'); fragment_table($node, 'workdb', 't4', 'w4'); my $ck_t4 = $node->safe_psql('workdb', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t4"); ok( wait_for( $node, 'workdb', "SELECT last_compaction IS NOT NULL FROM pg_stat_cfs " . "WHERE relname = 't4'"), 'auto-compaction works without the postgres database'); is($node->safe_psql('workdb', 'SELECT count(*) FROM t4'), 500, 't4 kept all rows after auto-compaction'); is( $node->safe_psql( 'workdb', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM t4"), $ck_t4, 't4 data intact after auto-compaction'); $node->stop('immediate'); }; # --------------------------------------------------------------------------- # TRUNCATE and bulk extend through a stale handle. # # A backend whose smgr cache still holds a CfsRelation handle from before # another session's pg_cfs_compact() must not journal TRUNCATE / bulk extend # through the stale handle: the swap unlinked the old sidecar inodes, so a # RESIZE record written there is lost, and after a crash the truncated rows # resurrect. cfs_smgr_truncate() and cfs_smgr_zeroextend() refresh the # stale handle under the append lock before journaling. # --------------------------------------------------------------------------- subtest 'truncate and zero-extend through a stale handle' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_stale_h'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; # Skip when LZ4 is not compiled in. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping stale-handle truncate test'; } # --- Phase 1: TRUNCATE through a handle cached before the swap -------- $node->safe_psql('postgres', "CREATE TABLE cfs_st (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO cfs_st SELECT g, repeat('s' || g, 200) " . "FROM generate_series(1, 2000) g"); $node->safe_psql('postgres', 'CHECKPOINT'); # Two flushed versions of every page: dead space for the compactor. $node->safe_psql('postgres', "UPDATE cfs_st SET payload = repeat('t' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); # Restart so the table pages leave shared_buffers: the session below # must really read through the CFS smgr path and cache its handle. $node->stop('fast'); $node->start; # Session A opens (and caches) its CfsRelation handle here. my $session1 = $node->background_psql('postgres', on_error_stop => 1); $session1->query_until(qr/stale-ready/m, "SELECT id, 'stale-ready' FROM cfs_st ORDER BY id LIMIT 1;\n"); # The read-back oracle from a fresh backend (its own handle). my $ck_before_swap = table_checksum($node, 'cfs_st'); # Another session compacts the relation: the sidecar files are swapped, # session A's cached handle is now stale. $node->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_st')"); # Session A reads the whole table through the stale handle: the read # path must reopen onto the new sidecar pair (cfs_handle_refresh_if_stale # under a shared append lock) instead of decompressing through the old # descriptors and offsets, so the digest must match the fresh-backend # oracle. A mismatch never prints the banner and fails the test by # timeout. $session1->query_until(qr/stale-read-ok/m, "SELECT CASE WHEN md5(string_agg(payload, '' ORDER BY id)) " . "= '$ck_before_swap' THEN 'stale-read-ok' END FROM cfs_st;\n"); # Session A truncates through the stale handle. A checkpoint then # persists the on-disk state, and the crash-restart below must not # resurrect the truncated rows. $session1->query_until(qr/TRUNCATE_DONE/m, "TRUNCATE cfs_st; SELECT 'TRUNCATE_DONE';\n"); $session1->quit; $node->safe_psql('postgres', 'CHECKPOINT'); $node->stop('immediate'); $node->start; is($node->safe_psql('postgres', "SELECT count(*) FROM cfs_st"), '0', 'TRUNCATE survived a crash after a compaction swap'); # --- Phase 2: bulk extend through a handle cached before the swap ----- $node->safe_psql('postgres', "INSERT INTO cfs_st SELECT g, repeat('e' || g, 200) " . "FROM generate_series(1, 3000) g"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "UPDATE cfs_st SET payload = repeat('f' || id, 200)"); $node->safe_psql('postgres', 'CHECKPOINT'); $node->stop('fast'); $node->start; my $session2 = $node->background_psql('postgres', on_error_stop => 1); $session2->query_until(qr/extend-ready/m, "SELECT id, 'extend-ready' FROM cfs_st ORDER BY id LIMIT 1;\n"); $node->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_st')"); # Session A bulk-extends the relation through the stale handle; the # RESIZE of the extend must be journalled through the refreshed handle. $session2->query_until(qr/extend-done/m, "INSERT INTO cfs_st SELECT g, repeat('n' || g, 200) " . "FROM generate_series(3001, 6000) g; " . "SELECT 'extend-done';\n"); $session2->quit; my $ck_extended = table_checksum($node, 'cfs_st'); $node->safe_psql('postgres', 'CHECKPOINT'); $node->stop('immediate'); $node->start; is($node->safe_psql('postgres', "SELECT count(*) FROM cfs_st"), '6000', 'rows bulk-inserted through a stale handle survived a crash'); is(table_checksum($node, 'cfs_st'), $ck_extended, 'data bulk-inserted through a stale handle is intact after a crash'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Startup cleanup removes only CFS-named temp files # # The startup scan cleans up ".tmp" and ".new" files left by interrupted # compactions. The cleanup must match the strict CFS sidecar name # template (a .cfp / .cfp.N / .cfsmap base): a foreign file that merely # shares the suffix (an editor backup, an administrator's scratch file) # must be left in place, exactly like vanilla's startup cleanups only # remove files matching the names the server itself creates. # --------------------------------------------------------------------------- subtest 'startup cleanup removes only CFS-named temp files' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_tmpl'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min"); $node->start; my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS temp-name template test'; } $node->safe_psql('postgres', "CREATE TABLE tmpl_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO tmpl_t SELECT g, repeat('m' || g, 80) " . "FROM generate_series(1, 100) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $dd = $node->data_dir; my $dboid = $node->safe_psql('postgres', "SELECT oid FROM pg_database WHERE datname = 'postgres'"); my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('tmpl_t')"); my $dbdir = "$dd/base/$dboid"; $node->stop('fast'); # Foreign files that merely share the transient suffixes. open my $f1, '>', "$dbdir/zz_not_cfs.tmp" or die $!; close $f1; open my $f2, '>', "$dbdir/zz_stray.new" or die $!; close $f2; # Foreign files shaped like a sidecar segment 0: the engine numbers # segments from 1, so ".cfp.0." is not an engine name. The # .tmp and .new branches must treat them identically. open my $f4, '>', "$dbdir/987654.cfp.0.tmp" or die $!; close $f4; open my $f5, '>', "$dbdir/987654.cfp.0.new" or die $!; close $f5; # Control: a genuine orphan compaction candidate (sidecar base, no # commit marker) — the scan must still remove this one. open my $f3, '>', "$dd/$rel_path.cfp.new" or die $!; close $f3; my $log_off = -s $node->logfile; $node->start; ok(-f "$dbdir/zz_not_cfs.tmp", 'foreign .tmp file is left in place'); ok(-f "$dbdir/zz_stray.new", 'foreign .new file is left in place'); ok(-f "$dbdir/987654.cfp.0.tmp", 'foreign segment-0 .cfp.0.tmp file is left in place'); ok(-f "$dbdir/987654.cfp.0.new", 'foreign segment-0 .cfp.0.new file is left in place'); ok(!-f "$dd/$rel_path.cfp.new", 'genuine orphan compaction candidate is removed'); my $log = PostgreSQL::Test::Utils::slurp_file($node->logfile, $log_off); unlike($log, qr/zz_not_cfs\.tmp/, 'no cleanup message for the foreign .tmp file'); unlike($log, qr/zz_stray\.new/, 'no cleanup message for the foreign .new file'); unlike($log, qr/987654\.cfp\.0/, 'no cleanup message for the foreign segment-0 files'); like( $log, qr/removed orphan compaction candidate.*cfp\.new/, 'genuine candidate removal is logged'); is($node->safe_psql('postgres', "SELECT count(*) FROM tmpl_t"), '100', 'CFS table intact after the scan'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A hard activation failure keeps the swap marker in place # # Completing an interrupted compaction swap is a durability operation: if # the activation rename fails with a persistent error (EISDIR / EACCES / # EROFS from a broken filesystem object), the failure must be a hard # ERROR, the commit marker must stay on disk and none of the follow-up # steps (map rename, trailing cleanup, journal reset, marker unlink) may # run — otherwise the pair is left half-swapped while looking completed, # and the promised idempotent retry has nothing left to retry. Vanilla # durability operations never mark work done when the work failed. # # The failure is emulated deterministically by replacing the target .cfp # with a directory: rename(file, dir) fails with EISDIR. # --------------------------------------------------------------------------- subtest 'a hard activation failure keeps the swap marker' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_swap_err'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min"); $node->start; my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/) { plan skip_all => 'LZ4 support not built, skipping CFS swap activation failure test'; } $node->safe_psql('postgres', "CREATE TABLE swap_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO swap_t SELECT g, repeat('a' || g, 80) " . "FROM generate_series(1, 100) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $dd = $node->data_dir; my $rel_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('swap_t')"); my $cfp = "$dd/$rel_path.cfp"; my $cfp_new = "$cfp.new"; my $cfsmap_new = "$dd/$rel_path.cfsmap.new"; my $marker = "$cfp.cfsswap"; $node->stop('fast'); # Emulate the crash-after-commit state: durable candidate pair plus the # commit marker. { open my $src, '<:raw', $cfp or die "open $cfp: $!"; local $/; my $blob = <$src>; close $src; open my $dst, '>:raw', $cfp_new or die "open $cfp_new: $!"; print $dst $blob; close $dst; } { my $map_src = "$dd/$rel_path.cfsmap"; open my $src, '<:raw', $map_src or die "open $map_src: $!"; local $/; my $blob = <$src>; close $src; open my $dst, '>:raw', $cfsmap_new or die "open $cfsmap_new: $!"; print $dst $blob; close $dst; } open my $mf, '>', $marker or die $!; close $mf; # Break the activation: the target .cfp becomes a directory, so the # candidate rename fails with EISDIR. unlink($cfp); mkdir($cfp) or die "mkdir $cfp: $!"; pass('target .cfp replaced with a directory'); my $log_off = -s $node->logfile; my $started = $node->start(fail_ok => 1); ok(!$started, 'server does NOT start when the swap cannot activate'); $node->log_check('activation failure message', $log_off, log_like => [qr/could not activate/i]); # The marker and the candidates survive: the retry contract is intact. ok(-f $marker, 'swap marker is kept after the failed activation'); ok(-f $cfp_new, 'candidate .cfp.new is kept after the failure'); ok(-f $cfsmap_new, 'candidate .cfsmap.new is kept after the failure'); }; # --------------------------------------------------------------------------- # A compaction interleaving with the checkpoint's fold owns the relation's # dead-space counters. The checkpoint used to publish them in phase 1 from # its stale pre-swap map, undoing the compaction's reset; the publication now # happens in phase 2, after the incarnation and generation checks skip the # reset for the swapped pair. # # The fold is parked on the injection point cfs-checkpoint-fold-row after its # first applied row; the compaction runs while it is parked. # --------------------------------------------------------------------------- subtest 'a compaction interleaving with the fold keeps its counters' => 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_fold_compact'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->start; if (!$node->check_extension('injection_points')) { plan skip_all => 'Extension injection_points not installed'; } $node->safe_psql( 'postgres', q{ CREATE TABLE fc_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO fc_t SELECT g, repeat('a' || g, 200) FROM generate_series(1, 2000) g; CHECKPOINT; UPDATE fc_t SET payload = repeat('b' || id, 200); CHECKPOINT; }); # Real dead space for the compaction to reclaim (the payload pattern of # the candidate-selection subtest above). cmp_ok( $node->safe_psql( 'postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'fc_t'"), '>', 0, 'the relation starts with dead space'); # One more rewrite feeds the fold, and the compaction runs while the # checkpointer is parked in the middle of it: phase 1 holds no append # lock, so the compaction swaps the pair, resets the journal and zeroes # the counters while the fold is still parked. $node->safe_psql('postgres', "UPDATE fc_t SET payload = repeat('c' || id, 200)"); $node->safe_psql('postgres', 'CREATE EXTENSION injection_points'); $node->safe_psql('postgres', "SELECT injection_points_attach('cfs-checkpoint-fold-row', 'wait')"); my $bg = $node->background_psql('postgres', timeout => 180); $bg->query_until(qr/FOLD_STARTED/, "\\echo 'FOLD_STARTED'\n" . "CHECKPOINT;\n"); $node->wait_for_event('checkpointer', 'cfs-checkpoint-fold-row'); $node->safe_psql('postgres', "SELECT pg_cfs_compact('fc_t')"); $node->safe_psql('postgres', "SELECT injection_points_wakeup('cfs-checkpoint-fold-row')"); $bg->query_until(qr/FOLD_DONE/, "SELECT 'FOLD_DONE';\n"); $bg->quit; $node->safe_psql('postgres', "SELECT injection_points_detach('cfs-checkpoint-fold-row')"); is( $node->safe_psql( 'postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'fc_t'"), '0', 'the interleaved compaction keeps its dead_bytes reset'); is($node->safe_psql('postgres', 'SELECT count(*) FROM fc_t'), '2000', 'the data is intact after the interleaving'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A checkpoint opening a handle while a compaction is staged (candidates # written, commit marker not yet) must not race into the swap: the open # takes the append lock conditionally, finds it held by the compaction, # and skips the relation for one round instead of running the # interrupted-swap recovery over the half-staged candidate pair. # # The compaction is parked on the injection point cfs-compaction-staged, # placed after the candidate pair is staged and before the commit marker # is written - the exact window the review named. # --------------------------------------------------------------------------- subtest 'a checkpoint during a staged compaction skips the relation' => 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_staged_ckpt'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->start; if (!$node->check_extension('injection_points')) { plan skip_all => 'Extension injection_points not installed'; } $node->safe_psql( 'postgres', q{ CREATE TABLE sc_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO sc_t SELECT g, repeat('a' || g, 200) FROM generate_series(1, 2000) g; CHECKPOINT; UPDATE sc_t SET payload = repeat('b' || id, 200); CHECKPOINT; }); $node->safe_psql('postgres', 'CREATE EXTENSION injection_points'); $node->safe_psql('postgres', "SELECT injection_points_attach('cfs-compaction-staged', 'wait')"); # Park the compaction in the staged window; it holds the append lock # for its whole copy + swap. my $bg = $node->background_psql('postgres', timeout => 180); $bg->query_until(qr/COMPACT_STARTED/, "\\echo 'COMPACT_STARTED'\n" . "SELECT pg_cfs_compact('sc_t');\n"); $node->wait_for_event('client backend', 'cfs-compaction-staged'); # The checkpoint the review scenario is about: it must succeed, skip # the parked relation (its dirty mark is untouched) and above all must # not run the swap recovery over the staged candidates. $node->safe_psql('postgres', 'CHECKPOINT'); # Let the compaction finish its swap; the skipped relation is picked # up by the next checkpoint, which folds and resets the new journal. $node->safe_psql('postgres', "SELECT injection_points_wakeup('cfs-compaction-staged')"); $bg->query_until(qr/COMPACT_DONE/, "SELECT 'COMPACT_DONE';\n"); $bg->quit; $node->safe_psql('postgres', "SELECT injection_points_detach('cfs-compaction-staged')"); $node->safe_psql('postgres', 'CHECKPOINT'); is($node->safe_psql('postgres', 'SELECT count(*) FROM sc_t'), '2000', 'the data is intact after the interleaving'); is( $node->safe_psql( 'postgres', "SELECT dead_bytes FROM pg_stat_cfs WHERE relname = 'sc_t'"), '0', 'the compaction kept its dead_bytes reset'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('sc_t', true)"), 't', 'pg_cfs_check is clean after the interleaving'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # The online mode (QDB-1514) parks in a second window: the catch-up phase, # after the lock-free copy and under the re-acquired append lock, with the # .tmp candidates on disk and no commit marker yet. A checkpoint hitting # that window must skip the relation exactly as it does in the staged one. # --------------------------------------------------------------------------- subtest 'a checkpoint during the online catch-up phase skips the relation' => 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_catchup_ckpt'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->start; if (!$node->check_extension('injection_points')) { plan skip_all => 'Extension injection_points not installed'; } $node->safe_psql( 'postgres', q{ CREATE TABLE cu_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO cu_t SELECT g, repeat('a' || g, 200) FROM generate_series(1, 2000) g; CHECKPOINT; UPDATE cu_t SET payload = repeat('b' || id, 200); CHECKPOINT; }); $node->safe_psql('postgres', 'CREATE EXTENSION injection_points'); $node->safe_psql('postgres', "SELECT injection_points_attach('cfs-compaction-catchup', 'wait')"); # The compaction parks in the catch-up phase: the lock-free copy is # over, the append lock is held again, the candidates exist, the marker # does not. my $bg = $node->background_psql('postgres', timeout => 180); $bg->query_until(qr/COMPACT_STARTED/, "\\echo 'COMPACT_STARTED'\n" . "SELECT pg_cfs_compact('cu_t');\n"); $node->wait_for_event('client backend', 'cfs-compaction-catchup'); # The checkpoint must not fold the parked relation and above all must # not run the interrupted-swap recovery over the live candidates. $node->safe_psql('postgres', 'CHECKPOINT'); $node->safe_psql('postgres', "SELECT injection_points_wakeup('cfs-compaction-catchup')"); $bg->query_until(qr/COMPACT_DONE/, "SELECT 'COMPACT_DONE';\n"); $bg->quit; $node->safe_psql('postgres', "SELECT injection_points_detach('cfs-compaction-catchup')"); $node->safe_psql('postgres', 'CHECKPOINT'); is($node->safe_psql('postgres', 'SELECT count(*) FROM cu_t'), '2000', 'the data is intact after the catch-up interleaving'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('cu_t', true)"), 't', 'pg_cfs_check is clean after the catch-up interleaving'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A crash in the online catch-up window (candidates written, no marker, # records appended during the copy not yet transferred) must leave the old # pair authoritative after recovery: WAL replay re-materializes everything # the copy saw and everything the concurrent writer added, the startup # cleanup discards the orphaned .tmp chain, and a later compaction succeeds. # --------------------------------------------------------------------------- subtest 'a crash in the online catch-up phase keeps the old pair' => 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_catchup_crash'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n" . "cfs_debug_compact_delay_ms = 20\n"); $node->start; if (!$node->check_extension('injection_points')) { plan skip_all => 'Extension injection_points not installed'; } $node->safe_psql( 'postgres', q{ CREATE TABLE cc_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO cc_t SELECT g, repeat('a' || g, 500) FROM generate_series(1, 2000) g; CHECKPOINT; UPDATE cc_t SET payload = repeat('b' || id, 500); CHECKPOINT; }); $node->safe_psql('postgres', 'CREATE EXTENSION injection_points'); $node->safe_psql('postgres', "SELECT injection_points_attach('cfs-compaction-catchup', 'wait')"); # Start the online compaction; its copy phase is stretched by the # delay GUC, so the concurrent writer below lands inside the copy # window and its records are the ones the catch-up phase would carry. my $bg = $node->background_psql('postgres', timeout => 180); $bg->query_until(qr/COMPACT_STARTED/, "\\echo 'COMPACT_STARTED'\n" . "SELECT pg_cfs_compact('cc_t');\n"); # Concurrent workload during the lock-free copy: updates of existing # blocks (the catch-up transfer path) and brand-new rows (map growth). $node->safe_psql( 'postgres', q{ UPDATE cc_t SET payload = repeat('c' || id, 500) WHERE id <= 200; INSERT INTO cc_t SELECT 10000 + g, repeat('n' || g, 500) FROM generate_series(1, 100) g; }); $node->wait_for_event('client backend', 'cfs-compaction-catchup'); # Crash before the catch-up transfers anything. $node->stop('immediate'); $node->start; is($node->safe_psql('postgres', 'SELECT count(*) FROM cc_t'), '2100', 'all rows survived the crash in the catch-up window'); is( $node->safe_psql( 'postgres', "SELECT count(*) FROM cc_t WHERE id <= 200 " . "AND payload = repeat('c' || id, 500)"), '200', 'the blocks updated during the copy read their new versions'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('cc_t', true)"), 't', 'pg_cfs_check is clean after the crash in the catch-up window'); # The orphaned candidates must not block the next compaction, and its # catch-up path must now carry nothing (the workload is over). is($node->safe_psql('postgres', "SELECT pg_cfs_compact('cc_t') LIKE 'compacted:%'"), 't', 'a compaction after the crash succeeds'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('cc_t', true)"), 't', 'pg_cfs_check is clean after the post-crash compaction'); $node->stop('fast'); }; done_testing();