# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group # # src/test/recovery/t/500_cfs_lifecycle.pl # # Lifecycle of a CFS relation, end to end: # * the basic read/write path: a CFS table accepts INSERT/UPDATE/DELETE, # VACUUM and COPY, stores its data in the .cfp sidecar after a # checkpoint and reads it back byte-identical across restarts and an # immediate-stop crash, while a plain table never gets sidecars; # * DDL on CFS relations: VACUUM FULL, CLUSTER, REINDEX, ALTER TABLE # SET/RESET (algorithm)/(level), SET TABLESPACE, partition policy # inheritance, ATTACH PARTITION, and the rejection of CFS on # TEMP/UNLOGGED tables; # * explicit CFS policies on indexes, including per-AM coverage and # REINDEX CONCURRENTLY; # * reloption validation edge cases: min_gain_bytes/level boundaries, # per-algorithm level ranges and the "policy freeze" contract for the # cfs_default_* GUCs; # * the SQL interface: pg_cfs_* functions, the pg_cfs_settings / # pg_stat_cfs views, background-worker control and access control; # * CFS-aware behaviour of the standard utilities: size functions, # pageinspect/amcheck/pgstattuple, pg_basebackup/pg_verifybackup and # pg_checksums; # * propagation of an altered policy to auxiliary processes and the # skipFsync contract on bulk writes; # * CREATE DATABASE ... TEMPLATE with both copy strategies, including a # crash before the first checkpoint of the copy. use strict; use warnings FATAL => 'all'; use File::Path qw(rmtree); use File::Temp (); use PostgreSQL::Test::Cluster; use PostgreSQL::Test::Utils; use Test::More; # Helpers shared by the sections below. Each takes the test node as its # first argument because every section runs against its own cluster. # Data-directory path prefix of a relation. sub rel_filepath { my ($node, $tbl) = @_; return $node->safe_psql('postgres', "SELECT pg_relation_filepath('$tbl')"); } # Whether the relation currently has a .cfp sidecar on disk. sub has_sidecars { my ($node, $tbl) = @_; my $path = rel_filepath($node, $tbl); return (-f $node->data_dir . "/$path.cfp"); } # md5 of the ordered payload concatenation of a table. sub checksum_tbl { my ($node, $tbl) = @_; return $node->safe_psql('postgres', "SELECT md5(string_agg(payload, chr(10) ORDER BY id)) FROM $tbl"); } # Raw reloptions text of a relation. sub reloptions { my ($node, $tbl) = @_; return $node->safe_psql('postgres', "SELECT reloptions::text FROM pg_class WHERE oid = '$tbl'::regclass"); } # --------------------------------------------------------------------------- # Basic end-to-end read/write path # --------------------------------------------------------------------------- { # A directory the server process can read, used for COPY FROM/TO files. my $copydir = File::Temp::tempdir(CLEANUP => 1); my $copyfile = "$copydir/cfs_data.csv"; # A single node; no streaming required for this scenario. my $node = PostgreSQL::Test::Cluster->new('cfs_node'); $node->init; # Shorten restart / crash-recovery wait cycles so a stuck readiness # probe is reported quickly rather than hanging the whole suite. $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; # Skip when LZ4 was not compiled in: it is the only algorithm this # section exercises and CREATE TABLE would otherwise fail. 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 basic test'; } # Return md5 of the concatenation of all rows' payload column, ordered # by id. sub table_checksum { my ($tbl) = @_; return $node->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM $tbl"); } # 1. Create a CFS table and populate it. $node->safe_psql('postgres', "CREATE TABLE cfs_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO cfs_t SELECT g, repeat('cfs-' || g, 100) " . "FROM generate_series(1, 1000) g"); my $checksum_insert = table_checksum('cfs_t'); is(length($checksum_insert), 32, 'CFS table populated, checksum computed'); # A plain (non-CFS) table, to contrast sidecar behaviour. $node->safe_psql('postgres', "CREATE TABLE plain_t (id int, payload text)"); $node->safe_psql('postgres', "INSERT INTO plain_t SELECT g, repeat('p' || g, 50) " . "FROM generate_series(1, 100) g"); # 2. DML churn + VACUUM. $node->safe_psql('postgres', "UPDATE cfs_t SET payload = repeat('upd-' || id, 100) WHERE id <= 500" ); $node->safe_psql('postgres', "DELETE FROM cfs_t WHERE id > 900"); $node->safe_psql('postgres', "VACUUM cfs_t"); my $checksum_dml = table_checksum('cfs_t'); isnt($checksum_dml, $checksum_insert, 'UPDATE/DELETE changed the payload'); # 900 rows survive (1..900). my $surviving = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_t"); is($surviving, '900', 'CFS table has 900 rows after DELETE'); # 3. CHECKPOINT: dirty buffers are flushed (compressed) into .cfp, the # journal is truncated and the map snapshot is persisted. $node->safe_psql('postgres', "CHECKPOINT"); my $cfs_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('cfs_t')"); my $plain_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('plain_t')"); my $data_dir = $node->data_dir; ok(-f "$data_dir/$cfs_path.cfp", 'CFS table has a .cfp sidecar after checkpoint'); ok(-f "$data_dir/$cfs_path.cfsmap", 'CFS table has a .cfsmap sidecar after checkpoint'); ok(-f "$data_dir/$cfs_path.cfsjrn", 'CFS table has a .cfsjrn sidecar after checkpoint'); ok(-s "$data_dir/$cfs_path.cfp" > 0, '.cfp holds compressed data after checkpoint'); ok( !-f "$data_dir/$plain_path.cfp", 'plain table has no CFS sidecar files'); # 4. COPY into a CFS table exercises the multi-page extension path. $node->safe_psql('postgres', "COPY (SELECT g AS id, repeat('copy-' || g, 80) " . "FROM generate_series(1, 2000) g) TO '$copyfile'"); $node->safe_psql('postgres', "CREATE TABLE cfs_copy_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "COPY cfs_copy_t FROM '$copyfile'"); my $copy_count = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_copy_t"); is($copy_count, '2000', 'COPY extends a CFS table by many pages'); # 5. Restart: the read path must decompress pages from .cfp. $node->restart; my $checksum_restart = table_checksum('cfs_t'); is($checksum_restart, $checksum_dml, 'CFS data is byte-identical after restart (read-path decompression)'); my $copy_count_after = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_copy_t"); is($copy_count_after, '2000', 'COPY-loaded CFS table survives restart'); # Further writes after restart still go through CFS. $node->safe_psql('postgres', "INSERT INTO cfs_t SELECT g, repeat('new-' || g, 100) " . "FROM generate_series(1001, 1100) g"); my $after_insert = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_t"); is($after_insert, '1000', 'CFS table accepts inserts after restart'); $node->safe_psql('postgres', "CHECKPOINT"); # Baseline of the durable state (900 original + 100 freshly inserted # rows). my $checksum_durable = table_checksum('cfs_t'); # 6. Crash-style restart (immediate stop) and final verification. $node->stop('immediate'); $node->start; my $checksum_final = table_checksum('cfs_t'); is($checksum_final, $checksum_durable, 'CFS data survives an immediate-stop restart (crash recovery)'); $node->stop('fast'); } # --------------------------------------------------------------------------- # DDL operations on CFS relations # --------------------------------------------------------------------------- subtest 'DDL operations on CFS relations' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_lifecycle'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $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 lifecycle test'; } # 1. VACUUM FULL on a CFS table. $node->safe_psql('postgres', "CREATE TABLE vf_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO vf_t SELECT g, repeat('vf-' || g, 80) " . "FROM generate_series(1, 500) g"); # Cause some bloat so VACUUM FULL has something to compact. $node->safe_psql('postgres', "UPDATE vf_t SET payload = repeat('upd-' || id, 60) WHERE id <= 300"); $node->safe_psql('postgres', "CHECKPOINT"); # Checksum AFTER the update but BEFORE VACUUM FULL. my $ck_vf_before = checksum_tbl($node, 'vf_t'); ok(has_sidecars($node, 'vf_t'), 'CFS table has sidecars before VACUUM FULL'); # VACUUM FULL rewrites the table. $node->safe_psql('postgres', "VACUUM FULL vf_t"); $node->safe_psql('postgres', "CHECKPOINT"); my $ck_vf_after = checksum_tbl($node, 'vf_t'); is($ck_vf_after, $ck_vf_before, 'VACUUM FULL preserves data on a CFS table'); ok(has_sidecars($node, 'vf_t'), 'CFS sidecars still present after VACUUM FULL'); # 2. CLUSTER on a CFS table. $node->safe_psql('postgres', "CREATE TABLE cl_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO cl_t SELECT g, repeat('cl-' || g, 50) " . "FROM generate_series(1, 300) g"); $node->safe_psql('postgres', "CREATE INDEX cl_t_idx ON cl_t (id)"); $node->safe_psql('postgres', "CHECKPOINT"); my $ck_cl_before = checksum_tbl($node, 'cl_t'); $node->safe_psql('postgres', "CLUSTER cl_t USING cl_t_idx"); $node->safe_psql('postgres', "CHECKPOINT"); my $ck_cl_after = checksum_tbl($node, 'cl_t'); is($ck_cl_after, $ck_cl_before, 'CLUSTER preserves data on a CFS table'); ok(has_sidecars($node, 'cl_t'), 'CFS sidecars still present after CLUSTER'); # 3. ALTER TABLE ... SET (algorithm) triggers a rewrite on a plain # table. $node->safe_psql('postgres', "CREATE TABLE alt_t (id int, payload text)"); $node->safe_psql('postgres', "INSERT INTO alt_t SELECT g, repeat('alt-' || g, 60) " . "FROM generate_series(1, 300) g"); $node->safe_psql('postgres', "CHECKPOINT"); ok(!has_sidecars($node, 'alt_t'), 'plain table has no sidecars before SET algorithm'); my $ck_alt_before = checksum_tbl($node, 'alt_t'); $node->safe_psql('postgres', "ALTER TABLE alt_t SET (algorithm = 'lz4')"); $node->safe_psql('postgres', "CHECKPOINT"); my $ck_alt_after = checksum_tbl($node, 'alt_t'); is($ck_alt_after, $ck_alt_before, 'ALTER TABLE SET (algorithm) preserves data'); ok(has_sidecars($node, 'alt_t'), 'ALTER TABLE SET (algorithm) creates CFS sidecars'); # 4. ALTER TABLE ... SET (level) does NOT trigger a rewrite. my $node_before = rel_filepath($node, 'alt_t'); $node->safe_psql('postgres', "ALTER TABLE alt_t SET (level = 5)"); my $node_after = rel_filepath($node, 'alt_t'); is($node_after, $node_before, 'ALTER TABLE SET (level) does not rewrite the table'); # 5. ALTER TABLE ... RESET (algorithm) triggers a rewrite to plain # storage. Must also reset level since it requires algorithm to be # present. $node->safe_psql('postgres', "CHECKPOINT"); $node_before = rel_filepath($node, 'alt_t'); $node->safe_psql('postgres', "ALTER TABLE alt_t RESET (algorithm, level)"); $node->safe_psql('postgres', "CHECKPOINT"); $node_after = rel_filepath($node, 'alt_t'); isnt($node_after, $node_before, 'ALTER TABLE RESET (algorithm) rewrites the table'); my $ck_alt_reset = checksum_tbl($node, 'alt_t'); is($ck_alt_reset, $ck_alt_before, 'ALTER TABLE RESET (algorithm) preserves data'); ok(!has_sidecars($node, 'alt_t'), 'plain table has no sidecars after RESET algorithm'); # 5b. A rewrite must be triggered only when the effective algorithm # actually changes, not merely because "algorithm" appears in the # command. This mirrors how fillfactor and other non-rewrite # reloptions behave: re-stating the same value is a no-op on # storage. # Re-stating the SAME algorithm on a CFS table: no rewrite, data and # sidecars kept intact. $node->safe_psql('postgres', "CREATE TABLE noop_cfs (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO noop_cfs SELECT g, repeat('noop-' || g, 50) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $noop_ck = checksum_tbl($node, 'noop_cfs'); my $noop_node = rel_filepath($node, 'noop_cfs'); ok(has_sidecars($node, 'noop_cfs'), 'noop_cfs starts as CFS'); $node->safe_psql('postgres', "ALTER TABLE noop_cfs SET (algorithm = 'lz4')"); is(rel_filepath($node, 'noop_cfs'), $noop_node, 'SET (algorithm) to the same value does not rewrite the table'); is(checksum_tbl($node, 'noop_cfs'), $noop_ck, 'SET (algorithm) to the same value preserves data'); ok(has_sidecars($node, 'noop_cfs'), 'SET (algorithm) to the same value keeps CFS sidecars'); # RESET (algorithm) on a plain (non-CFS) table: nothing to reset, no # rewrite. $node->safe_psql('postgres', "CREATE TABLE noop_plain (id int, payload text)"); $node->safe_psql('postgres', "INSERT INTO noop_plain SELECT g, repeat('p-' || g, 30) " . "FROM generate_series(1, 100) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $plain_node = rel_filepath($node, 'noop_plain'); $node->safe_psql('postgres', "ALTER TABLE noop_plain RESET (algorithm)"); is(rel_filepath($node, 'noop_plain'), $plain_node, 'RESET (algorithm) on a plain table does not rewrite'); # Control: a genuine transition compressed -> plain must still rewrite. $node->safe_psql('postgres', "CHECKPOINT"); my $disable_node = rel_filepath($node, 'noop_cfs'); $node->safe_psql('postgres', "ALTER TABLE noop_cfs RESET (algorithm)"); $node->safe_psql('postgres', "CHECKPOINT"); isnt(rel_filepath($node, 'noop_cfs'), $disable_node, 'RESET (algorithm) on a CFS table rewrites to plain storage'); is(checksum_tbl($node, 'noop_cfs'), $noop_ck, 'RESET (algorithm) on a CFS table preserves data'); ok(!has_sidecars($node, 'noop_cfs'), 'CFS sidecars gone after RESET (algorithm)'); # Control: enabling CFS on a plain table must still rewrite. my $enable_node = rel_filepath($node, 'noop_plain'); $node->safe_psql('postgres', "ALTER TABLE noop_plain SET (algorithm = 'lz4')"); $node->safe_psql('postgres', "CHECKPOINT"); isnt(rel_filepath($node, 'noop_plain'), $enable_node, 'SET (algorithm) on a plain table rewrites to compressed storage'); # Control: switching between two compression algorithms must still # rewrite. Guarded on zstd because this fork is built with both codecs # but the suite's skip guard above only checks lz4. SKIP: { skip "zstd not built, skipping cross-algorithm rewrite test", 3 unless $configure =~ /--with-zstd/; $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('sw-' || g, 50) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $swap_ck = checksum_tbl($node, 'swap_t'); my $swap_node = rel_filepath($node, 'swap_t'); $node->safe_psql('postgres', "ALTER TABLE swap_t SET (algorithm = 'zstd')"); $node->safe_psql('postgres', "CHECKPOINT"); isnt(rel_filepath($node, 'swap_t'), $swap_node, 'SET (algorithm) lz4 -> zstd rewrites the table'); is(checksum_tbl($node, 'swap_t'), $swap_ck, 'SET (algorithm) lz4 -> zstd preserves data'); like(reloptions($node, 'swap_t'), qr/algorithm=zstd/, 'cross-algorithm rewrite stores the new algorithm'); } # 6. ALTER TABLE ... SET UNLOGGED on a CFS table is rejected. $node->safe_psql('postgres', "CREATE TABLE unlog_t (id int) WITH (algorithm = 'lz4')"); my ($ret, $stdout, $stderr) = $node->psql('postgres', "ALTER TABLE unlog_t SET UNLOGGED"); isnt($ret, 0, 'ALTER TABLE SET UNLOGGED on CFS table fails'); like( $stderr, qr/unlogged because it uses CFS compression/i, 'correct error message for SET UNLOGGED on CFS table'); # 7. TEMP and UNLOGGED tables reject the algorithm reloption. ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TEMP TABLE bad_temp (id int) WITH (algorithm = 'lz4')"); isnt($ret, 0, 'CREATE TEMP TABLE WITH algorithm fails'); like( $stderr, qr/not supported for temporary tables/i, 'correct error for TEMP CFS'); ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE UNLOGGED TABLE bad_unlog (id int) WITH (algorithm = 'lz4')"); isnt($ret, 0, 'CREATE UNLOGGED TABLE WITH algorithm fails'); like( $stderr, qr/not supported for unlogged tables/i, 'correct error for UNLOGGED CFS'); # 8. REINDEX on a CFS table's index. $node->safe_psql('postgres', "CREATE TABLE reidx_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO reidx_t SELECT g, repeat('ri-' || g, 40) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CREATE INDEX reidx_t_idx ON reidx_t (id)"); $node->safe_psql('postgres', "CHECKPOINT"); my $reidx_count_before = $node->safe_psql('postgres', "SELECT count(*) FROM reidx_t WHERE id > 100"); $node->safe_psql('postgres', "REINDEX TABLE reidx_t"); $node->safe_psql('postgres', "CHECKPOINT"); my $reidx_count_after = $node->safe_psql('postgres', "SELECT count(*) FROM reidx_t WHERE id > 100"); is($reidx_count_after, $reidx_count_before, 'REINDEX preserves query results on CFS table'); # Index scan still works. my $idx_scan = $node->safe_psql('postgres', "EXPLAIN (COSTS OFF) SELECT * FROM reidx_t WHERE id = 42"); like( $idx_scan, qr/Index Scan/i, 'index scan works after REINDEX on CFS table'); # 9. VACUUM (without FULL) on a CFS table does not corrupt data. $node->safe_psql('postgres', "UPDATE vf_t SET payload = repeat('vac-' || id, 40) WHERE id <= 100"); $node->safe_psql('postgres', "VACUUM vf_t"); my $ck_vac = checksum_tbl($node, 'vf_t'); ok(has_sidecars($node, 'vf_t'), 'VACUUM (non-FULL) does not remove sidecars'); # 10. Partition CFS policy inheritance. $node->safe_psql('postgres', "CREATE TABLE part_t (id int, payload text) " . "PARTITION BY RANGE (id) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "CREATE TABLE part_t_p1 PARTITION OF part_t " . "FOR VALUES FROM (0) TO (10000)"); my $part_relopts = $node->safe_psql('postgres', "SELECT reloptions FROM pg_class WHERE relname = 'part_t_p1'"); like($part_relopts, qr/algorithm=lz4/i, 'partition inherits algorithm from partitioned root'); $node->safe_psql('postgres', "INSERT INTO part_t SELECT g, repeat('p' || g, 50) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CHECKPOINT"); ok(has_sidecars($node, 'part_t_p1'), 'partition has CFS sidecars (inherited policy active)'); my $ck_part = checksum_tbl($node, 'part_t'); is(length($ck_part), 32, 'partition table data is readable (inherited CFS policy)'); # 10a. ATTACH PARTITION: the child keeps its own CFS policy (or lack # thereof). A partitioned table's default CFS policy for # partitions is inherited silently only via CREATE TABLE ... # PARTITION OF (a new empty table). ATTACH PARTITION of an # already-existing table must NOT silently swap the reloptions of # the child (the snapshot model freezes the policy at its own DDL # time); it must instead WARN the administrator when the child's # policy diverges from the parent default, so the administrator # can apply the policy explicitly via ALTER TABLE ... SET # (algorithm) (which triggers the existing rewrite path). # Fresh parent with a CFS default policy for partitions. $node->safe_psql('postgres', "CREATE TABLE attach_parent (id int, payload text) " . "PARTITION BY RANGE (id) WITH (algorithm = 'lz4')"); # (a) A plain (uncompressed) standalone table attached as a partition # must keep its empty reloptions and must NOT be rewritten (relfile # node stable), but the ATTACH must emit a WARNING about the # divergence. $node->safe_psql('postgres', "CREATE TABLE attach_plain (id int, payload text)"); $node->safe_psql('postgres', "INSERT INTO attach_plain SELECT g, repeat('ap-' || g, 40) " . "FROM generate_series(1, 100) g"); my $ap_relopts_before = $node->safe_psql('postgres', "SELECT reloptions::text FROM pg_class WHERE relname = 'attach_plain'" ); my $ap_node_before = rel_filepath($node, 'attach_plain'); my $ap_ck_before = checksum_tbl($node, 'attach_plain'); ok(!has_sidecars($node, 'attach_plain'), 'plain attach target has no CFS sidecars before ATTACH'); my ($ap_ret, $ap_std, $ap_err) = $node->psql('postgres', "ALTER TABLE attach_parent ATTACH PARTITION attach_plain " . "FOR VALUES FROM (0) TO (10000)"); is($ap_ret, 0, 'ATTACH of plain table succeeds (WARNING, not ERROR)'); like( $ap_err, qr/does not use CFS compression/i, 'ATTACH of an uncompressed table emits a CFS divergence WARNING'); my $ap_relopts_after = $node->safe_psql('postgres', "SELECT reloptions::text FROM pg_class WHERE relname = 'attach_plain'" ); is($ap_relopts_after, $ap_relopts_before, 'ATTACH does not change reloptions of the attached plain partition'); is( rel_filepath($node, 'attach_plain'), $ap_node_before, 'ATTACH does not rewrite (relfilenode stable) the attached partition' ); ok(!has_sidecars($node, 'attach_plain'), 'plain partition still has no CFS sidecars after ATTACH'); # Data stays intact through the ATTACH (no rewrite). is(checksum_tbl($node, 'attach_plain'), $ap_ck_before, 'attached plain partition data intact (no rewrite)'); # (b) A table already carrying a CFS policy that DIFFERS from the # parent default must keep its own policy and emit a WARNING about the # mismatch. Guarded on zstd so the test runs only when both codecs # are present. SKIP: { skip "zstd not built, skipping cross-policy ATTACH warning test", 7 unless $configure =~ /--with-zstd/; $node->safe_psql('postgres', "CREATE TABLE attach_zstd (id int, payload text) " . "WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "INSERT INTO attach_zstd SELECT g, repeat('az-' || g, 40) " . "FROM generate_series(10000, 10100) g"); $node->safe_psql('postgres', "CHECKPOINT"); ok(has_sidecars($node, 'attach_zstd'), 'zstd attach target has CFS sidecars before ATTACH'); my $az_node_before = rel_filepath($node, 'attach_zstd'); my ($az_ret, $az_std, $az_err) = $node->psql('postgres', "ALTER TABLE attach_parent ATTACH PARTITION attach_zstd " . "FOR VALUES FROM (10000) TO (20000)"); is($az_ret, 0, 'ATTACH of zstd table succeeds (WARNING, not ERROR)'); like( $az_err, qr/uses a different CFS algorithm/i, 'ATTACH of a divergent-CFS table emits a mismatch WARNING'); like($az_err, qr/zstd/i, 'ATTACH mismatch WARNING names the child algorithm'); like($az_err, qr/lz4/i, 'ATTACH mismatch WARNING names the parent default algorithm'); is( rel_filepath($node, 'attach_zstd'), $az_node_before, 'ATTACH of a CFS partition does not rewrite it (keeps its policy)' ); ok(has_sidecars($node, 'attach_zstd'), 'zstd partition keeps its CFS sidecars after ATTACH'); } # (c) A table whose CFS policy MATCHES the parent default must NOT # emit a WARNING at ATTACH: there is no divergence to report. $node->safe_psql('postgres', "CREATE TABLE attach_lz4 (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "CHECKPOINT"); my ($al_ret, $al_std, $al_err) = $node->psql('postgres', "ALTER TABLE attach_parent ATTACH PARTITION attach_lz4 " . "FOR VALUES FROM (20000) TO (30000)"); is($al_ret, 0, 'ATTACH of a matching-CFS table succeeds'); unlike($al_err, qr/CFS/i, 'ATTACH of a matching-CFS partition emits no CFS WARNING'); # (d) A table attached to a NON-CFS parent must NEVER emit a CFS # WARNING, even when the table itself is compressed: the parent has no # default policy to diverge from. $node->safe_psql('postgres', "CREATE TABLE plain_parent (id int, payload text) " . "PARTITION BY RANGE (id)"); $node->safe_psql('postgres', "CREATE TABLE pp_plain (id int, payload text)"); my ($pp_ret, $pp_std, $pp_err) = $node->psql('postgres', "ALTER TABLE plain_parent ATTACH PARTITION pp_plain " . "FOR VALUES FROM (0) TO (10000)"); is($pp_ret, 0, 'ATTACH to a non-CFS parent succeeds'); unlike($pp_err, qr/CFS/i, 'ATTACH to a non-CFS parent does not mention CFS'); # (e) An auxiliary (level / min_gain_bytes) divergence at ATTACH is a # DEBUG1 diagnostic, not a WARNING, and it fires only when BOTH sides # store the field explicitly. A parent without an explicit level has # no opinion on the level, so attaching a child with its own explicit # level must not log a spurious "level=0" divergence. $node->safe_psql('postgres', "CREATE TABLE attach_aux (id int, payload text) " . "PARTITION BY RANGE (id) WITH (algorithm = 'zstd', level = 10)"); $node->safe_psql('postgres', "CREATE TABLE attach_aux_child (id int, payload text) " . "WITH (algorithm = 'zstd', level = 5)"); my ($aux_ret, $aux_std, $aux_err) = $node->psql('postgres', "SET client_min_messages = debug1; " . "ALTER TABLE attach_aux ATTACH PARTITION attach_aux_child " . "FOR VALUES FROM (0) TO (10000)"); is($aux_ret, 0, 'ATTACH of a same-algorithm child with divergent level succeeds'); like( $aux_err, qr/auxiliary option divergence.*level=10.*level=5/, 'both-explicit level divergence is reported at DEBUG1'); # Parent without an explicit level: the same attach is silent. $node->safe_psql('postgres', "CREATE TABLE attach_aux_nolvl (id int, payload text) " . "PARTITION BY RANGE (id) WITH (algorithm = 'zstd')"); $node->safe_psql('postgres', "CREATE TABLE attach_aux_nolvl_child (id int, payload text) " . "WITH (algorithm = 'zstd', level = 5)"); my ($aux2_ret, $aux2_std, $aux2_err) = $node->psql('postgres', "SET client_min_messages = debug1; " . "ALTER TABLE attach_aux_nolvl ATTACH PARTITION attach_aux_nolvl_child " . "FOR VALUES FROM (0) TO (10000)"); is($aux2_ret, 0, 'ATTACH to a parent without an explicit level succeeds'); unlike( $aux2_err, qr/auxiliary option divergence/, 'no auxiliary divergence report when the parent level is unset'); # 11. ALTER TABLE/INDEX ... SET TABLESPACE preserves CFS compression. my $ts_dir = $node->data_dir . '/ts_move'; mkdir $ts_dir; $node->safe_psql('postgres', "CREATE TABLESPACE ts_move LOCATION '$ts_dir'"); $node->safe_psql('postgres', "CREATE TABLE mv_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO mv_t SELECT g, repeat('mv-' || g, 80) " . "FROM generate_series(1, 500) g"); # One index with an explicit policy, one inheriting the table's policy. $node->safe_psql('postgres', "CREATE INDEX mv_t_idx ON mv_t (id) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "CREATE INDEX mv_t_idx_inh ON mv_t (payload)"); $node->safe_psql('postgres', "CHECKPOINT"); my $ck_mv_before = checksum_tbl($node, 'mv_t'); ok(has_sidecars($node, 'mv_t'), 'CFS table has sidecars before SET TABLESPACE'); ok(has_sidecars($node, 'mv_t_idx'), 'CFS index has sidecars before SET TABLESPACE'); $node->safe_psql('postgres', "ALTER TABLE mv_t SET TABLESPACE ts_move"); $node->safe_psql('postgres', "ALTER INDEX mv_t_idx SET TABLESPACE ts_move"); $node->safe_psql('postgres', "ALTER INDEX mv_t_idx_inh SET TABLESPACE ts_move"); $node->safe_psql('postgres', "CHECKPOINT"); # reloptions still claim compression ... my $mv_relopts = $node->safe_psql('postgres', "SELECT reloptions FROM pg_class WHERE relname = 'mv_t'"); like($mv_relopts, qr/algorithm=lz4/i, 'reloptions still claim compression after SET TABLESPACE'); # ... and the physical storage must agree with them. ok(has_sidecars($node, 'mv_t'), 'CFS sidecars recreated in new tablespace (table)'); ok(has_sidecars($node, 'mv_t_idx'), 'CFS sidecars recreated in new tablespace (index, explicit policy)'); ok( has_sidecars($node, 'mv_t_idx_inh'), 'CFS sidecars recreated in new tablespace (index, inherited policy)'); # The TOAST table follows the parent table's policy, and its sidecars # are materialized when the TOAST relation's policy is published at its # creation (the SET TABLESPACE copy recreates the TOAST table for the # new tablespace), the same contract as for the parent table: the # empty TOAST already owns its sidecar triple after the move, and the # first externally stored value below is written into them in the NEW # tablespace. my $mv_toast = $node->safe_psql('postgres', "SELECT reltoastrelid::regclass::text FROM pg_class " . "WHERE relname = 'mv_t'"); ok( has_sidecars($node, $mv_toast), 'empty TOAST has sidecars after SET TABLESPACE (created with the relation)' ); # Data must stay readable through the CFS path. is(checksum_tbl($node, 'mv_t'), $ck_mv_before, 'data readable after SET TABLESPACE'); # The copy must actually be compressed: the .cfp holding 500 highly # compressible payloads is far smaller than the raw payload bytes. my $raw_bytes = $node->safe_psql('postgres', "SELECT sum(length(payload)) FROM mv_t"); my $cfp_size = -s ($node->data_dir . '/' . rel_filepath($node, 'mv_t') . '.cfp'); ok($cfp_size < $raw_bytes, 'relation is physically compressed after SET TABLESPACE'); # Index scans work on the moved indexes. my $mv_idx_scan = $node->safe_psql('postgres', "SET enable_seqscan = off; EXPLAIN (COSTS OFF) " . "SELECT * FROM mv_t WHERE id = 42"); like( $mv_idx_scan, qr/Index Scan/i, 'index scan works after SET TABLESPACE on CFS index'); # Completion of the TOAST check above: the first value stored # externally must be written into the sidecars in the NEW tablespace, # proving the TOAST relation resolves its storage there after the # move. The payload index is dropped first: btree caps the row size # far below what is needed to force external TOAST storage (and the # index fork has already been verified above). $node->safe_psql('postgres', "DROP INDEX mv_t_idx_inh"); $node->safe_psql('postgres', "INSERT INTO mv_t VALUES (1, repeat('mv-big', 100000))"); ok(has_sidecars($node, $mv_toast), 'TOAST sidecars still present after the first external value'); is( $node->safe_psql( 'postgres', "SELECT length(payload) FROM mv_t WHERE length(payload) > 1000"), 600000, 'externally stored TOAST value reads back intact after the move'); # Remove the probe row again: the end-of-test checksum comparison # expects the original 500 rows. $node->safe_psql('postgres', "DELETE FROM mv_t WHERE length(payload) > 1000"); # 11b. ALTER TABLE SET / RESET (algorithm) must not corrupt TOAST # values. The rewrite copies TOAST pointers from the old heap, # but the old toast relation's SMgrRelation must still resolve # its I/O path from the *physical* storage (sidecar existence), # not from the already-updated reloptions. Incompressible data # is used so the values are genuinely stored in the toast table # (not merely inline-compressed), exercising the toast I/O path. # (a) plain -> CFS: large incompressible text that forces real TOAST # storage $node->safe_psql('postgres', "CREATE TABLE toast_set (id int, payload text)"); $node->safe_psql('postgres', "INSERT INTO toast_set SELECT 1, " . "(SELECT string_agg(md5(g::text), '') " . " FROM generate_series(1, 8000) g)"); # Verify the value is actually stored in the toast table (not inline). my $toast_col_size = $node->safe_psql('postgres', "SELECT pg_column_size(payload) FROM toast_set WHERE id = 1"); cmp_ok($toast_col_size, '>', 8160, 'toast_set value is stored externally in TOAST'); my $ck_toast_set = $node->safe_psql('postgres', "SELECT md5(payload) FROM toast_set WHERE id = 1"); # Restart so that the rewrite below detoasts through the smgr read # path: with warm shared buffers the old toast pages would be served # from the buffer cache and the I/O-path resolution bug would stay # invisible. The ALTER itself then runs in a fresh session (cold # relcache). $node->restart; $node->safe_psql('postgres', "ALTER TABLE toast_set SET (algorithm = 'lz4')"); is( $node->safe_psql( 'postgres', "SELECT md5(payload) FROM toast_set WHERE id = 1"), $ck_toast_set, 'SET (algorithm) preserves large TOAST value (plain -> CFS)'); ok(has_sidecars($node, 'toast_set'), 'toast_set has CFS sidecars after SET (algorithm)'); # (b) CFS -> plain: RESET (algorithm) on a table whose toast was CFS. $node->safe_psql('postgres', "CREATE TABLE toast_reset (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO toast_reset SELECT 1, " . "(SELECT string_agg(md5(g::text), '') " . " FROM generate_series(1, 8000) g)"); my $ck_toast_reset = $node->safe_psql('postgres', "SELECT md5(payload) FROM toast_reset WHERE id = 1"); # Cold buffers + fresh session again (see above). $node->restart; $node->safe_psql('postgres', "ALTER TABLE toast_reset RESET (algorithm)"); is( $node->safe_psql( 'postgres', "SELECT md5(payload) FROM toast_reset WHERE id = 1"), $ck_toast_reset, 'RESET (algorithm) preserves large TOAST value (CFS -> plain)'); ok(!has_sidecars($node, 'toast_reset'), 'toast_reset has no CFS sidecars after RESET (algorithm)'); # A large value written AFTER the transition must land in the rebuilt # plain TOAST and read back: the coverage of new-chunk writes, which # the old-value checks above cannot provide. $node->safe_psql('postgres', "INSERT INTO toast_reset SELECT 2, " . "(SELECT string_agg(md5((g + 8000)::text), '') " . " FROM generate_series(1, 8000) g)"); cmp_ok( $node->safe_psql( 'postgres', "SELECT pg_column_size(payload) FROM toast_reset WHERE id = 2"), '>', 8160, 'toast_reset new value is stored externally in TOAST'); my $ck_toast_reset_new = $node->safe_psql('postgres', "SELECT md5(payload) FROM toast_reset WHERE id = 2"); is( $node->safe_psql( 'postgres', "SELECT md5((SELECT string_agg(md5((g + 8000)::text), '') " . "FROM generate_series(1, 8000) g))"), $ck_toast_reset_new, 'toast_reset new TOAST value reads back intact after RESET'); # (c) Cross-algorithm swap (lz4 -> zstd) must also preserve TOAST data. my $ck_toast_swap_new; SKIP: { skip "zstd not built, skipping cross-algorithm TOAST test", 5 unless $configure =~ /--with-zstd/; $node->safe_psql('postgres', "CREATE TABLE toast_swap (id int, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO toast_swap SELECT 1, " . "(SELECT string_agg(md5(g::text), '') " . " FROM generate_series(1, 8000) g)"); my $ck_toast_swap = $node->safe_psql('postgres', "SELECT md5(payload) FROM toast_swap WHERE id = 1"); # Cold buffers + fresh session again (see above). $node->restart; $node->safe_psql('postgres', "ALTER TABLE toast_swap SET (algorithm = 'zstd')"); is( $node->safe_psql( 'postgres', "SELECT md5(payload) FROM toast_swap WHERE id = 1"), $ck_toast_swap, 'cross-algorithm swap preserves large TOAST value (lz4 -> zstd)'); ok(has_sidecars($node, 'toast_swap'), 'toast_swap has CFS sidecars after algorithm swap'); # New-chunk coverage for the swap direction as well: a large value # written after the transition goes into the rebuilt zstd TOAST. $node->safe_psql('postgres', "INSERT INTO toast_swap SELECT 2, " . "(SELECT string_agg(md5((g + 8000)::text), '') " . " FROM generate_series(1, 8000) g)"); cmp_ok( $node->safe_psql( 'postgres', "SELECT pg_column_size(payload) FROM toast_swap WHERE id = 2" ), '>', 8160, 'toast_swap new value is stored externally in TOAST'); $ck_toast_swap_new = $node->safe_psql('postgres', "SELECT md5(payload) FROM toast_swap WHERE id = 2"); is( $node->safe_psql( 'postgres', "SELECT md5((SELECT string_agg(md5((g + 8000)::text), '') " . "FROM generate_series(1, 8000) g))"), $ck_toast_swap_new, 'toast_swap new TOAST value reads back intact after swap'); } # 12. Restart and verify all data is intact. $node->restart; is(checksum_tbl($node, 'vf_t'), $ck_vac, 'VACUUM FULL table data intact after restart'); is(checksum_tbl($node, 'cl_t'), $ck_cl_before, 'CLUSTER table data intact after restart'); is(checksum_tbl($node, 'alt_t'), $ck_alt_before, 'ALTER table data intact after restart'); is(checksum_tbl($node, 'part_t'), $ck_part, 'partition table data intact after restart'); is(checksum_tbl($node, 'mv_t'), $ck_mv_before, 'SET TABLESPACE table data intact after restart'); ok(has_sidecars($node, 'mv_t'), 'CFS sidecars still present after restart'); is( $node->safe_psql( 'postgres', "SELECT md5(payload) FROM toast_set WHERE id = 1"), $ck_toast_set, 'toast_set TOAST value intact after restart'); is( $node->safe_psql( 'postgres', "SELECT md5(payload) FROM toast_reset WHERE id = 1"), $ck_toast_reset, 'toast_reset TOAST value intact after restart'); is( $node->safe_psql( 'postgres', "SELECT md5(payload) FROM toast_reset WHERE id = 2"), $ck_toast_reset_new, 'toast_reset new TOAST value intact after restart'); SKIP: { skip "zstd not built, skipping new-value restart check", 1 unless $configure =~ /--with-zstd/; is( $node->safe_psql( 'postgres', "SELECT md5(payload) FROM toast_swap WHERE id = 2"), $ck_toast_swap_new, 'toast_swap new TOAST value intact after restart'); } $node->stop('fast'); }; # --------------------------------------------------------------------------- # Explicit CFS policy on indexes # --------------------------------------------------------------------------- subtest 'explicit CFS policy on indexes' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_index_policy'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->append_conf('postgresql.conf', "cfs_bg_period_ms = 36000000"); $node->start; # The policy/reloptions layer is codec-independent; this section # exercises it with both LZ4 and Zstd. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/ || $configure !~ /--with-zstd/) { plan skip_all => 'LZ4 and Zstd support required, skipping CFS index-policy test'; } # 1. CREATE INDEX ... WITH (algorithm = ...) gives the index its own # policy. $node->safe_psql('postgres', "CREATE TABLE base_t (id int, data text) WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO base_t SELECT g, repeat('x', 200) " . "FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CREATE INDEX own_idx ON base_t (id) WITH (algorithm = 'lz4', level = 3)" ); ok(has_sidecars($node, 'own_idx'), 'CFS index with explicit algorithm has sidecars'); like(reloptions($node, 'own_idx'), qr/algorithm=lz4/, 'explicit index policy stored'); $node->safe_psql('postgres', "CREATE INDEX inh_idx ON base_t (data)"); ok(has_sidecars($node, 'inh_idx'), 'index on CFS table inherits sidecars (no explicit policy)'); is(reloptions($node, 'inh_idx'), '{algorithm=lz4}', 'index without explicit policy inherits the table algorithm alone'); unlike(reloptions($node, 'inh_idx'), qr/level=|min_gain_bytes=/, 'inheriting index stores no GUC-frozen auxiliary keys'); # 2. level without algorithm is rejected for indexes. my ($ret, $stdout, $stderr); ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE INDEX bad_lvl_idx ON base_t (id) WITH (level = 3)"); isnt($ret, 0, 'CREATE INDEX WITH (level) without algorithm fails'); like( $stderr, qr/CFS compression algorithm must be specified/i, 'level-without-algorithm rejected for index'); # 3. ALTER INDEX RESET (algorithm) on a standalone CFS index. $node->safe_psql('postgres', "CREATE TABLE plain_t (id int)"); $node->safe_psql('postgres', "INSERT INTO plain_t SELECT g FROM generate_series(1, 200) g"); $node->safe_psql('postgres', "CREATE INDEX plain_cfs_idx ON plain_t (id) " . "WITH (algorithm = 'lz4', level = 5)"); ok( has_sidecars($node, 'plain_cfs_idx'), 'CFS index on plain table has sidecars'); $node->safe_psql('postgres', "ALTER INDEX plain_cfs_idx RESET (algorithm)"); $node->safe_psql('postgres', "CHECKPOINT"); ok(!has_sidecars($node, 'plain_cfs_idx'), 'ALTER INDEX RESET (algorithm) rebuilds index to plain storage'); # 4. ALTER INDEX SET (algorithm) rebuilds the index only when the # effective algorithm actually changes. Re-stating the same # algorithm is a storage no-op (like SET (level)); switching # algorithms rebuilds. # Same algorithm, different auxiliary options: no rebuild. my $fp_before = rel_filepath($node, 'own_idx'); $node->safe_psql('postgres', "ALTER INDEX own_idx SET (algorithm = 'lz4', level = 7)"); my $fp_after = rel_filepath($node, 'own_idx'); is($fp_after, $fp_before, 'ALTER INDEX SET (same algorithm) does not rebuild the index'); like(reloptions($node, 'own_idx'), qr/level=7/, 'index level updated without a rebuild'); # A genuinely different algorithm: rebuild required. $fp_before = rel_filepath($node, 'own_idx'); $node->safe_psql('postgres', "ALTER INDEX own_idx SET (algorithm = 'zstd', level = 7)"); $node->safe_psql('postgres', "CHECKPOINT"); $fp_after = rel_filepath($node, 'own_idx'); isnt($fp_after, $fp_before, 'ALTER INDEX SET (algorithm lz4 -> zstd) rebuilds the index'); like(reloptions($node, 'own_idx'), qr/algorithm=zstd/, 'index algorithm updated by rebuild'); like(reloptions($node, 'own_idx'), qr/level=7/, 'index level kept by rebuild'); ok(has_sidecars($node, 'own_idx'), 'rebuilt index still has sidecars'); my $cnt = $node->safe_psql('postgres', "SELECT count(*) FROM base_t WHERE id = 1"); is($cnt, 1, 'index usable after algorithm rebuild'); # 5. ALTER INDEX SET (level) does NOT rebuild. $fp_before = rel_filepath($node, 'own_idx'); $node->safe_psql('postgres', "ALTER INDEX own_idx SET (level = 9)"); $fp_after = rel_filepath($node, 'own_idx'); is($fp_after, $fp_before, 'ALTER INDEX SET (level) does not rebuild index'); like(reloptions($node, 'own_idx'), qr/level=9/, 'index level updated to 9'); # 6. Every built-in AM accepts an explicit CFS policy (LZ4). $node->safe_psql('postgres', "CREATE TABLE am_t (id serial, data text, tags text[], pt point)"); $node->safe_psql('postgres', "INSERT INTO am_t (data, tags, pt) " . "SELECT md5(g::text), ARRAY[md5(g::text)], point(g, g) " . "FROM generate_series(1, 300) g"); $node->safe_psql('postgres', "CREATE INDEX am_gin ON am_t USING gin (tags) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "CREATE INDEX am_gist ON am_t USING gist (pt) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "CREATE INDEX am_brin ON am_t USING brin (id) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "CREATE INDEX am_hash ON am_t USING hash (data) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "CREATE INDEX am_btree ON am_t USING btree (id) WITH (algorithm = 'lz4')" ); for my $idx (qw(am_gin am_gist am_brin am_hash am_btree)) { ok(has_sidecars($node, $idx), "CFS index $idx has sidecars"); like(reloptions($node, $idx), qr/algorithm=lz4/, "CFS index $idx stores policy"); } $node->safe_psql('postgres', "SET enable_seqscan = off"); $cnt = $node->safe_psql('postgres', "SELECT count(*) FROM am_t WHERE tags @> ARRAY[md5('1')]"); is($cnt, 1, 'gin CFS index usable'); $cnt = $node->safe_psql('postgres', "SELECT count(*) FROM am_t WHERE pt <@ box(point(0,0),point(5,5))"); is($cnt, 5, 'gist CFS index usable'); $cnt = $node->safe_psql('postgres', "SELECT count(*) FROM am_t WHERE id < 10"); is($cnt, 9, 'brin CFS index usable'); $cnt = $node->safe_psql('postgres', "SELECT count(*) FROM am_t WHERE data = md5('1')"); is($cnt, 1, 'hash CFS index usable'); # 7. REINDEX CONCURRENTLY preserves the index's effective CFS policy. my $policy_before = reloptions($node, 'am_gin'); $node->safe_psql('postgres', "REINDEX INDEX CONCURRENTLY am_gin"); $node->safe_psql('postgres', "CHECKPOINT"); my $policy_after = reloptions($node, 'am_gin'); is($policy_after, $policy_before, 'REINDEX CONCURRENTLY preserves index CFS reloptions'); ok(has_sidecars($node, 'am_gin'), 'REINDEX CONCURRENTLY keeps sidecars for CFS index'); # 8. zstd reloptions are accepted and stored (the policy layer is # codec-independent), and the index can be built and read back # through the CFS storage layer. $node->safe_psql('postgres', "CREATE INDEX zstd_store_idx ON base_t (id) " . "WITH (algorithm = 'zstd', level = 3)"); like(reloptions($node, 'zstd_store_idx'), qr/algorithm=zstd/, 'zstd index policy stored'); ok(has_sidecars($node, 'zstd_store_idx'), 'zstd index has sidecars'); $cnt = $node->safe_psql('postgres', "SET enable_seqscan = off; SELECT count(*) FROM base_t WHERE id = 1"); is($cnt, 1, 'zstd index is readable after build'); # 9. Reject CFS on a TEMP-table index. ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TEMP TABLE tmp_t (id int); " . "CREATE INDEX tmp_idx ON tmp_t (id) WITH (algorithm = 'lz4')"); isnt($ret, 0, 'CREATE INDEX WITH algorithm on TEMP table fails'); like( $stderr, qr/not supported for temporary tables/i, 'TEMP index rejects CFS'); $node->stop('immediate'); }; # --------------------------------------------------------------------------- # Edge cases for CFS reloptions # # Covers: ALTER TABLE RESET (algorithm) alone with explicit level and # min_gain_bytes present; a partition overriding the policy inherited from # the partitioned root; the effective min_gain_bytes default of 512; # min_gain_bytes boundaries at reloption and GUC level; per-algorithm # "level" boundaries (zstd 1..22, lz4 1..12); the explicit-only catalog # policy (nothing is frozen from the session GUCs, unset fields resolve # at runtime); ALTER TABLE ... SET (algorithm), SET UNLOGGED in one # statement; and the runtime-resolve model for indexes and TOAST # relations. # --------------------------------------------------------------------------- subtest 'CFS reloption edge cases' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_reloptions_edge'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $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 reloptions edge test'; } # min_gain_bytes effective default is 512. my $min_gain_default = $node->safe_psql('postgres', "SHOW cfs_default_min_gain_bytes"); is($min_gain_default, '512', 'cfs_default_min_gain_bytes GUC default is the canonical 512'); # A table created without an explicit min_gain_bytes / level stores # nothing for them (explicit-only reloptions contract: unset fields # resolve from the per-algorithm GUCs at write time, nothing is frozen # at DDL time). $node->safe_psql('postgres', "CREATE TABLE mg_t (id int, payload text) WITH (algorithm = 'lz4')"); is(reloptions($node, 'mg_t'), '{algorithm=lz4}', 'table without explicit auxiliary keys stores the algorithm alone'); # min_gain_bytes reloption boundaries and the GUC boundary. my ($ret, $stdout, $stderr); ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TABLE mg_neg (id int) " . "WITH (algorithm = 'lz4', min_gain_bytes = -10)"); isnt($ret, 0, 'min_gain_bytes = -10 rejected'); like($stderr, qr/min_gain_bytes/i, 'negative min_gain_bytes error'); ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TABLE mg_over (id int) " . "WITH (algorithm = 'lz4', min_gain_bytes = 8193)"); isnt($ret, 0, 'min_gain_bytes = 8193 rejected'); like($stderr, qr/min_gain_bytes/i, 'over-page min_gain_bytes error'); # 8192 is the valid upper bound (BLCKSZ). $node->safe_psql('postgres', "CREATE TABLE mg_max (id int) " . "WITH (algorithm = 'lz4', min_gain_bytes = 8192)"); like(reloptions($node, 'mg_max'), qr/min_gain_bytes=8192/, 'min_gain_bytes = 8192 accepted at boundary'); ($ret, $stdout, $stderr) = $node->psql('postgres', "SET cfs_default_min_gain_bytes = 8193"); isnt($ret, 0, 'GUC cfs_default_min_gain_bytes = 8193 rejected'); $node->safe_psql('postgres', "SET cfs_default_min_gain_bytes = 8192"); $node->safe_psql('postgres', "RESET cfs_default_min_gain_bytes"); # ALTER TABLE RESET (algorithm) ALONE with explicit level and # min_gain_bytes present must succeed: level/min_gain_bytes depend on # algorithm and are cleared together with it. $node->safe_psql('postgres', "CREATE TABLE reset_full_t (id int, payload text) " . "WITH (algorithm = 'lz4', level = 5, min_gain_bytes = 256)"); $node->safe_psql('postgres', "INSERT INTO reset_full_t SELECT g, repeat('rf-' || g, 40) " . "FROM generate_series(1, 200) g"); ok(has_sidecars($node, 'reset_full_t'), 'table with an explicit policy starts as CFS'); my $rf_ck_before = checksum_tbl($node, 'reset_full_t'); # RESET (algorithm) alone -- must NOT raise "algorithm must be # specified". $node->safe_psql('postgres', "CHECKPOINT"); $node->safe_psql('postgres', "ALTER TABLE reset_full_t RESET (algorithm)"); $node->safe_psql('postgres', "CHECKPOINT"); ok(!has_sidecars($node, 'reset_full_t'), 'RESET (algorithm) alone moves table back to plain storage'); is(reloptions($node, 'reset_full_t'), '', 'RESET (algorithm) cleared level and min_gain_bytes too'); is(checksum_tbl($node, 'reset_full_t'), $rf_ck_before, 'RESET (algorithm) preserves data'); # Resetting just level (algorithm still present) must work too. Under # the explicit-only reloptions contract RESET (level) removes the key # from the catalog and the field returns to runtime resolve from the # session's per-algorithm GUC — no value is frozen in its place. $node->safe_psql('postgres', "CREATE TABLE reset_lvl_t (id int) WITH (algorithm = 'lz4', level = 5)" ); $node->safe_psql('postgres', "ALTER TABLE reset_lvl_t RESET (level)"); is(reloptions($node, 'reset_lvl_t'), '{algorithm=lz4}', 'RESET (level) removes the key, algorithm intact'); # RESET (level) succeeds regardless of the session GUC values: the GUCs # are never validated against an algorithm at DDL time (each per- # algorithm GUC applies only to its own algorithm). $node->safe_psql('postgres', "CREATE TABLE reset_lvl2_t (id int) WITH (algorithm = 'lz4', level = 5)" ); $node->safe_psql('postgres', "SET cfs_default_zstd_level = 22; ALTER TABLE reset_lvl2_t RESET (level)" ); is(reloptions($node, 'reset_lvl2_t'), '{algorithm=lz4}', 'RESET (level) works with a wide zstd GUC value'); # A partition may override the policy inherited from the partitioned # root (no "parameter specified more than once" error). $node->safe_psql('postgres', "CREATE TABLE parent (id int, dt date) PARTITION BY RANGE (dt) " . "WITH (algorithm = 'lz4', level = 3)"); $node->safe_psql('postgres', "CREATE TABLE part_inh PARTITION OF parent " . "FOR VALUES FROM ('2025-01-01') TO ('2025-02-01')"); like(reloptions($node, 'part_inh'), qr/algorithm=lz4/, 'partition without explicit policy inherits root algorithm'); # The override boundary: explicit policy on the partition itself. $node->safe_psql('postgres', "CREATE TABLE part_ovr PARTITION OF parent " . "FOR VALUES FROM ('2025-02-01') TO ('2025-03-01') " . "WITH (algorithm = 'zstd', level = 5)"); like(reloptions($node, 'part_ovr'), qr/algorithm=zstd/, 'partition overrides root algorithm'); like(reloptions($node, 'part_ovr'), qr/level=5/, 'partition override stores its own level'); like(reloptions($node, 'parent'), qr/algorithm=lz4/, 'parent policy unchanged by partition override'); # Overriding just the level while keeping the inherited algorithm # family is not expressible (level requires algorithm), but a # partition can re-state the algorithm and change level together, # which is the documented contract. $node->safe_psql('postgres', "CREATE TABLE part_ovr2 PARTITION OF parent " . "FOR VALUES FROM ('2025-03-01') TO ('2025-04-01') " . "WITH (algorithm = 'lz4', level = 9)"); like( reloptions($node, 'part_ovr2'), qr/algorithm=lz4.*level=9|level=9.*algorithm=lz4/, 'partition may re-state the same algorithm with a different level'); # Per-algorithm "level" boundaries: the validator uses the codec # range. zstd accepts 1..22, rejects 0 and 23; lz4 accepts 1..12, # rejects 0 and 13. ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TABLE lvl_z0 (id int) WITH (algorithm = 'zstd', level = 0)"); isnt($ret, 0, 'zstd level=0 rejected (below min)'); like($stderr, qr/level/i, 'zstd level=0 error mentions level'); ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TABLE lvl_z23 (id int) WITH (algorithm = 'zstd', level = 23)" ); isnt($ret, 0, 'zstd level=23 rejected (above zstd max 22)'); like($stderr, qr/level/i, 'zstd level=23 error mentions level'); # zstd: valid boundaries. $node->safe_psql('postgres', "CREATE TABLE lvl_z1 (id int) WITH (algorithm = 'zstd', level = 1)"); like(reloptions($node, 'lvl_z1'), qr/level=1/, 'zstd level=1 accepted (min boundary)'); $node->safe_psql('postgres', "CREATE TABLE lvl_z22 (id int) WITH (algorithm = 'zstd', level = 22)" ); like(reloptions($node, 'lvl_z22'), qr/level=22/, 'zstd level=22 accepted (max boundary)'); # lz4: algorithm-specific range is 1..12 (narrower than zstd). ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TABLE lvl_l0 (id int) WITH (algorithm = 'lz4', level = 0)"); isnt($ret, 0, 'lz4 level=0 rejected (below min)'); like($stderr, qr/level/i, 'lz4 level=0 error mentions level'); ($ret, $stdout, $stderr) = $node->psql('postgres', "CREATE TABLE lvl_l13 (id int) WITH (algorithm = 'lz4', level = 13)"); isnt($ret, 0, 'lz4 level=13 rejected (above lz4 max 12, within zstd range)'); like($stderr, qr/level/i, 'lz4 level=13 error mentions level'); # lz4 level=12 is the valid upper bound (not 22, which zstd would # accept). $node->safe_psql('postgres', "CREATE TABLE lvl_l12 (id int) WITH (algorithm = 'lz4', level = 12)"); like(reloptions($node, 'lvl_l12'), qr/level=12/, 'lz4 level=12 accepted (algorithm-specific max boundary)'); # The per-algorithm GUCs are never validated against an algorithm at # DDL time: each applies only to its own algorithm, so an out-of- # range value for one algorithm cannot hinder creating a relation # with another one, and an unset level stores nothing at all (no # cross-field GUC error class exists anymore). # # cfs_default_* are PGC_USERSET, so each SET+DDL pair runs in a # single psql session (a SET in one safe_psql() call does not persist # to the next). # GUC 20: beyond the lz4 range (max 12) — the lz4 table is still # created, storing the algorithm alone. ($ret, $stdout, $stderr) = $node->psql('postgres', "SET cfs_default_zstd_level = 20; " . "CREATE TABLE guc_lz4 (id int, data text) WITH (algorithm = 'lz4')" ); is($ret, 0, 'lz4 with a wide zstd GUC value is created'); is(reloptions($node, 'guc_lz4'), '{algorithm=lz4}', 'nothing of the GUC is stored for an unset level'); # GUC 20: valid for zstd (max 22). Same session, different algorithm, # nothing stored either. $node->safe_psql('postgres', "SET cfs_default_zstd_level = 20; " . "CREATE TABLE guc_zstd (id int, data text) WITH (algorithm = 'zstd')" ); like(reloptions($node, 'guc_zstd'), qr/algorithm=zstd/, 'zstd table created, algorithm alone stored'); # GUC 13: beyond the lz4 boundary, valid for zstd — same story. $node->safe_psql('postgres', "SET cfs_default_zstd_level = 13; " . "CREATE TABLE guc_zstd_b (id int) WITH (algorithm = 'zstd')"); like(reloptions($node, 'guc_zstd_b'), qr/algorithm=zstd/, 'zstd still created with GUC level 13'); # Index path: an index carrying its own algorithm goes through the # same explicit-only validator as a table — an explicit out-of-range # level is still rejected there (covered above); the GUC never is. $node->safe_psql('postgres', "SET cfs_default_zstd_level = 13; " . "CREATE INDEX guc_idx_lz4 ON guc_zstd (id) WITH (algorithm = 'lz4')" ); is(reloptions($node, 'guc_idx_lz4'), '{algorithm=lz4}', 'index path validates explicit values only'); # Runtime resolve: a session-level cfs_default_lz4_level change # affects the very next write, and the stored policy never changes. $node->safe_psql('postgres', "CREATE TABLE freeze_lz4 (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('postgres', "INSERT INTO freeze_lz4 SELECT g, repeat('fr', 100) " . "FROM generate_series(1, 50) g"); # Fresh session, GUC at the lz4 maximum: the insert is written with # that level, succeeds, and the stored policy stays the algorithm # alone (an out-of-range value cannot even be SET anymore — the # per-algorithm GUC range makes the old cross-check unnecessary). $node->safe_psql('postgres', "SET cfs_default_lz4_level = 12; " . "INSERT INTO freeze_lz4 SELECT 999, repeat('x', 100)"); is(reloptions($node, 'freeze_lz4'), '{algorithm=lz4}', 'session GUC change does not alter the stored policy'); is($node->safe_psql('postgres', "SELECT count(*) FROM freeze_lz4"), '51', 'insert with a raised session GUC succeeds'); # ... and a NEW table also stores nothing from the GUC (no DDL-time # freeze at all). $node->safe_psql('postgres', "SET cfs_default_zstd_level = 20; " . "CREATE TABLE freeze_zstd (id int) WITH (algorithm = 'zstd')"); is(reloptions($node, 'freeze_zstd'), '{algorithm=zstd}', 'GUC at DDL time is not frozen into the new table'); # ALTER TABLE ... SET (algorithm), SET UNLOGGED in ONE statement must # not create the forbidden UNLOGGED + CFS configuration: the # persistence check sees the pre-CFS reloptions and the reloptions # check sees the pre-UNLOGGED persistence, so the rewrite phase # re-verifies the final configuration. $node->safe_psql('postgres', "CREATE TABLE unlog_combo_t (id int, payload text)"); $node->safe_psql('postgres', "INSERT INTO unlog_combo_t SELECT g, repeat('uc', 100) " . "FROM generate_series(1, 50) g"); ($ret, $stdout, $stderr) = $node->psql('postgres', "ALTER TABLE unlog_combo_t SET (algorithm = 'lz4'), SET UNLOGGED"); isnt($ret, 0, 'combined SET (algorithm), SET UNLOGGED is rejected'); like($stderr, qr/CFS/i, 'error explains the CFS/UNLOGGED incompatibility'); # The failed statement must leave the table untouched. is( $node->safe_psql( 'postgres', "SELECT relpersistence FROM pg_class WHERE oid = 'unlog_combo_t'::regclass" ), 'p', 'table stays permanent after the rejected statement'); is(reloptions($node, 'unlog_combo_t'), '', 'table has no CFS reloptions after the rejected statement'); # Subcommand order does not matter. ($ret, $stdout, $stderr) = $node->psql('postgres', "ALTER TABLE unlog_combo_t SET UNLOGGED, SET (algorithm = 'lz4')"); isnt($ret, 0, 'SET UNLOGGED, SET (algorithm) is rejected too'); is( $node->safe_psql( 'postgres', "SELECT relpersistence FROM pg_class WHERE oid = 'unlog_combo_t'::regclass" ), 'p', 'table still permanent after the reverse-order attempt'); # Control: CFS on a permanent table works, and the two separate steps # fail at the second one. $node->safe_psql('postgres', "ALTER TABLE unlog_combo_t SET (algorithm = 'lz4')"); like(reloptions($node, 'unlog_combo_t'), qr/algorithm=lz4/, 'SET (algorithm) alone on a permanent table works'); ($ret, $stdout, $stderr) = $node->psql('postgres', "ALTER TABLE unlog_combo_t SET UNLOGGED"); isnt($ret, 0, 'SET UNLOGGED alone on a CFS table is rejected'); is( $node->safe_psql( 'postgres', "SELECT relpersistence FROM pg_class WHERE oid = 'unlog_combo_t'::regclass" ), 'p', 'CFS table stays permanent'); # Unified explicit-only policy model for CFS objects: # * an index without explicit CFS reloptions stores the parent # table's algorithm plus its explicitly stored auxiliary keys at # CREATE INDEX and is independent afterwards; # * a TOAST relation stores no CFS options of its own — its policy # follows the owning table at runtime — so its stored reloptions # stay empty regardless of the table's ALTERs. my $cfs_info = sub { my ($rel, $field) = @_; return $node->safe_psql('postgres', "SELECT (pg_cfs_relation_info('$rel'::regclass)).$field"); }; $node->safe_psql('postgres', "CREATE TABLE freeze_t (id int, payload text) " . "WITH (algorithm = 'lz4', level = 3)"); $node->safe_psql('postgres', "CREATE INDEX freeze_idx ON freeze_t (id)"); $node->safe_psql('postgres', "CREATE INDEX freeze_own ON freeze_t (id) WITH (algorithm = 'lz4', level = 2)" ); like(reloptions($node, 'freeze_idx'), qr/algorithm=lz4.*level=3/, 'index without policy inherits the table explicit keys'); is($cfs_info->('freeze_idx', 'level'), '3', 'inheriting index starts at the table explicit level'); $node->safe_psql('postgres', "ALTER TABLE freeze_t SET (level = 9)"); is($cfs_info->('freeze_idx', 'level'), '3', 'inheriting index does NOT follow the table level change'); is($cfs_info->('freeze_own', 'level'), '2', 'index with explicit policy does not follow the table'); # TOAST: the toast relation stores no CFS options of its own — its # policy follows the owning table at runtime — so its stored options # never change, whatever the table's ALTERs do. my $freeze_toid = "(SELECT reltoastrelid FROM pg_class WHERE oid = 'freeze_t'::regclass)"; is( $node->safe_psql( 'postgres', "SELECT coalesce(reloptions::text, '') FROM pg_class " . "WHERE oid = $freeze_toid"), '', 'toast reloptions stay empty across SET (level)'); $node->safe_psql('postgres', "ALTER TABLE freeze_t RESET (algorithm)"); is( $node->safe_psql( 'postgres', "SELECT coalesce(reloptions::text, '') FROM pg_class " . "WHERE oid = $freeze_toid"), '', 'toast reloptions stay empty across RESET (algorithm)'); $node->safe_psql('postgres', "ALTER TABLE freeze_t SET (algorithm = 'zstd')"); is( $node->safe_psql( 'postgres', "SELECT coalesce(reloptions::text, '') FROM pg_class " . "WHERE oid = $freeze_toid"), '', 'toast reloptions stay empty across SET (algorithm)'); # The table's stored policy is exactly what was spelled out: nothing # is frozen from the session GUCs at DDL time, and the toast relation # stores no CFS options at all (its policy is resolved from the parent # at runtime). $node->safe_psql('postgres', "SET cfs_default_lz4_level = 7; " . "CREATE TABLE freeze_g (id int, payload text) WITH (algorithm = 'lz4')" ); is( $node->safe_psql( 'postgres', "SELECT coalesce(reloptions::text, '') FROM pg_class WHERE oid = " . "(SELECT reltoastrelid FROM pg_class " . "WHERE oid = 'freeze_g'::regclass)"), '', 'toast stores no CFS options of its own'); # RESET (level) on a policy without an explicit level is a no-op: the # catalog keeps the algorithm alone and the field stays runtime. $node->safe_psql('postgres', "ALTER TABLE freeze_g RESET (level)"); is(reloptions($node, 'freeze_g'), '{algorithm=lz4}', 'RESET (level) without a stored level is a no-op'); $node->stop('immediate'); }; # --------------------------------------------------------------------------- # SQL interface and monitoring # # Exercises the user-facing observability and administration surface: # pg_cfs_relation_info, pg_cfs_relation_size, pg_cfs_check, # pg_cfs_reset_stats, pg_cfs_estimate_compression, pg_cfs_compact; the # pg_cfs_settings, pg_stat_cfs and pg_stat_progress_cfs_compact views; the # background-worker control functions pg_cfs_bgworker_pause / _resume / # _status; and the CFS wait events registered in pg_wait_events. # --------------------------------------------------------------------------- subtest 'SQL interface and monitoring' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_sql'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; # Skip when neither codec is available: the test creates CFS relations. my $configure = $node->safe_psql('postgres', "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'"); if ($configure !~ /--with-lz4/ && $configure !~ /--with-zstd/) { plan skip_all => 'no LZ4/Zstd support built, skipping CFS SQL test'; } my $has_lz4 = ($configure =~ /--with-lz4/) ? 1 : 0; my $has_zstd = ($configure =~ /--with-zstd/) ? 1 : 0; my $algo = $has_zstd ? 'zstd' : 'lz4'; # Setup: one CFS table, one plain table. $node->safe_psql('postgres', "CREATE TABLE cfs_t (id int, payload text) WITH (algorithm='$algo');" ); $node->safe_psql('postgres', "CREATE TABLE plain_t (id int, payload text);"); $node->safe_psql('postgres', "INSERT INTO cfs_t SELECT g, repeat('x', 200) FROM generate_series(1,2000) g;" ); $node->safe_psql('postgres', "INSERT INTO plain_t SELECT g, repeat('x', 200) FROM generate_series(1,2000) g;" ); $node->safe_psql('postgres', "CHECKPOINT;"); # pg_cfs_relation_info is( $node->safe_psql( 'postgres', "SELECT is_cfs, algorithm, is_supported FROM pg_cfs_relation_info('cfs_t');" ), "t|$algo|t", "pg_cfs_relation_info marks cfs_t as CFS"); is( $node->safe_psql( 'postgres', "SELECT is_cfs, algorithm IS NULL, is_supported FROM pg_cfs_relation_info('plain_t');" ), "f|t|t", "pg_cfs_relation_info marks plain_t as non-CFS (algorithm NULL)"); # pg_cfs_settings view is( $node->safe_psql( 'postgres', "SELECT is_cfs, algorithm FROM pg_cfs_settings WHERE relname='cfs_t';" ), "t|$algo", "pg_cfs_settings lists cfs_t as CFS"); is( $node->safe_psql( 'postgres', "SELECT is_cfs, algorithm IS NULL FROM pg_cfs_settings WHERE relname='plain_t';" ), "f|t", "pg_cfs_settings lists plain_t as non-CFS"); # pg_stat_cfs view reports the CFS relation with non-zero sizes. is( $node->safe_psql( 'postgres', "SELECT algorithm, logical_size > 0, physical_size > 0 FROM pg_stat_cfs WHERE relname='cfs_t';" ), "$algo|t|t", "pg_stat_cfs reports cfs_t sizes"); # Mapped catalogs (pg_database has no relfilenumber of its own, unlike # pg_class, which has a real one) and session TEMP tables are not CFS # candidates: the view must skip them early, before even building a # storage path for them. The TEMP table has to live in the same psql # session as the probe, hence the single safe_psql call. is( $node->safe_psql( 'postgres', "CREATE TEMP TABLE cfs_tmp_not_cfs (id int); SELECT count(*) FROM pg_stat_cfs WHERE relid IN ('pg_class'::regclass, 'pg_database'::regclass, 'cfs_tmp_not_cfs'::regclass);" ), "0", "pg_stat_cfs skips mapped catalogs and session TEMP tables"); # Monitoring views must survive concurrent DDL: the SRFs resolve each # row's policy by opening the relation, and a concurrent DROP can make # that open fail against the live catalog. Like pg_relation_size # (dbsize.c), the views skip such a row instead of aborting the whole # query. The failure is a race, so the test is statistical: this # session hammers both views while a background session churns # CREATE/DROP of a CFS table. Every DDL statement must be its own # transaction (autocommit) - one DO block would hide the table from # other sessions until the final commit and the race could not happen. my $churn_sql = ""; for my $i (1 .. 300) { $churn_sql .= "CREATE TABLE cfs_race_t (id int) WITH (algorithm='$algo'); " . "DROP TABLE cfs_race_t;\n"; } my $churn = $node->background_psql('postgres', on_error_stop => 0); $churn->query_until(qr/CHURN_READY/, "\\echo CHURN_READY\n$churn_sql\\echo CHURN_DONE\n"); my $scan_failures = 0; my $first_failure = ''; for my $scan (1 .. 60) { my ($sret, $sout, $serr) = $node->psql('postgres', "SELECT count(*) FROM pg_cfs_settings; SELECT count(*) FROM pg_stat_cfs;" ); if ($sret != 0) { $scan_failures++; $first_failure ||= $serr; } } $churn->query_until(qr/CHURN_DONE/, ''); $churn->quit; ok( $scan_failures == 0, "monitoring views survive concurrent CREATE/DROP churn" . ($scan_failures ? " (first failure: $first_failure)" : "")); # pg_cfs_relation_size is( $node->safe_psql( 'postgres', "SELECT logical_size > 0, physical_size >= 0 FROM pg_cfs_relation_size('cfs_t');" ), "t|t", "pg_cfs_relation_size returns sizes"); # pg_cfs_check (default and deep) is( $node->safe_psql( 'postgres', "SELECT ok, is_cfs, errors FROM pg_cfs_check('cfs_t');"), "t|t|0", "pg_cfs_check ok on cfs_t"); is( $node->safe_psql( 'postgres', "SELECT ok, is_cfs FROM pg_cfs_check('cfs_t', true);" ), "t|t", "pg_cfs_check deep ok on cfs_t"); is( $node->safe_psql( 'postgres', "SELECT ok, is_cfs FROM pg_cfs_check('plain_t');"), "t|f", "pg_cfs_check on non-CFS relation returns ok/is_cfs=false"); # Relations whose rd_options is NOT a StdRdOptions struct (views, # composite types, sequences) must never be cast to StdRdOptions: that # reads unrelated memory and yields a random CFS policy. The # information functions must return is_cfs=false with zeroed fields # and never ERROR or crash. $node->safe_psql('postgres', "CREATE VIEW cfs_v AS SELECT 1 AS a;"); $node->safe_psql('postgres', "CREATE OR REPLACE VIEW cfs_v WITH (security_barrier = true) AS SELECT 1 AS a;" ); is( $node->safe_psql( 'postgres', "SELECT is_cfs, algorithm IS NULL, is_supported FROM pg_cfs_relation_info('cfs_v');" ), "f|t|f", "pg_cfs_relation_info on a view returns is_cfs=false, not supported"); is( $node->safe_psql( 'postgres', "SELECT ok, is_cfs, errors FROM pg_cfs_check('cfs_v');"), "t|f|0", "pg_cfs_check on a view returns ok/is_cfs=false without ERROR"); # security_invoker is another ViewOptions field. $node->safe_psql('postgres', "CREATE OR REPLACE VIEW cfs_v WITH (security_invoker = true) AS SELECT 1 AS a;" ); is( $node->safe_psql( 'postgres', "SELECT ok, is_cfs FROM pg_cfs_check('cfs_v');"), "t|f", "pg_cfs_check on a security_invoker view returns is_cfs=false"); # A composite type and a sequence also use non-StdRdOptions reloptions. $node->safe_psql('postgres', "CREATE TYPE cfs_typ AS (a int, b text);"); $node->safe_psql('postgres', "CREATE SEQUENCE cfs_seq;"); is( $node->safe_psql( 'postgres', "SELECT is_cfs, is_supported FROM pg_cfs_relation_info('cfs_typ');" ), "f|f", "pg_cfs_relation_info on a composite type returns is_cfs=false"); is( $node->safe_psql( 'postgres', "SELECT ok, is_cfs FROM pg_cfs_check('cfs_seq');"), "t|f", "pg_cfs_check on a sequence returns is_cfs=false"); # The server survived every call on non-StdRdOptions relations (a # crashed backend would have taken the connection down with it). is($node->safe_psql('postgres', "SELECT 1;"), "1", "backend alive after CFS calls on view/type/sequence"); $node->safe_psql('postgres', "DROP VIEW cfs_v; DROP TYPE cfs_typ; DROP SEQUENCE cfs_seq;"); # pg_cfs_estimate_compression is read-only and returns sensible # numbers. Capture reloptions before/after to prove no change. my $relopts_before = $node->safe_psql('postgres', "SELECT coalesce(reloptions::text,'') FROM pg_class WHERE relname='plain_t';" ); is( $node->safe_psql( 'postgres', "SELECT sampled_pages > 0, estimated_compression_ratio > 0 FROM pg_cfs_estimate_compression('plain_t','$algo');" ), "t|t", "pg_cfs_estimate_compression samples pages"); my $relopts_after = $node->safe_psql('postgres', "SELECT coalesce(reloptions::text,'') FROM pg_class WHERE relname='plain_t';" ); is($relopts_before, $relopts_after, "pg_cfs_estimate_compression does not change reloptions"); is( $node->safe_psql( 'postgres', "SELECT sampled_pages > 0 FROM pg_cfs_estimate_compression('cfs_t','$algo',3,10);" ), "t", "pg_cfs_estimate_compression works on a CFS relation"); my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT * FROM pg_cfs_estimate_compression('plain_t','bogus');"); ok($ret != 0, "pg_cfs_estimate_compression rejects unknown algorithm"); # NULL-argument handling. pg_cfs_estimate_compression is deliberately # not strict (its "level DEFAULT NULL" must reach the C function), so # the required arguments are validated by hand: a NULL there must # raise a clean SQL error, not crash the backend. pg_cfs_check is # STRICT, so a NULL argument must deterministically yield a NULL # result without a call. ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_estimate_compression(NULL, '$algo');"); ok( $ret != 0 && $stderr =~ /argument "relation" must not be null/, "pg_cfs_estimate_compression rejects NULL relation"); ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_estimate_compression('plain_t', NULL);"); ok( $ret != 0 && $stderr =~ /argument "algorithm" must not be null/, "pg_cfs_estimate_compression rejects NULL algorithm"); ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_estimate_compression('plain_t', '$algo', 3, NULL);"); ok( $ret != 0 && $stderr =~ /argument "sample_pct" must not be null/, "pg_cfs_estimate_compression rejects NULL sample_pct"); ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_estimate_compression('plain_t', '$algo', 3, 'NaN');"); ok( $ret != 0 && $stderr =~ /sample_pct must be between/, "pg_cfs_estimate_compression rejects NaN sample_pct"); # NULL level is documented input: it selects the server default level. is( $node->safe_psql( 'postgres', "SELECT sampled_pages > 0 FROM pg_cfs_estimate_compression('plain_t', '$algo', NULL, 10);" ), "t", "pg_cfs_estimate_compression accepts NULL level (server default)"); is( $node->safe_psql( 'postgres', "SELECT pg_cfs_check(NULL, NULL) IS NULL;"), "t", "STRICT pg_cfs_check returns NULL on NULL input"); # Pin the intended strictness contract in the catalog. is( $node->safe_psql( 'postgres', "SELECT proisstrict FROM pg_proc WHERE proname = 'pg_cfs_check';" ), "t", "pg_cfs_check is STRICT in the catalog"); is( $node->safe_psql( 'postgres', "SELECT proisstrict FROM pg_proc WHERE proname = 'pg_cfs_estimate_compression';" ), "f", "pg_cfs_estimate_compression is deliberately not strict"); # The server survived every NULL call above (a crashed backend would # have taken the connection down with it). is($node->safe_psql('postgres', "SELECT 1;"), "1", "backend is still alive after NULL-argument calls"); # pg_cfs_reset_stats $node->safe_psql('postgres', "SELECT pg_cfs_reset_stats('cfs_t');"); is( $node->safe_psql( 'postgres', "SELECT write_count = 0 FROM pg_stat_cfs WHERE relname='cfs_t';"), "t", "pg_cfs_reset_stats clears one relation"); $node->safe_psql('postgres', "SELECT pg_cfs_reset_stats();"); # After reset, every row should report zero counters. is( $node->safe_psql( 'postgres', "SELECT count(*) FROM pg_stat_cfs WHERE write_count <> 0 OR read_count <> 0;" ), "0", "pg_cfs_reset_stats() clears all relations"); # pg_cfs_compact runs synchronously and records last_compaction. $node->safe_psql('postgres', "UPDATE cfs_t SET payload = repeat('y', 200) WHERE id < 1000;"); $node->safe_psql('postgres', "CHECKPOINT;"); like($node->safe_psql('postgres', "SELECT pg_cfs_compact('cfs_t');"), qr/compacted/i, "pg_cfs_compact returns a summary"); is( $node->safe_psql( 'postgres', "SELECT last_compaction IS NOT NULL FROM pg_stat_cfs WHERE relname='cfs_t';" ), "t", "pg_stat_cfs.last_compaction is set after compaction"); ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_compact('plain_t');"); ok($ret != 0, "pg_cfs_compact on a non-CFS relation raises an error"); # pg_stat_progress_cfs_compact exists and is empty when idle. is( $node->safe_psql( 'postgres', "SELECT count(*) FROM pg_stat_progress_cfs_compact;"), "0", "pg_stat_progress_cfs_compact is empty when idle"); # started_at is an absolute point in time (timestamp with time zone), # like every other statistics timestamp: param4 is a TimestampTz # (microseconds since 2000-01-01 UTC), and the view must not strip # the zone while reconstructing the value. is( $node->safe_psql( 'postgres', "SELECT data_type FROM information_schema.columns " . "WHERE table_name = 'pg_stat_progress_cfs_compact' " . "AND column_name = 'started_at';"), "timestamp with time zone", "pg_stat_progress_cfs_compact.started_at is timestamptz"); # Background-worker pause / resume / status. # Pause without a duration (indefinite pause) — the DEFAULT NULL must # be accepted so callers may omit the argument. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause();"); is( $node->safe_psql( 'postgres', "SELECT paused, paused_until IS NULL FROM pg_cfs_bgworker_status();" ), "t|t", "pg_cfs_bgworker_pause() without duration sets paused=true, no expiry" ); $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume();"); # Pause with a duration. $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_pause(interval '1 hour');"); is( $node->safe_psql( 'postgres', "SELECT paused, paused_until IS NOT NULL FROM pg_cfs_bgworker_status();" ), "t|t", "pg_cfs_bgworker_pause(interval) sets paused=true with an expiry"); # A non-positive duration must be rejected outright: a negative or # zero interval would put paused_until in the past, so the pause # would silently "self-heal" while the call reports success. my $pause_deadline = $node->safe_psql('postgres', "SELECT paused_until::text FROM pg_cfs_bgworker_status();"); ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_bgworker_pause(interval '-1 hour');"); ok( $ret != 0 && $stderr =~ /pause duration must be positive/, "pg_cfs_bgworker_pause rejects a negative duration"); ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT pg_cfs_bgworker_pause(interval '0 seconds');"); ok( $ret != 0 && $stderr =~ /pause duration must be positive/, "pg_cfs_bgworker_pause rejects a zero duration"); is( $node->safe_psql( 'postgres', "SELECT paused, paused_until::text FROM pg_cfs_bgworker_status();" ), "t|$pause_deadline", "a rejected duration leaves the active pause untouched"); # A manual compaction still works while the worker is paused. is( $node->safe_psql( 'postgres', "SELECT pg_cfs_compact('cfs_t') IS NOT NULL;"), "t", "manual pg_cfs_compact works while the worker is paused"); $node->safe_psql('postgres', "SELECT pg_cfs_bgworker_resume();"); is( $node->safe_psql( 'postgres', "SELECT paused FROM pg_cfs_bgworker_status();"), "f", "pg_cfs_bgworker_resume clears the pause"); # Access control: the administrative functions are revoked from PUBLIC # at initdb time, and pg_cfs_compact additionally requires ownership # of the relation (the same model as VACUUM FULL / CLUSTER). $node->safe_psql('postgres', "CREATE ROLE cfs_alice;"); $node->safe_psql('postgres', "CREATE ROLE cfs_bob;"); # A non-superuser role gets "permission denied" for every # administrative function. Read-only diagnostics stay public on # purpose. for my $call ( "pg_cfs_compact('cfs_t')", "pg_cfs_check('cfs_t', true)", "pg_cfs_estimate_compression('cfs_t', '$algo')", "pg_cfs_reset_stats('cfs_t')", "pg_cfs_reset_stats()", "pg_cfs_bgworker_pause(interval '1 hour')", "pg_cfs_bgworker_resume()") { ($ret, $stdout, $stderr) = $node->psql('postgres', "SET ROLE cfs_alice; SELECT $call;"); ok($ret != 0 && $stderr =~ /permission denied for function/, "non-privileged role cannot call $call"); } is( $node->safe_psql( 'postgres', "SET ROLE cfs_alice; SELECT is_cfs FROM pg_cfs_relation_info('cfs_t');" ), "t", "read-only pg_cfs_relation_info stays public"); is( $node->safe_psql( 'postgres', "SET ROLE cfs_alice; SELECT paused FROM pg_cfs_bgworker_status();" ), "f", "read-only pg_cfs_bgworker_status stays public"); # EXECUTE is the cost boundary for pg_cfs_check: once granted, the # deep check (IO proportional to the relation size) runs fine. $node->safe_psql('postgres', "GRANT EXECUTE ON FUNCTION pg_cfs_check(regclass, boolean) TO cfs_alice;" ); is( $node->safe_psql( 'postgres', "SET ROLE cfs_alice; SELECT ok FROM pg_cfs_check('cfs_t', true);" ), "t", "pg_cfs_check runs for a role with EXECUTE granted"); # The same model covers pg_cfs_estimate_compression: with EXECUTE # granted, the sampling estimate runs for a non-superuser. $node->safe_psql('postgres', "GRANT EXECUTE ON FUNCTION pg_cfs_estimate_compression(regclass, text, integer, real) TO cfs_alice;" ); is( $node->safe_psql( 'postgres', "SET ROLE cfs_alice; SELECT sampled_pages > 0 FROM pg_cfs_estimate_compression('cfs_t', '$algo');" ), "t", "pg_cfs_estimate_compression runs for a role with EXECUTE granted"); # EXECUTE alone is not enough for pg_cfs_compact: the caller must also # own the relation. $node->safe_psql('postgres', "GRANT EXECUTE ON FUNCTION pg_cfs_compact(regclass) TO cfs_bob;"); ($ret, $stdout, $stderr) = $node->psql('postgres', "SET ROLE cfs_bob; SELECT pg_cfs_compact('cfs_t');"); ok($ret != 0 && $stderr =~ /must be owner of/, "pg_cfs_compact denied to a non-owner with EXECUTE granted"); # The owner may compact its own relation once EXECUTE is granted. $node->safe_psql('postgres', "CREATE TABLE bob_t (id int) WITH (algorithm='$algo');"); $node->safe_psql('postgres', "INSERT INTO bob_t SELECT generate_series(1,100);"); $node->safe_psql('postgres', "ALTER TABLE bob_t OWNER TO cfs_bob;"); is( $node->safe_psql( 'postgres', "SET ROLE cfs_bob; SELECT pg_cfs_compact('bob_t') IS NOT NULL;"), "t", "relation owner can run pg_cfs_compact"); # CFS wait events are registered in pg_wait_events. my $events = $node->safe_psql('postgres', "SELECT string_agg(name, ',' ORDER BY name) FROM pg_wait_events WHERE name LIKE 'Cfs%';" ); like($events, qr/CfsCompact/, "CfsCompact wait event registered"); like($events, qr/CfsFsync/, "CfsFsync wait event registered"); like($events, qr/CfsJournalReplay/, "CfsJournalReplay wait event registered"); like($events, qr/CfsRead/, "CfsRead wait event registered"); like($events, qr/CfsWrite/, "CfsWrite wait event registered"); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Standard utilities and contrib on CFS relations # # Exercises the CFS-aware behaviour of the standard PostgreSQL tooling: # pg_relation_size() / pg_total_relation_size() account for the sidecar # bytes; pg_basebackup copies sidecars into the backup; pg_verifybackup # verifies a manifest that includes sidecars and detects a corrupted one; # pg_checksums skips sidecars on an offline cluster; the contrib # extensions pageinspect, amcheck and pgstattuple operate on CFS tables # through the buffer manager. # # pg_upgrade compatibility is verified at build time: pg_upgrade is # rebuilt against the same source and the format-version check runs as # part of `pg_upgrade --check`; a full end-to-end upgrade is the # responsibility of the pg_upgrade test suite. # --------------------------------------------------------------------------- subtest 'standard utilities on CFS relations' => sub { # Initialise a primary that can serve a base backup. my $node = PostgreSQL::Test::Cluster->new('cfs_util'); $node->init(allows_streaming => 1); $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s"); $node->start; # Skip when LZ4 was not compiled in: it is the only algorithm this # section exercises and CREATE TABLE would otherwise fail. 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 utilities test'; } # Setup: a CFS table with some data, a plain (non-CFS) table for # contrast, and a btree index on the CFS table (which itself inherits # the policy). $node->safe_psql('postgres', "CREATE TABLE cfs_t (id int PRIMARY KEY, payload text) " . "WITH (algorithm = 'lz4')"); $node->safe_psql('postgres', "INSERT INTO cfs_t SELECT g, repeat('utility-' || g, 80) " . "FROM generate_series(1, 500) g"); $node->safe_psql('postgres', "CREATE TABLE plain_t (id int PRIMARY KEY, payload text)"); $node->safe_psql('postgres', "INSERT INTO plain_t SELECT g, repeat('plain-' || g, 80) " . "FROM generate_series(1, 500) g"); # Flush everything through the CFS write path and persist the map # snapshot. $node->safe_psql('postgres', 'CHECKPOINT'); my $cfs_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('cfs_t')"); my $plain_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('plain_t')"); my $data_dir = $node->data_dir; # Sanity: sidecars exist for the CFS relation and not for the plain # one. ok(-f "$data_dir/$cfs_path.cfp", '.cfp exists for CFS table'); ok(-f "$data_dir/$cfs_path.cfsmap", '.cfsmap exists for CFS table'); ok(-f "$data_dir/$cfs_path.cfsjrn", '.cfsjrn exists for CFS table'); ok(!-f "$data_dir/$plain_path.cfp", 'plain table has no .cfp sidecar'); # Size functions account for sidecars. # # pg_relation_size(cfs_t, 'main') must include the physical bytes of # the sidecar files, not report ~0 (the base main-fork file is only a # marker). pg_total_relation_size must be >= the sidecar bytes as # well. my $cfp_size = -s "$data_dir/$cfs_path.cfp"; my $cfsmap_size = -s "$data_dir/$cfs_path.cfsmap"; my $cfsjrn_size = -s "$data_dir/$cfs_path.cfsjrn"; my $sidecar_bytes = $cfp_size + $cfsmap_size + $cfsjrn_size; my $cfs_rel_size = $node->safe_psql('postgres', "SELECT pg_relation_size('cfs_t', 'main')"); my $cfs_total_size = $node->safe_psql('postgres', "SELECT pg_total_relation_size('cfs_t')"); my $plain_rel_size = $node->safe_psql('postgres', "SELECT pg_relation_size('plain_t', 'main')"); cmp_ok($cfs_rel_size, '>=', $sidecar_bytes, 'pg_relation_size(CFS, main) includes sidecar bytes'); cmp_ok($cfs_total_size, '>=', $sidecar_bytes, 'pg_total_relation_size(CFS) includes sidecar bytes'); cmp_ok($cfs_rel_size, '>', 0, 'CFS relation size is non-zero'); cmp_ok($plain_rel_size, '>', 0, 'plain relation size is non-zero'); # Compression sanity: a highly compressible payload should occupy # fewer bytes on disk than the equivalent plain heap's main fork. # This also confirms the size functions return meaningful numbers on a # real workload. my $plain_main_bytes = -s "$data_dir/$plain_path"; cmp_ok($cfs_rel_size, '<', $plain_main_bytes, 'CFS sidecar bytes are smaller than the equivalent plain heap'); # Contrib extensions operate on CFS tables. # # pageinspect / amcheck / pgstattuple read through the buffer manager, # which returns decompressed pages, so they must work unchanged on CFS # relations. $node->safe_psql('postgres', 'CREATE EXTENSION pageinspect'); $node->safe_psql('postgres', 'CREATE EXTENSION amcheck'); $node->safe_psql('postgres', 'CREATE EXTENSION pgstattuple'); # pageinspect: get_raw_page + heap_page_items return rows. my $page_ok = $node->safe_psql('postgres', "SELECT count(*) > 0 FROM heap_page_items(get_raw_page('cfs_t', 0))"); is($page_ok, 't', 'pageinspect reads a decompressed CFS heap page'); # amcheck: verify_heapam succeeds on the CFS table. $node->safe_psql('postgres', "SELECT * FROM verify_heapam('cfs_t', startblock := 0, endblock := 10)" ); pass('amcheck verify_heapam runs on CFS table'); # amcheck: bt_index_check on the CFS-inherited PRIMARY KEY index. $node->safe_psql('postgres', "SELECT bt_index_check('cfs_t_pkey')"); pass('amcheck bt_index_check runs on CFS-inherited index'); # pgstattuple: returns a row with a sensible tuple_count. my $stat = $node->safe_psql('postgres', "SELECT tuple_count FROM pgstattuple('cfs_t')"); like($stat, qr/^\d+$/, 'pgstattuple returns integer tuple_count on CFS table'); cmp_ok($stat, '>', 0, 'pgstattuple sees live tuples on CFS table'); # pg_basebackup copies sidecars into the backup. my $backup_dir = $node->backup_dir . '/cfs_util_backup'; rmtree($backup_dir) if -d $backup_dir; # Use a manifest so pg_verifybackup can verify the backup afterwards. $node->command_ok( [ 'pg_basebackup', '-D', $backup_dir, '-X', 'stream', '-c', 'fast', '--manifest-checksums=SHA256', '--no-password' ], 'pg_basebackup succeeds on cluster with CFS tables'); # The sidecar files must be present in the backup. ok(-f "$backup_dir/$cfs_path.cfp", 'pg_basebackup copied the .cfp sidecar'); ok(-f "$backup_dir/$cfs_path.cfsmap", 'pg_basebackup copied the .cfsmap sidecar'); ok(-f "$backup_dir/$cfs_path.cfsjrn", 'pg_basebackup copied the .cfsjrn sidecar'); # The backed-up .cfp must match the source byte-for-byte (in size). my $src_cfp_size = -s "$data_dir/$cfs_path.cfp"; my $dst_cfp_size = -s "$backup_dir/$cfs_path.cfp"; is($src_cfp_size, $dst_cfp_size, 'backed-up .cfp sidecar has the same size as the source'); # pg_verifybackup verifies the manifest (which includes the sidecars). $node->command_ok([ 'pg_verifybackup', $backup_dir ], 'pg_verifybackup succeeds on a backup that contains CFS sidecars'); # Corrupt a sidecar in a copy of the backup and confirm verification # fails. my $corrupt_dir = $node->backup_dir . '/cfs_util_corrupt'; rmtree($corrupt_dir) if -d $corrupt_dir; is(system('cp', '-r', $backup_dir, $corrupt_dir), 0, 'prepared a copy of the backup for corruption testing'); # Flip one byte in the .cfp (past the header so it is a payload CRC # mismatch, not a header-magic mismatch -- both must be caught). { open my $fh, '+<:raw', "$corrupt_dir/$cfs_path.cfp" or die "open corrupt .cfp: $!"; my $pos = 64; # past CfsCompressedBlockHeader seek($fh, $pos, 0) or die "seek: $!"; my $b; read($fh, $b, 1); seek($fh, $pos, 0) or die "seek back: $!"; print $fh chr((ord($b) ^ 0xFF) & 0xFF); close($fh); } $node->command_fails([ 'pg_verifybackup', $corrupt_dir ], 'pg_verifybackup detects a corrupted CFS sidecar'); # pg_checksums skips CFS sidecars on an offline cluster. # # pg_checksums requires the cluster to be shut down (it refuses to run # on a live cluster), so this check runs after $node->stop() and uses # the real data directory. # Stop the server so pg_checksums accepts the data directory. $node->stop('fast'); # Run pg_checksums in check mode. It must not fail on the sidecar # files: the skip rule added for CFS means they are excluded from the # BLCKSZ-page scan loop entirely. The completion banner must also say # plainly that the CFS data was not examined, so that a successful # exit is not mistaken for a verification of the whole cluster. { my ($stdout, $stderr) = PostgreSQL::Test::Utils::run_command( [ 'pg_checksums', '--check', '-D', $data_dir ]); my $combined = $stdout . "\n" . $stderr; my $exit_ok = ($stderr eq '' || $stderr !~ /error|fatal/i); ok($exit_ok, 'pg_checksums completes without error on a cluster with CFS sidecars' ) or diag("pg_checksums output:\n$combined"); like( $combined, qr/CFS data was not verified/, 'pg_checksums --check states that CFS data was not verified' ) or diag("pg_checksums output:\n$combined"); } # Verify the skip counter is exposed when running in verbose mode. { my ($stdout, $stderr) = PostgreSQL::Test::Utils::run_command( [ 'pg_checksums', '--check', '--verbose', '-D', $data_dir ]); my $combined = $stdout . "\n" . $stderr; like( $combined, qr/CFS sidecars skipped:/, 'pg_checksums reports the number of skipped CFS sidecars' ) or diag("pg_checksums --verbose output:\n$combined"); } # Cleanup. rmtree($backup_dir); rmtree($corrupt_dir); }; # --------------------------------------------------------------------------- # Policy refresh at auxiliary processes and skipFsync on bulk writes # # Part A (stale policy at the bgwriter): auxiliary processes resolve the # effective CFS policy of a relation once and would keep writing new pages # with the OLD policy after ALTER TABLE ... SET (min_gain_bytes) without a # rewrite, until the next checkpoint. The shared-memory policy # publication is versioned and re-resolved on generation change. The test # dirties a table whose policy forces RAW storage, lets the bgwriter cache # that policy under buffer pressure, then changes the policy to favour # compression and checks that the pages flushed afterwards are actually # compressed (small .cfp delta) and that the bgwriter logged a policy # refresh. # # Part B (skipFsync honoured on the bulk-write path): cfs_smgr_writev / # cfs_smgr_extend / cfs_smgr_zeroextend must honour the skipFsync flag, # registering the sidecar files with the checkpointer sync queue once at # the end of a bulk operation (CREATE INDEX, CLUSTER, ALTER ... SET # TABLESPACE copy) instead of for EVERY page; bulk_write.c ends the # operation with smgrregistersync(), which CFS maps to a single # "registered sidecar files" DEBUG1 line per bulk operation (the per-page # DEBUG1 on the hot CFS write path was removed deliberately). The test # runs those bulk operations with debug1 logging enabled and checks that # the "registered sidecar files" messages appear, then verifies data # integrity across a checkpoint and an immediate-stop crash. # --------------------------------------------------------------------------- subtest 'policy refresh and skipFsync on bulk writes' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_policy_refresh'); $node->init; my $node_config = qq{ shared_buffers = 2MB bgwriter_delay = 10ms bgwriter_lru_maxpages = 10000 checkpoint_timeout = 1h max_wal_size = 2GB autovacuum = off log_min_messages = debug1 }; $node->append_conf('postgresql.conf', $node_config); $node->start; # Skip when LZ4 was 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 policy refresh test'; } my $datadir = $node->data_dir; # Return the current size of the .cfp sidecar for a table (0 if # absent). my $cfp_size = sub { my ($tbl) = @_; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('$tbl')"); return 0 unless -f "$datadir/$path.cfp"; return -s "$datadir/$path.cfp"; }; # Wait until the .cfp sidecar exists on disk and stops growing, # indicating the bgwriter has finished flushing all dirty CFS pages # for the relation. Without this, measurements taken immediately # after INSERT see a partial or non-existent file — the bgwriter # flushes asynchronously and on slower kernels the flush can lag well # behind the INSERT completion, producing a spuriously-zero baseline. my $wait_cfp_stable = sub { my ($tbl) = @_; my $prev = -1; for (1 .. 100) { my $curr = $cfp_size->($tbl); return $curr if $curr == $prev && $curr > 0; $prev = $curr; select(undef, undef, undef, 0.2); } return $prev; }; # Part A: the bgwriter must pick up an altered policy without a # checkpoint. # Short identical rows: pglz never touches them (< 2 kB), but a whole # page compresses ~100x with lz4. min_gain_bytes=8192 initially # forces every page to be stored RAW, so the .cfp size directly shows # which policy the writing process used: ~8.2 kB per page when RAW, # ~0.1 kB when compressed. $node->safe_psql('postgres', "CREATE TABLE cfs_stale (id int, payload text) WITH (algorithm='lz4', min_gain_bytes=8192)" ); $node->safe_psql('postgres', "CREATE TABLE pad (filler text)"); my $bgwriter_pid = $node->safe_psql('postgres', "SELECT pid FROM pg_stat_activity WHERE backend_type = 'background writer'" ); my $rf = $node->safe_psql('postgres', "SELECT relfilenode FROM pg_class WHERE relname = 'cfs_stale'"); # Phase 0: fill the table and force the dirty pages out under buffer # pressure from a separate plain table. Every writer (backend # evictions and the bgwriter) uses the current policy, so everything # lands RAW. $node->safe_psql('postgres', "INSERT INTO cfs_stale SELECT 1, repeat('x', 100) FROM generate_series(1, 40000) g" ); $node->safe_psql('postgres', "INSERT INTO pad SELECT repeat('p', 1900) FROM generate_series(1, 40000) g" ); # Wait for the bgwriter to flush all dirty cfs_stale pages before # measuring. On slower kernels the flush lags behind the INSERT and # the .cfp file may not exist yet, giving a zero baseline. my $cfp0 = $wait_cfp_stable->('cfs_stale'); # Phase 0 sanity: 40000 rows of ~136 bytes = ~5.4 MB of logical data. # When stored RAW (min_gain_bytes=8192) the .cfp stays in the multi-MB # ballpark; under compression it would shrink well below 1 MB. cmp_ok($cfp0, '>', 1_000_000, 'phase 0: .cfp is multi-MB, confirming RAW storage with min_gain_bytes=8192' ); # The bgwriter must have resolved (and thereby cached) the policy # while flushing pages in phase 0; otherwise the staleness check below # would be vacuous. The DEBUG1 line carries the resolving process PID # and the relfilenode. my $log_offset = -s $node->logfile; my $found_bgw_resolve = 0; for (1 .. 30) { my $log = slurp_file($node->logfile); if ($log =~ /\[$bgwriter_pid\].*CFS: smgr policy resolved from shared cache for relation \d+\/\d+\/$rf:/ ) { $found_bgw_resolve = 1; last; } # More buffer pressure gives the bgwriter another chance to flush # a page of cfs_stale and cache its policy. $node->safe_psql('postgres', "INSERT INTO pad SELECT repeat('r', 1900) FROM generate_series(1, 10000) g" ) if $_ % 5 == 0; select(undef, undef, undef, 0.2); } ok($found_bgw_resolve, 'bgwriter cached the CFS policy in phase 0'); # Change the policy without a rewrite: new pages should now be stored # compressed. A fresh backend re-opens the relation and republishes # the policy into shared memory. $node->safe_psql('postgres', "ALTER TABLE cfs_stale SET (min_gain_bytes = 1)"); $node->safe_psql('postgres', "INSERT INTO cfs_stale VALUES (1, 'republish')"); # Phase 1: dirty a second batch and flush it under pressure. A writer # holding a stale cached policy would still apply min_gain_bytes=8192 # and land most pages RAW; with the generation-based refresh every # writer uses the new policy. $node->safe_psql('postgres', "INSERT INTO cfs_stale SELECT 1, repeat('x', 100) FROM generate_series(40001, 80000) g" ); $node->safe_psql('postgres', "INSERT INTO pad SELECT repeat('q', 1900) FROM generate_series(40001, 80000) g" ); # Phase 1 check. The same data volume was inserted again (40000 # identical rows), so if the bgwriter still held the stale RAW policy # the .cfp would grow by roughly cfp0 once more (~5 MB). With the # refresh the new pages are compressed, so the delta is a small # fraction of the RAW baseline (~400 KB). Use integer-only arithmetic # (3 * delta < cfp0) to avoid any floating-point quirks across Perl # builds / locales. my $cfp1 = $wait_cfp_stable->('cfs_stale'); my $delta = $cfp1 - $cfp0; diag("cfp0=$cfp0 cfp1=$cfp1 delta=$delta threshold=" . int($cfp0 / 3)); cmp_ok(3 * $delta, '<', $cfp0, 'phase 1: .cfp growth is a fraction of the RAW baseline (pages compressed)' ); # The invalidation channel must have fired: the bgwriter re-resolved # the policy from shared memory instead of keeping its frozen copy. # Allow a short grace window in case the last flush is still in # flight. my $log = ''; for (1 .. 25) { $log = slurp_file($node->logfile, $log_offset); last if $log =~ /\[$bgwriter_pid\].*CFS: smgr policy refreshed from shared cache for relation \d+\/\d+\/$rf:/; select(undef, undef, undef, 0.2); } like( $log, qr/\[$bgwriter_pid\].*CFS: smgr policy refreshed from shared cache for relation \d+\/\d+\/$rf:/, 'bgwriter re-resolved the policy after the ALTER'); # Part B: bulk operations honour skipFsync. $node->safe_psql('postgres', "CREATE TABLE cfs_bulk (id int, payload text) WITH (algorithm='lz4')" ); $node->safe_psql('postgres', "INSERT INTO cfs_bulk SELECT g, g::text || repeat('y', 80) FROM generate_series(1, 100000) g" ); $node->safe_psql('postgres', "CHECKPOINT"); # CREATE INDEX writes the new index through smgr_bulk with # skipFsync=true: no per-page dirty-file registrations may happen on # the CFS path. $log_offset = -s $node->logfile; $node->safe_psql('postgres', "CREATE INDEX cfs_bulk_idx ON cfs_bulk (payload)"); $log = slurp_file($node->logfile, $log_offset); like( $log, qr/CFS: registered sidecar files/, 'CREATE INDEX honours skipFsync on the CFS write path'); # CLUSTER rewrites the heap through the same bulk machinery. $log_offset = -s $node->logfile; $node->safe_psql('postgres', "CLUSTER cfs_bulk USING cfs_bulk_idx"); $log = slurp_file($node->logfile, $log_offset); like( $log, qr/CFS: registered sidecar files/, 'CLUSTER honours skipFsync on the CFS write path'); my $count = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_bulk"); is($count, '100000', 'CLUSTER preserved all rows'); # ALTER ... SET TABLESPACE copies the storage through # RelationCopyStorage (smgr_bulk with skipFsync=true) as well. my $ts_dir = PostgreSQL::Test::Utils::tempdir(); $node->safe_psql('postgres', "CREATE TABLESPACE cfs_ts LOCATION '$ts_dir'"); $log_offset = -s $node->logfile; $node->safe_psql('postgres', "ALTER TABLE cfs_bulk SET TABLESPACE cfs_ts"); $log = slurp_file($node->logfile, $log_offset); like( $log, qr/CFS: registered sidecar files/, 'ALTER TABLE ... SET TABLESPACE honours skipFsync on the CFS write path' ); $count = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_bulk"); is($count, '100000', 'SET TABLESPACE preserved all rows'); # Crash without a checkpoint: the journal/WAL recovery must rebuild # the bulk-written data exactly (no durability regression from # skipping the per-page registration). $node->stop('immediate'); $node->start; $count = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_bulk"); is($count, '100000', 'bulk-written data survives an immediate-stop crash'); my $indexed = $node->safe_psql('postgres', "SELECT count(*) FROM cfs_bulk WHERE payload LIKE '42%'"); cmp_ok($indexed, '>', 0, 'index-built data is readable after crash'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # CREATE DATABASE ... TEMPLATE with CFS tables # # Verifies that CREATE DATABASE ... TEMPLATE ... produces a copy whose CFS # tables are fully and immediately readable: # * STRATEGY WAL_LOG (the main case): right after the copy commits — # before any checkpoint — a CFS table must return all rows, its TOAST # relation and indexes must work, and writing into the fresh copy must # not fail (the failure modes guarded against: silent 0 rows until the # next checkpoint, and "block 0 out of range" on insert). A checkpoint # taken between the copy and the first connection to it must not # change anything either, and the copy's physical layout must be a # proper CFS layout (empty main fork stub, data in .cfp); # * STRATEGY FILE_COPY (the control case): byte-wise copy of the data # directory already carried the sidecar files, must keep working; # * crash recovery: a WAL_LOG copy whose pages were never checkpointed # must be reconstructed by WAL replay after an immediate stop. # --------------------------------------------------------------------------- subtest 'CREATE DATABASE TEMPLATE with CFS tables' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_createdb'); $node->init; $node->start; # Skip when LZ4 was not compiled in: it is the only algorithm this # section exercises and CREATE TABLE would otherwise fail. 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 create-database test'; } # Return md5 of the concatenation of all rows' payload column, ordered # by id, in the given database. my $db_checksum = sub { my ($db, $tbl) = @_; return $node->safe_psql($db, "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM $tbl"); }; # Reference checksums of the template tables, filled in before the # copies. my $checksum_cfs; my $checksum_toast; # Run the set of assertions every copied database must satisfy. The # strategy tag and the expected cfs_t row count / checksum vary per # copy. my $check_copy = sub { my ($db, $strategy, $expect_count, $expect_checksum) = @_; is($node->safe_psql($db, "SELECT count(*) FROM cfs_t"), $expect_count, "cfs_t row count in $strategy copy"); is($db_checksum->($db, 'cfs_t'), $expect_checksum, "cfs_t content in $strategy copy"); is($node->safe_psql($db, "SELECT count(*) FROM cfs_toast_t"), '10', "cfs_toast_t row count in $strategy copy"); is($db_checksum->($db, 'cfs_toast_t'), $checksum_toast, "cfs_toast_t (TOAST relation) content in $strategy copy"); # Force the inherited-policy index: the point lookup must go # through the copied index storage, not a seqscan over the heap. my $plan = $node->safe_psql($db, "SET enable_seqscan TO off; EXPLAIN (COSTS OFF) " . "SELECT payload FROM cfs_t WHERE id = 1234"); like($plan, qr/Index Scan/, "index used in $strategy copy"); is( $node->safe_psql( $db, "SET enable_seqscan TO off; SELECT length(payload) FROM cfs_t WHERE id = 1234" ), '800', "index lookup content in $strategy copy"); is($node->safe_psql($db, "SELECT count(*) FROM plain_t"), '100', "plain_t row count in $strategy copy"); }; # 1. Template database with a CFS table (plus TOAST and an index) and # a plain table. $node->safe_psql('postgres', "CREATE DATABASE tpl_db"); $node->safe_psql('tpl_db', "CREATE TABLE cfs_t (id int, payload text) WITH (algorithm = 'lz4')"); $node->safe_psql('tpl_db', "INSERT INTO cfs_t SELECT g, repeat('cfs-' || g, 100) " . "FROM generate_series(1, 2000) g"); $node->safe_psql('tpl_db', "CREATE INDEX cfs_t_id_idx ON cfs_t (id)"); # Wide values force out-of-line TOAST storage in the TOAST relation, # which inherits the table's CFS policy and has its own # .cfp/.cfsmap/.cfsjrn. $node->safe_psql('tpl_db', "CREATE TABLE cfs_toast_t (id int, payload text) WITH (algorithm = 'lz4')" ); $node->safe_psql('tpl_db', "INSERT INTO cfs_toast_t SELECT g, repeat('toast-' || g, 5000) " . "FROM generate_series(1, 10) g"); $node->safe_psql('tpl_db', "CREATE TABLE plain_t (id int)"); $node->safe_psql('tpl_db', "INSERT INTO plain_t SELECT generate_series(1, 100)"); $checksum_cfs = $db_checksum->('tpl_db', 'cfs_t'); $checksum_toast = $db_checksum->('tpl_db', 'cfs_toast_t'); is(length($checksum_cfs), 32, 'template CFS table populated'); is(length($checksum_toast), 32, 'template CFS TOAST table populated'); # Make the template's durable state settled before copying. $node->safe_psql('postgres', "CHECKPOINT"); # 2. WAL_LOG strategy (main case): the copy must be fully readable # before the next checkpoint, and must accept writes. $node->safe_psql('postgres', "CREATE DATABASE cp_wal STRATEGY WAL_LOG TEMPLATE tpl_db"); # Deliberately no CHECKPOINT here: reading and writing happen in the # window where the copied pages may still live only in shared buffers. $check_copy->('cp_wal', 'WAL_LOG', '2000', $checksum_cfs); # Writing into the fresh copy must not fail with "block 0 out of # range". $node->safe_psql('cp_wal', "INSERT INTO cfs_t VALUES (999999, repeat('new', 100))"); is($node->safe_psql('cp_wal', "SELECT count(*) FROM cfs_t"), '2001', 'INSERT into WAL_LOG copy before checkpoint'); my $checksum_cfs_inserted = $db_checksum->('cp_wal', 'cfs_t'); # A checkpoint after the reads/writes must not change the visible # state. $node->safe_psql('postgres', "CHECKPOINT"); $check_copy->( 'cp_wal', 'WAL_LOG post-checkpoint', '2001', $checksum_cfs_inserted); # 2b. The harshest window: a checkpoint between the copy and the very # first connection to it. The copy must be fully durable and # readable on its own, with a proper CFS physical layout (the main # fork stays an empty compatibility stub, the data lives in the # .cfp sidecar). $node->safe_psql('postgres', "CREATE DATABASE cp_ckpt STRATEGY WAL_LOG TEMPLATE tpl_db"); $node->safe_psql('postgres', "CHECKPOINT"); $check_copy->( 'cp_ckpt', 'WAL_LOG checkpoint-first', '2000', $checksum_cfs); my $data_dir = $node->data_dir; my $cfs_path = $node->safe_psql('cp_ckpt', "SELECT pg_relation_filepath('cfs_t')"); is(-s "$data_dir/$cfs_path", 0, 'main fork of the copy stays an empty stub'); ok(-s "$data_dir/$cfs_path.cfp" > 0, 'data of the copy lives in the .cfp sidecar'); ok(-f "$data_dir/$cfs_path.cfsmap" && -f "$data_dir/$cfs_path.cfsjrn", 'map and journal sidecars exist in the copy'); # 3. FILE_COPY strategy (control case): byte-wise copy carries the # sidecar files as-is; must keep working unchanged. $node->safe_psql('postgres', "CREATE DATABASE cp_file STRATEGY FILE_COPY TEMPLATE tpl_db"); $check_copy->('cp_file', 'FILE_COPY', '2000', $checksum_cfs); # 4. Crash recovery: a WAL_LOG copy whose pages were never # checkpointed must come back through WAL replay after an immediate # stop. $node->safe_psql('postgres', "CREATE DATABASE cp_crash STRATEGY WAL_LOG TEMPLATE tpl_db"); $node->stop('immediate'); $node->start; $check_copy->('cp_crash', 'WAL_LOG after crash', '2000', $checksum_cfs); $node->stop('fast'); }; # ---------------------------------------------------------------------- # Deferred policy publication: an ALTER changing only the tuning # (level) publishes the new policy at commit, not mid-transaction. An # ALTER that later fails and rolls back leaves the previous policy in # effect; a successful one is visible after commit. The shared-cache # timing itself (pending across subtransaction rollback, publication at # commit and through prepared transactions) is covered by the test_cfs # module: its probes read the shared policy cache directly. # ---------------------------------------------------------------------- subtest 'deferred policy publication' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_defer_publish'); $node->init; $node->append_conf('postgresql.conf', "checkpoint_timeout = 30s\n"); $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 deferred publication test'; } $node->safe_psql('postgres', "CREATE TABLE defer_t (id int, payload text) " . "WITH (algorithm = 'lz4', level = 3)"); $node->safe_psql('postgres', "INSERT INTO defer_t SELECT g, repeat('d' || g, 100) " . "FROM generate_series(1, 100) g"); $node->safe_psql('postgres', "CHECKPOINT"); my $level = sub { return $node->safe_psql('postgres', "SELECT (pg_cfs_relation_info('defer_t'::regclass)).level"); }; is($level->(), '3', 'deferred: table starts at level 3'); # A multi-subcommand ALTER that fails on the second subcommand rolls # back the whole statement; the level change must not survive. my ($ret, $stdout, $stderr) = $node->psql('postgres', "ALTER TABLE defer_t SET (level = 7), SET (fillfactor = 'bogus')"); isnt($ret, 0, 'deferred: failing ALTER is rejected'); like( $stderr, qr/invalid value for integer option "fillfactor"/, 'deferred: failure is the invalid fillfactor'); # The aborted ALTER left the policy and the data intact. is($level->(), '3', 'deferred: aborted ALTER keeps level 3'); is($node->safe_psql('postgres', "SELECT count(*) FROM defer_t"), '100', 'deferred: aborted ALTER keeps the data'); # A successful ALTER is visible after commit. $node->safe_psql('postgres', "ALTER TABLE defer_t SET (level = 7)"); is($level->(), '7', 'deferred: committed ALTER publishes level 7'); is($node->safe_psql('postgres', "SELECT count(*) FROM defer_t"), '100', 'deferred: committed ALTER keeps the data'); $node->safe_psql('postgres', "DROP TABLE defer_t"); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Shared block-map segment pool. # # The per-relation block map lives in the shared segment pool # (cfs_map_memory). A segment loaded once stays resident across sessions # AND across checkpoints: the checkpoint journal truncation must not # invalidate it, and a fresh backend reading the same relation reloads # nothing (before the pool, every backend rebuilt its private map after # each checkpoint). pg_cfs_map_pool() exposes the counters. # --------------------------------------------------------------------------- subtest 'shared block-map segment pool' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_map_pool'); $node->init; # A buffer cache smaller than the table forces the re-reads below # through the CFS read path: with the default 128MB the second and # third scans would be served from shared_buffers and the residency # assertions would pass vacuously. $node->append_conf('postgresql.conf', "shared_buffers = 1MB\n"); $node->start; # One segment covers the whole table: enough to observe the loads. $node->safe_psql( 'postgres', q{ CREATE TABLE sm_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO sm_t SELECT g, repeat('SM' || g, 100) FROM generate_series(1, 5000) g; }); # Empty the buffer cache so the scan below really goes through the CFS # read path; the write path itself no longer loads map segments. $node->restart; # The first full scan resolves every block through the pool and loads # the relation's segment(s) once. $node->safe_psql('postgres', "SELECT count(*) FROM sm_t"); my $loads_after_warm = $node->safe_psql('postgres', "SELECT segment_loads FROM pg_cfs_map_pool()"); ok($loads_after_warm > 0, "segment pool warmed (loads=$loads_after_warm)"); # A second backend reads the same relation before any checkpoint: the # segment is already resident, no reload. my $loads_before_ckpt = $node->safe_psql('postgres', "SELECT segment_loads FROM pg_cfs_map_pool()"); is($node->safe_psql('postgres', "SELECT count(*) FROM sm_t"), 5000, 'second session reads correct row count'); is( $node->safe_psql( 'postgres', "SELECT segment_loads FROM pg_cfs_map_pool()"), $loads_before_ckpt, 'second session reuses the resident segment (no loads)'); # CHECKPOINT must not drop the relation's segments, and a third fresh # backend must not reload them either. $node->safe_psql('postgres', 'CHECKPOINT'); my $loads_after_ckpt = $node->safe_psql('postgres', "SELECT segment_loads FROM pg_cfs_map_pool()"); is($node->safe_psql('postgres', "SELECT count(*) FROM sm_t"), 5000, 'third session reads correct row count after checkpoint'); is( $node->safe_psql( 'postgres', "SELECT segment_loads FROM pg_cfs_map_pool()"), $loads_after_ckpt, 'checkpoint does not invalidate the segment pool'); cmp_ok( $node->safe_psql( 'postgres', "SELECT segments_in_use FROM pg_cfs_map_pool()"), '>', 0, 'segments remain in use'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Pool fallback mode (cfs_map_memory=0) and pool exhaustion. # # With the segment pool disabled the regular read path must fall back to # the handle's private map exactly like before the pool: data written # before a restart reads back byte-identical, never as silent zero pages. # With a pool too small for the concurrently open relations (every open # CFS relation pins its resident segments), a read that cannot make its # segment resident is served through the private authoritative map and # counted in fallback_reads; only when that path fails too is an error # raised. # --------------------------------------------------------------------------- subtest 'map pool disabled falls back to private maps' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_map_off'); $node->init; $node->append_conf('postgresql.conf', "cfs_map_memory = 0\n"); $node->start; is( $node->safe_psql( 'postgres', "SELECT pool_segments FROM pg_cfs_map_pool()"), '0', 'pool off: no segments allocated'); $node->safe_psql( 'postgres', q{ CREATE TABLE mapoff_t (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO mapoff_t SELECT g, repeat('MO' || g, 100) FROM generate_series(1, 5000) g; }); $node->safe_psql('postgres', 'CHECKPOINT'); my $ck = $node->safe_psql('postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM mapoff_t"); # The restart empties shared_buffers, so every heap page read below # resolves through the CFS read path, not the buffer cache. $node->restart; is($node->safe_psql('postgres', 'SELECT count(*) FROM mapoff_t'), 5000, 'pool off: rows survive restart'); is( $node->safe_psql( 'postgres', "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM mapoff_t"), $ck, 'pool off: payload survives restart byte-identical'); # A brand-new table written and read back in ONE session before any # checkpoint: the handle materialises its private map on the first # write, so the read must resolve through it (never a silent zero page # or a spurious pool failure). is( ( $node->safe_psql( 'postgres', q{ CREATE TABLE mapoff_fresh (id int) WITH (algorithm = 'lz4'); INSERT INTO mapoff_fresh SELECT g FROM generate_series(1, 50) g; SELECT count(*) FROM mapoff_fresh;})), 50, 'pool off: fresh table read back in the writing session'); $node->stop('fast'); }; subtest 'a pinned relation does not exhaust the map pool' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_map_pin'); $node->init; $node->append_conf('postgresql.conf', "cfs_map_memory = 1\nautovacuum = off\n"); $node->start; $node->safe_psql( 'postgres', q{ CREATE TABLE pin_a (id int, payload text) WITH (algorithm = 'lz4'); CREATE TABLE pin_b (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO pin_a SELECT g, repeat('A' || g, 100) FROM generate_series(1, 2000) g; INSERT INTO pin_b SELECT g, repeat('B' || g, 100) FROM generate_series(1, 2000) g; CHECKPOINT; }); # The restart empties both the buffer cache and the pool: the first # cold read of pin_a takes the pool's only segment. $node->restart; # Session A reads pin_a and stays connected: its open handle pins the # relation (the metadata slot). The pin must not protect the segment: # with a one-segment pool a reader of pin_b has to evict it. my $session_a = $node->background_psql('postgres', on_error_stop => 1); $session_a->query_until(qr/pin-a-resident/m, "SELECT count(*) FROM pin_a; SELECT 'pin-a-resident';\n"); my $stats_before = $node->safe_psql('postgres', "SELECT segment_evictions || ',' || fallback_reads FROM pg_cfs_map_pool()" ); my ($ev_before, $fb_before) = split(',', $stats_before); my ($ret, $stdout, $stderr) = $node->psql('postgres', 'SELECT count(*) FROM pin_b'); is($ret, 0, 'adaptive pool: read served, not failed'); is($stdout, '2000', 'adaptive pool: read returns the data'); is($stderr, '', 'adaptive pool: no error is raised'); # pin_b's read evicted the pinned pin_a's segment instead of # degrading to the authoritative fallback. cmp_ok( $node->safe_psql( 'postgres', "SELECT segment_evictions FROM pg_cfs_map_pool()"), '>', $ev_before, 'adaptive pool: pinned segment was evicted'); is( $node->safe_psql( 'postgres', "SELECT fallback_reads FROM pg_cfs_map_pool()"), $fb_before, 'adaptive pool: no fallback read was needed'); # After the pinning session is gone pin_a reads correctly again (the # evicted segment is simply reloaded). $session_a->quit; is($node->safe_psql('postgres', 'SELECT count(*) FROM pin_a'), 2000, 'pin released: pin_a reads correctly'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Crash with a non-empty journal: test the two distinct contracts. # First, force a cold shared-map read while the snapshot and journal still # contain different portions of the relation. Then crash and prove that # recovery replays the journal, folds it into the snapshot, and preserves # the complete data set. Recovery itself may already populate the pool. # --------------------------------------------------------------------------- subtest 'cold pool reads snapshot plus journal and crash recovery preserves data' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_crash_journal'); # Avoid hint-bit WAL from the checksum scan. Recovery can still load # map segments while replaying ordinary WAL. $node->init(extra => ['--no-data-checksums']); # A buffer cache smaller than the table forces the post-restart reads # through the CFS read path and therefore through the pool. $node->append_conf('postgresql.conf', "shared_buffers = 1MB\ncfs_map_memory = 1\nautovacuum = off\ncheckpoint_timeout = 30min\nmax_wal_size = 1GB\n"); $node->start; $node->safe_psql('postgres', 'SELECT pg_cfs_bgworker_pause()'); $node->safe_psql( 'postgres', q{ CREATE TABLE crash_jrn (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO crash_jrn SELECT g, repeat('CJ' || g, 100) FROM generate_series(1, 50000) g; CREATE TABLE cold_control (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO cold_control SELECT g, repeat('CC' || g, 100) FROM generate_series(1, 3000) g; CHECKPOINT; INSERT INTO crash_jrn SELECT g, repeat('CJ' || g, 100) FROM generate_series(50001, 100000) g; }); # The second INSERT is not checkpointed: .cfsmap covers the first 50000 # rows and the .cfsjrn sidecar carries the map entries for the rest. my $jrn_path = $node->data_dir . '/' . $node->safe_psql('postgres', "SELECT pg_relation_filepath('crash_jrn')") . '.cfsjrn'; ok(-s $jrn_path, 'journal holds the post-checkpoint writes') or diag("missing or empty journal file $jrn_path"); my $checksum_before = checksum_tbl($node, 'crash_jrn'); my $map_path = $jrn_path; $map_path =~ s/\.cfsjrn$/.cfsmap/; my $map_before = -s $map_path; my $journal_before = -s $jrn_path; cmp_ok($journal_before, '>', 16, 'journal contains records beyond its header'); is($node->safe_psql('postgres', 'SELECT pool_segments FROM pg_cfs_map_pool()'), 1, 'fixture has one map segment'); my $evictions_before = $node->safe_psql('postgres', 'SELECT segment_evictions FROM pg_cfs_map_pool()'); is($node->safe_psql('postgres', 'SELECT count(*) FROM cold_control'), 3000, 'eviction control table readable'); cmp_ok($node->safe_psql('postgres', 'SELECT segment_evictions FROM pg_cfs_map_pool()'), '>', $evictions_before, 'control table displaced a map segment'); my $cold_loads = $node->safe_psql('postgres', 'SELECT segment_loads FROM pg_cfs_map_pool()'); my $fallback = $node->safe_psql('postgres', 'SELECT fallback_reads FROM pg_cfs_map_pool()'); is(checksum_tbl($node, 'crash_jrn'), $checksum_before, 'cold read with live journal preserves all payloads'); cmp_ok($node->safe_psql('postgres', 'SELECT segment_loads FROM pg_cfs_map_pool()'), '>', $cold_loads, 'cold read actually loaded a map segment'); is($node->safe_psql('postgres', 'SELECT fallback_reads FROM pg_cfs_map_pool()'), $fallback, 'cold read used pool rather than fallback'); is(-s $map_path, $map_before, 'snapshot size unchanged during cold read'); cmp_ok(-s $jrn_path, '>=', $journal_before, 'journal not folded before cold read'); my $log_offset = -s $node->logfile; $node->stop('immediate'); $node->start; # Recovery folds the journal and may load the segment before SQL is accepted. # The startup log proves journal replay; the cold-read assertion above # separately proves the snapshot plus journal miss path. ok($node->log_contains(qr/CFS: recovery init complete \(replayed [1-9][0-9]* journal record\(s\)/, $log_offset), 'recovery replayed nonempty journal'); cmp_ok(-s $map_path, '>', $map_before, 'recovery folded new entries into snapshot'); is(-s $jrn_path, 16, 'recovery checkpoint leaves only journal header'); cmp_ok($node->safe_psql('postgres', 'SELECT segment_loads FROM pg_cfs_map_pool()'), '>', 0, 'map was loaded during recovery'); is($node->safe_psql('postgres', 'SELECT count(*) FROM crash_jrn'), 100000, 'cold pool: all rows survived the crash'); is(checksum_tbl($node, 'crash_jrn'), $checksum_before, 'cold pool: payloads read back byte-identical'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # Correctness regressions of the shared block-map pool: # * a lazy handle must not resurrect the pre-VACUUM relation size (F1); # * the pool must not load a segment through a replaced .cfsmap inode # after CHECKPOINT (F2); # * a full handle (cfs_map_memory=0) must see another backend's writes # (F3). # --------------------------------------------------------------------------- subtest 'lazy handle does not resurrect the pre-VACUUM size' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_lazy_truncate'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n"); $node->append_conf('postgresql.conf', "max_wal_size = 1GB\n"); $node->append_conf('postgresql.conf', "shared_buffers = 1MB\n"); $node->start; my $blcksz = $node->safe_psql('postgres', "SELECT setting::int FROM pg_settings WHERE name = 'block_size'"); $node->safe_psql( 'postgres', q{ CREATE TABLE trunc_t (id int primary key, payload text) WITH (algorithm = 'lz4'); INSERT INTO trunc_t SELECT g, repeat(md5(g::text), 20) FROM generate_series(1, 5000) g; CREATE TABLE filler (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO filler SELECT g, repeat(md5(g::text), 20) FROM generate_series(1, 30000) g; CHECKPOINT; }); my $size_n = $node->safe_psql('postgres', "SELECT logical_size FROM pg_cfs_relation_size('trunc_t')"); my $nblocks_n = int($size_n / $blcksz); ok($nblocks_n > 10, "relation starts with $nblocks_n blocks"); # Delete the tail and let VACUUM truncate the relation in place. No # checkpoint may run before the INSERT below: the .cfsmap snapshot must # keep the old size while the journal carries the shrink. $node->safe_psql( 'postgres', q{ DELETE FROM trunc_t WHERE id > 100; VACUUM trunc_t; }); my $size_m = $node->safe_psql('postgres', "SELECT logical_size FROM pg_cfs_relation_size('trunc_t')"); my $nblocks_m = int($size_m / $blcksz); ok($nblocks_m < $nblocks_n, "VACUUM truncated the relation: $nblocks_n -> $nblocks_m blocks"); # The truncation does NOT shrink the .cfsmap file physically anymore: # cfs_truncate only journals the RESIZE record (it runs inside # RelationTruncate()'s critical section), and the checkpoint's phase 2 # applies it later. The file keeps its dead tail until then; the # logical size above is the authoritative one. my $trunc_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('trunc_t')"); is( -s $node->data_dir . "/$trunc_path.cfsmap", 8 + 24 * $nblocks_n, 'VACUUM truncation keeps the .cfsmap file until the checkpoint'); # A fresh backend opens a lazy handle from the stale snapshot (old # size) and extends at the authoritative end M. Enough rows are # inserted to force at least one new block. $node->safe_psql( 'postgres', q{ INSERT INTO trunc_t SELECT g, repeat(md5(g::text), 20) FROM generate_series(100001, 101000) g; }); my $size_after = $node->safe_psql('postgres', "SELECT logical_size FROM pg_cfs_relation_size('trunc_t')"); cmp_ok($size_after, '<', $size_n, 'the extension does not resurrect the pre-VACUUM size'); cmp_ok($size_after, '>', $size_m, 'the relation grew with the inserts'); # Push the dirty page out through smgr without a checkpoint, so the # journal holds the UPDATE while the last RESIZE is still the shrink. $node->safe_psql('postgres', "SELECT count(*) FROM filler"); $node->stop('immediate'); $node->start; is( $node->safe_psql( 'postgres', "SELECT count(*) FROM trunc_t WHERE id > 100000"), '1000', 'the rows written past the truncated end survive recovery'); is( $node->safe_psql( 'postgres', "SELECT logical_size FROM pg_cfs_relation_size('trunc_t')"), $size_after, 'the size is unchanged across recovery'); # The checkpoint now applies the journal's last RESIZE: the dead tail # the truncation left behind is charged and physically truncated, so # the file finally agrees with the logical size. $node->safe_psql('postgres', 'CHECKPOINT'); my $nblocks_after = int($size_after / $blcksz); is( -s $node->data_dir . "/$trunc_path.cfsmap", 8 + 24 * $nblocks_after, 'the checkpoint applies the deferred map truncation'); $node->stop('fast'); }; # --------------------------------------------------------------------------- # A failed deferred map truncation converges at the retry checkpoint. # # The physical truncation of the map file lives in the checkpoint's RESIZE # application (phase 2), not in the critical section of RelationTruncate(). # When that ftruncate fails, the checkpoint is fatal (data_sync_elevel -> # PANIC, like every checkpoint durability failure) but the journal keeps # the RESIZE record, so recovery replays the logical shrink and the next # checkpoint finishes the physical truncation. # # The failure is injected with the injection point cfs-fail-map-truncate, # placed inside cfs_map_file_resize(); the ERROR/PANIC aborts the # checkpoint exactly like a real ftruncate failure would. # --------------------------------------------------------------------------- subtest 'a failed map truncation converges at recovery' => 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_trunc_window'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->append_conf('postgresql.conf', "checkpoint_timeout = 30min\n"); $node->start; if (!$node->check_extension('injection_points')) { plan skip_all => 'Extension injection_points not installed'; } my $blcksz = $node->safe_psql('postgres', "SELECT setting::int FROM pg_settings WHERE name = 'block_size'"); $node->safe_psql( 'postgres', q{ CREATE TABLE win_t (id int primary key, payload text) WITH (algorithm = 'lz4'); INSERT INTO win_t SELECT g, repeat(md5(g::text), 20) FROM generate_series(1, 5000) g; CHECKPOINT; }); # The truncation journals the shrink only: the map file must keep its # dead tail until the checkpoint applies the RESIZE. $node->safe_psql('postgres', 'DELETE FROM win_t WHERE id > 100'); $node->safe_psql('postgres', 'VACUUM win_t'); my $nblocks_win = int( $node->safe_psql('postgres', "SELECT logical_size FROM pg_cfs_relation_size('win_t')") / $blcksz); my $win_path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('win_t')"); cmp_ok( -s $node->data_dir . "/$win_path.cfsmap", '>', 8 + 24 * $nblocks_win, 'the map file still carries the dead tail after VACUUM'); $node->safe_psql('postgres', 'CREATE EXTENSION injection_points'); # The checkpoint's phase 2 hits the injected ftruncate failure. The # failure goes through data_sync_elevel(), so the checkpointer PANICs # and (restart_after_crash = off in a TAP cluster) the postmaster is # gone; use the non-fatal psql() so the torn connection does not abort # the harness. my $log_off = -s $node->logfile; my ($ret, $stdout, $stderr) = $node->psql('postgres', "SELECT injection_points_attach('cfs-fail-map-truncate', 'notice');\n" . "CHECKPOINT;\n"); isnt($ret, 0, 'checkpoint fails when the map ftruncate fails'); ok($node->log_contains(qr/CFS: could not resize page map/, $log_off), 'the failure is the page map truncation'); ok($node->log_contains(qr/PANIC/, $log_off), 'the checkpoint durability failure escalates to PANIC'); # The TAP harness sets restart_after_crash = off, so the PANIC left the # postmaster down: start it again to run recovery. $node->stop('immediate', fail_ok => 1); $node->start; # Recovery replayed the journal (the RESIZE record is intact - the # reset never ran), so the logical shrink survived the crash. is($node->safe_psql('postgres', 'SELECT count(*) FROM win_t'), '100', 'the truncated tail stays truncated after recovery'); # The injection point died with the crashed cluster: the retry # checkpoint now applies the RESIZE and physically truncates the map. $node->safe_psql('postgres', 'CHECKPOINT'); is( -s $node->data_dir . "/$win_path.cfsmap", 8 + 24 * $nblocks_win, 'the retry checkpoint finishes the physical map truncation'); is( $node->safe_psql( 'postgres', "SELECT ok FROM pg_cfs_check('win_t', true)"), 't', 'pg_cfs_check is clean after the failed truncation'); $node->stop('fast'); }; subtest 'pool reloads .cfsmap after a checkpoint rename' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_stale_snapshot'); $node->init; $node->append_conf('postgresql.conf', "cfs_map_memory = 1\n"); $node->append_conf('postgresql.conf', "shared_buffers = 1MB\n"); $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->start; $node->safe_psql( 'postgres', q{ CREATE TABLE snap_t (id int primary key, payload text) WITH (algorithm = 'lz4'); INSERT INTO snap_t VALUES (1, 'v0'); CREATE TABLE snap_u (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO snap_u SELECT g, repeat('u', 100) FROM generate_series(1, 100) g; CREATE TABLE snap_filler (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO snap_filler SELECT g, repeat(md5(g::text), 20) FROM generate_series(1, 5000) g; CHECKPOINT; }); $node->restart; # cold pool and buffer cache # B occupies the only pool segment and keeps it pinned for the whole # transaction. my $session_b = $node->background_psql('postgres', on_error_stop => 1); $session_b->query_safe('BEGIN'); $session_b->query_safe('SELECT count(*) FROM snap_u'); # A opens its persistent lazy handle before the checkpoint that will # replace the .cfsmap inode. pg_relation_size() opens the handle but # loads no segment. my $session_a = $node->background_psql('postgres', on_error_stop => 1); $session_a->query_safe("SELECT pg_relation_size('snap_t')"); # The only segment belongs to snap_u, so this write is journal-only. $session_a->query_safe("UPDATE snap_t SET payload = 'v1' WHERE id = 1"); $node->safe_psql('postgres', 'CHECKPOINT'); # snapshot #1 (v1), new inode $session_a->query_safe("UPDATE snap_t SET payload = 'v2' WHERE id = 1"); $node->safe_psql('postgres', 'CHECKPOINT'); # snapshot #2 (v2), new inode $session_b->query_safe('COMMIT'); $session_b->quit; # free the only segment # Evict the hot data page and the pool segment: the read below must go # through the CFS map instead of shared_buffers. $node->safe_psql('postgres', 'SELECT count(*) FROM snap_filler'); is($session_a->query('SELECT payload FROM snap_t WHERE id = 1'), 'v2', 'long-lived handle reads through the checkpoint rename'); is( $node->safe_psql( 'postgres', "SELECT payload FROM snap_t WHERE id = 1"), 'v2', 'a fresh session is not served a stale resident segment'); $session_a->quit; $node->stop('fast'); }; subtest 'full handle sees writes of another backend' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_full_handle_stale'); $node->init; $node->append_conf('postgresql.conf', "cfs_map_memory = 0\n"); $node->append_conf('postgresql.conf', "shared_buffers = 1MB\n"); $node->start; $node->safe_psql( 'postgres', q{ CREATE TABLE full_t (id int primary key, payload text) WITH (algorithm = 'lz4'); INSERT INTO full_t VALUES (1, 'old'); CREATE TABLE full_filler (id int, payload text) WITH (algorithm = 'lz4'); INSERT INTO full_filler SELECT g, repeat(md5(g::text), 20) FROM generate_series(1, 5000) g; CHECKPOINT; }); my $session_a = $node->background_psql('postgres', on_error_stop => 1); is($session_a->query('SELECT payload FROM full_t WHERE id = 1'), 'old', 'session A loaded the private map'); $node->safe_psql('postgres', "UPDATE full_t SET payload = 'new' WHERE id = 1"); # Evict the hot page so the read below reaches the CFS map instead of # shared_buffers. $node->safe_psql('postgres', 'SELECT count(*) FROM full_filler'); is($session_a->query('SELECT payload FROM full_t WHERE id = 1'), 'new', 'A sees the update committed by another backend'); $session_a->quit; $node->stop('fast'); }; # --------------------------------------------------------------------------- # Observability of the map rows a checkpoint writes. The # checkpoint_map_rows_written counter must grow by the number of CHANGED # blocks between two checkpoints, not by nblocks: a table of ~1.9 kB rows # at fillfactor 50 packs two rows per page, so an in-place update of 40 # consecutive rows dirties a computable number of pages and the counter # delta must equal exactly that number. While the checkpoint still # rewrites the full snapshot the delta equals nblocks, so this section # stays red until the incremental checkpoint lands. # --------------------------------------------------------------------------- subtest 'checkpoint writes only the changed map rows' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_ckpt_rows_written'); $node->init; $node->append_conf('postgresql.conf', "autovacuum = off\n"); $node->start; $node->safe_psql( 'postgres', q{ CREATE TABLE ckr_t (g int, payload text) WITH (algorithm = 'lz4', fillfactor = 50); INSERT INTO ckr_t SELECT g, repeat(md5(g::text), 59) FROM generate_series(1, 5000) g; -- Pre-warm hint bits on every page and settle: the baseline -- checkpoint below must be the last one that touches all pages. SELECT count(*) FROM ckr_t; CHECKPOINT; }); my $nblocks = $node->safe_psql('postgres', "SELECT count(DISTINCT split_part(ctid::text, ',', 1)) FROM ckr_t"); # Pages holding the rows to be updated (ctid page numbers, counted # before the update so the expectation does not depend on packing). my $npages = $node->safe_psql( 'postgres', "SELECT count(DISTINCT split_part(ctid::text, ',', 1)) FROM ckr_t WHERE g BETWEEN 101 AND 140"); my $c0 = $node->safe_psql( 'postgres', "SELECT checkpoint_map_rows_written FROM pg_stat_cfs WHERE relname = 'ckr_t'"); # Same-length payload keeps the new versions HOT on the same pages. $node->safe_psql( 'postgres', "UPDATE ckr_t SET payload = repeat(md5(g::text || 'u'), 59) WHERE g BETWEEN 101 AND 140"); $node->safe_psql('postgres', 'CHECKPOINT'); my $c1 = $node->safe_psql( 'postgres', "SELECT checkpoint_map_rows_written FROM pg_stat_cfs WHERE relname = 'ckr_t'"); my $delta = $c1 - $c0; is($delta, $npages, "checkpoint rewrote the $npages changed map rows, not nblocks"); diag("nblocks=$nblocks changed_pages=$npages counter_delta=$delta"); $node->stop('fast'); }; # --------------------------------------------------------------------------- # The checkpoint folds the journal into the .cfsmap file # in place. Only the rows the journal carries are rewritten and the last # RESIZE record sizes the file; the full-map snapshot rewrite is gone. # After a checkpoint the journal is a bare 16-byte header, the map is # exactly the prologue plus whole rows, and a crash right after the # checkpoint (fold durable, nothing else pending) reads everything back. # --------------------------------------------------------------------------- subtest 'checkpoint folds the journal into the map' => sub { my $node = PostgreSQL::Test::Cluster->new('cfs_fold'); $node->init; $node->start; $node->safe_psql( 'postgres', q{ CREATE TABLE fold_t (g int, payload text) WITH (algorithm = 'lz4'); INSERT INTO fold_t SELECT g, repeat(md5(g::text), 8) FROM generate_series(1, 3000) g; CHECKPOINT; }); my $dd = $node->data_dir; my $path = $node->safe_psql('postgres', "SELECT pg_relation_filepath('fold_t')"); my $map = "$dd/$path.cfsmap"; my $jrn = "$dd/$path.cfsjrn"; # The first checkpoint already folds: the map grew from the bare # prologue to whole rows, the journal is empty. my $map_size = -s $map; is(-s $jrn, 16, 'journal is a bare header after the fold'); ok(($map_size - 8) % 24 == 0 && $map_size > 8, "map is the prologue plus whole rows (size $map_size)"); ok(!-f "$map.tmp", 'no snapshot temp file is left behind'); # A second round adds rows (RESIZE growth) and rewrites old ones. $node->safe_psql( 'postgres', "INSERT INTO fold_t SELECT g + 3000, repeat(md5(g::text), 8) FROM generate_series(1, 500) g; UPDATE fold_t SET payload = repeat(md5(g::text || 'u'), 8) WHERE g <= 40;"); $node->safe_psql('postgres', 'CHECKPOINT'); my $map_size2 = -s $map; is(-s $jrn, 16, 'journal is a bare header after the second fold'); ok(($map_size2 - 8) % 24 == 0, 'map still ends on a whole row'); ok(!-f "$map.tmp", 'no snapshot temp file after the second fold'); # Crash right after the checkpoint: everything must read back. my $expect = $node->safe_psql('postgres', "SELECT md5(string_agg(md5(payload), '' ORDER BY g)) FROM fold_t"); $node->stop('immediate'); $node->start; is($node->safe_psql('postgres', 'SELECT count(*) FROM fold_t'), 3500, 'all rows survive the crash after the fold'); is( $node->safe_psql( 'postgres', "SELECT md5(string_agg(md5(payload), '' ORDER BY g)) FROM fold_t" ), $expect, 'payloads are byte-identical after the crash'); $node->stop('fast'); }; done_testing();