/*-------------------------------------------------------------------------- * test_cfs.c * Test module for the Compressed File Store (CFS) codec and * page-level compression/decompression API. * * CFS exposes no SQL surface of its own; this extension provides * a SQL-callable entry point so that the codec dispatch table and the * CfsCompressPage/CfsDecompressPage helpers can be exercised through the * regression-test infrastructure. * * The tests are deterministic so that the expected output is stable. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/test/modules/test_cfs/test_cfs.c * * ------------------------------------------------------------------------- */ #include "postgres.h" #include #include #include #include #ifdef USE_LZ4 #include #include #endif #ifdef USE_ZSTD #include #endif #include "catalog/pg_tablespace_d.h" #include "funcapi.h" #include "miscadmin.h" #include "access/relation.h" #include "access/htup_details.h" #include "access/xact.h" #include "access/xlog.h" #include "port/pg_crc32c.h" #include "postmaster/bgwriter.h" #include "storage/block.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_codec.h" #include "storage/cfs/cfs_compact.h" #include "storage/cfs/cfs_compress.h" #include "storage/cfs/cfs_format.h" #include "storage/cfs/cfs_fsck.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_journal.h" #include "storage/cfs/cfs_path.h" #include "storage/cfs/cfs_recovery.h" #include "storage/cfs/cfs_rel.h" #include "storage/cfs/cfs_shmem.h" #include "storage/cfs/cfs_smgr.h" #include "storage/cfs/cfs_storage.h" #include "storage/fd.h" #include "storage/lmgr.h" #include "storage/smgr.h" #include "utils/builtins.h" #include "utils/memutils.h" #include "utils/rel.h" #include "utils/resowner.h" #include "utils/timestamp.h" #include "utils/tuplestore.h" #include "varatt.h" PG_MODULE_MAGIC; /* Page size used throughout the tests (matches CFS_BLCKSZ). */ #define TEST_BLCKSZ 8192 /* * Result of a single test case, accumulated in a fixed array and emitted as * a result set at the end of cfs_run_tests(). */ typedef struct CfsTestResult { const char *test_name; const char *result; /* "ok", "skip", or "fail" */ char detail[128]; /* human-readable detail */ } CfsTestResult; #define MAX_RESULTS 64 static CfsTestResult test_results[MAX_RESULTS]; static int test_result_count = 0; /* * Test-side journal reset: the production API asks the caller for the * generation watermark it stamped. Full test handles can compute it from * their map; lazy ones (map == NULL) carry no rows and use the handle's * current watermark. */ static void test_journal_reset(CfsRelation *cfs, int elevel) { uint32 max_generation = cfs->map_hdr.max_generation; if (cfs->map != NULL) max_generation = cfs_map_live_summary(cfs); cfs_journal_reset_point(cfs, max_generation, elevel); } static CfsAlgorithm parse_algorithm_text(text *algorithm) { char *name; CfsAlgorithm result; name = text_to_cstring(algorithm); result = CfsAlgorithmFromName(name); if (!CFS_ALGORITHM_VALID(result)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid CFS algorithm name: %s", name))); } pfree(name); return result; } static void fill_page_from_payload(unsigned char *page, bytea *payload) { Size payload_size = VARSIZE_ANY_EXHDR(payload); char *payload_data = VARDATA_ANY(payload); Size offset; if (payload_size == 0) { MemSet(page, 0, TEST_BLCKSZ); return; } for (offset = 0; offset < TEST_BLCKSZ; offset += payload_size) { Size chunk_size = Min(payload_size, TEST_BLCKSZ - offset); memcpy(page + offset, payload_data, chunk_size); } } static void add_result(const char *name, const char *result, const char *detail) { CfsTestResult *r; if (test_result_count >= MAX_RESULTS) elog(ERROR, "test_cfs: test result table overflow (MAX_RESULTS=%d)", MAX_RESULTS); r = &test_results[test_result_count++]; r->test_name = name; r->result = result; if (detail != NULL) strlcpy(r->detail, detail, sizeof(r->detail)); else r->detail[0] = '\0'; } /* ---------------------------------------------------------------- * Deterministic test-data fillers * ---------------------------------------------------------------- */ /* Monotonic pattern; highly compressible by every algorithm. */ static void fill_sequential(unsigned char *buf, size_t len) { size_t i; for (i = 0; i < len; i++) buf[i] = (unsigned char) (i & 0xFF); } /* Constant pattern; compresses to almost nothing. */ static void fill_constant(unsigned char *buf, size_t len, unsigned char val) { memset(buf, val, len); } /* * Deterministic pseudo-random pattern (LCG). Resembles incompressible data * well enough to defeat LZ4/Zstd within an 8 kB page. */ static void fill_pseudo_random(unsigned char *buf, size_t len) { size_t i; uint32 state = 0x12345678; for (i = 0; i < len; i++) { state = state * 1103515245u + 12345u; buf[i] = (unsigned char) ((state >> 16) & 0xFF); } } /* ---------------------------------------------------------------- * Codec-level round-trip helper * * Compresses src, decompresses it back, and checks the data matches. * Returns true on success. * ---------------------------------------------------------------- */ static bool codec_roundtrip(CfsAlgorithm algo, const unsigned char *src, size_t src_size, int level, char *detail, size_t detail_len) { const CfsCodec *codec = CfsCodecLookup(algo); CfsCodecState *state; CfsCodecResult rc; void *cbuf; void *dbuf; size_t bound; size_t csize = 0; size_t dsize = 0; bool ok = false; if (codec == NULL || !codec->available()) { snprintf(detail, detail_len, "codec %d not available", (int) algo); return false; } bound = codec->compress_bound(src_size); cbuf = palloc(bound); dbuf = palloc(src_size); state = CfsCodecStateCreate(algo); if (state == NULL) { snprintf(detail, detail_len, "could not create codec state"); goto done; } rc = codec->compress(state, src, src_size, cbuf, bound, level, &csize); /* * CFS_CODEC_OK means the data was compressed (or, for RAW, copied * verbatim); CFS_CODEC_NOOP is still accepted for any codec that may * report it. In both cases the output buffer holds valid data and the * round-trip can proceed. */ if (rc != CFS_CODEC_OK && rc != CFS_CODEC_NOOP) { snprintf(detail, detail_len, "compress rc=%d", (int) rc); goto done; } rc = codec->decompress(state, cbuf, csize, dbuf, src_size, src_size, &dsize); if (rc != CFS_CODEC_OK) { snprintf(detail, detail_len, "decompress rc=%d", (int) rc); goto done; } if (dsize != src_size || memcmp(src, dbuf, src_size) != 0) { snprintf(detail, detail_len, "round-trip mismatch"); goto done; } snprintf(detail, detail_len, "compressed %zu -> %zu bytes", src_size, csize); ok = true; done: if (state != NULL) CfsCodecStateDestroy(algo); pfree(cbuf); pfree(dbuf); return ok; } /* ---------------------------------------------------------------- * Individual test cases * ---------------------------------------------------------------- */ static void test_raw_codec(void) { unsigned char page[TEST_BLCKSZ]; char detail[128]; fill_sequential(page, sizeof(page)); if (codec_roundtrip(CFS_ALGORITHM_RAW, page, sizeof(page), 0, detail, sizeof(detail))) add_result("raw_codec_roundtrip", "ok", detail); else add_result("raw_codec_roundtrip", "fail", detail); } static void test_lz4_codec(void) { unsigned char page[TEST_BLCKSZ]; char detail[128]; if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4)) { add_result("lz4_codec_roundtrip", "skip", "LZ4 not compiled in"); return; } fill_constant(page, sizeof(page), 0x41); if (codec_roundtrip(CFS_ALGORITHM_LZ4, page, sizeof(page), 1, detail, sizeof(detail))) add_result("lz4_codec_roundtrip", "ok", detail); else add_result("lz4_codec_roundtrip", "fail", detail); } static void test_zstd_codec(void) { unsigned char page[TEST_BLCKSZ]; char detail[128]; if (!CfsCodecAvailable(CFS_ALGORITHM_ZSTD)) { add_result("zstd_codec_roundtrip", "skip", "Zstd not compiled in"); return; } fill_constant(page, sizeof(page), 0x00); if (codec_roundtrip(CFS_ALGORITHM_ZSTD, page, sizeof(page), 3, detail, sizeof(detail))) add_result("zstd_codec_roundtrip", "ok", detail); else add_result("zstd_codec_roundtrip", "fail", detail); } /* Direct codec tests: no RAW fallback can hide a codec failure here. */ static const char *const pglz_extended_names[6] = { "pglz_sizes", "pglz_incompressible", "pglz_corrupt_stream", "pglz_truncated_stream", "pglz_buffer_bounds", "pglz_state_reuse" }; static const char *const zlib_extended_names[6] = { "zlib_sizes", "zlib_incompressible", "zlib_corrupt_stream", "zlib_truncated_stream", "zlib_buffer_bounds", "zlib_state_reuse" }; static void test_extended_codec(CfsAlgorithm algo, const char *const names[6]) { static const size_t sizes[] = {64, 256, 1024, 4096, TEST_BLCKSZ}; const CfsCodec *codec = CfsCodecLookup(algo); CfsCodecState *state = NULL; unsigned char *src = NULL, *compressed = NULL, *decoded = NULL; unsigned char *scratch = NULL; size_t bound = 0, csize = 0, dsize = 0; CfsCodecResult rc; CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT; CfsCompressResult cres; CfsDecompressResult dres; bool ok, base_ok; int i; /* names point to static storage: add_result retains these pointers. */ if (codec == NULL || !codec->available()) { for (i = 0; i < 6; i++) add_result(names[i], "skip", "codec unavailable"); return; } state = CfsCodecStateCreate(algo); bound = codec->compress_bound(TEST_BLCKSZ); if (state == NULL || bound == 0) { for (i = 0; i < 6; i++) add_result(names[i], "fail", "state/bound initialization failed"); goto done; } src = palloc(TEST_BLCKSZ); compressed = palloc(bound + 16); decoded = palloc(TEST_BLCKSZ + 16); scratch = palloc(CfsCompressScratchSize(TEST_BLCKSZ)); ok = true; for (i = 0; i < lengthof(sizes); i++) { fill_constant(src, sizes[i], (unsigned char) (0x41 + i)); csize = dsize = 0; rc = codec->compress(state, src, sizes[i], compressed, bound, 1, &csize); if (rc != CFS_CODEC_OK || csize == 0 || csize > bound) { ok = false; break; } rc = codec->decompress(state, compressed, csize, decoded, sizes[i], sizes[i], &dsize); if (rc != CFS_CODEC_OK || dsize != sizes[i] || memcmp(src, decoded, sizes[i]) != 0) { ok = false; break; } } add_result(names[0], ok ? "ok" : "fail", ok ? "64/256/1024/4096/8192 exact" : "size matrix mismatch"); /* Direct OVERFLOW on incompressible data is valid; page RAW fallback * must still be byte-exact. */ fill_pseudo_random(src, TEST_BLCKSZ); csize = 0; rc = codec->compress(state, src, TEST_BLCKSZ, compressed, bound, 1, &csize); ok = rc == CFS_CODEC_OVERFLOW; if (rc == CFS_CODEC_OK) { dsize = 0; ok = csize > 0 && csize <= bound && codec->decompress(state, compressed, csize, decoded, TEST_BLCKSZ, TEST_BLCKSZ, &dsize) == CFS_CODEC_OK && dsize == TEST_BLCKSZ && memcmp(src, decoded, TEST_BLCKSZ) == 0; } opts.algorithm = algo; opts.level = 1; opts.min_gain_bytes = 1; opts.explicit_algorithm = true; opts.allow_raw_fallback = true; CfsCompressPage(src, TEST_BLCKSZ, &opts, scratch, CfsCompressScratchSize(TEST_BLCKSZ), &cres); ok = ok && cres.is_raw && cres.algorithm_used == CFS_ALGORITHM_RAW && CfsDecompressPage(cres.result_data, cres.total_size, decoded, TEST_BLCKSZ, &dres) == CFS_DECOMPRESS_OK && dres.decompressed_size == TEST_BLCKSZ && memcmp(src, decoded, TEST_BLCKSZ) == 0; add_result(names[1], ok ? "ok" : "fail", ok ? "incompressible/RAW fallback exact" : "incompressible/RAW fallback mismatch"); fill_constant(src, TEST_BLCKSZ, 0x5A); csize = 0; rc = codec->compress(state, src, TEST_BLCKSZ, compressed, bound, 1, &csize); base_ok = rc == CFS_CODEC_OK && csize > 2 && csize <= bound; ok = false; if (base_ok) { unsigned char old = compressed[0]; compressed[0] = 0xFF; dsize = 0; rc = codec->decompress(state, compressed, csize, decoded, TEST_BLCKSZ, TEST_BLCKSZ, &dsize); /* The codec alone has no CRC obligation; a changed byte result * is detectable by the outer page's CRC. */ ok = rc != CFS_CODEC_OK || dsize != TEST_BLCKSZ || memcmp(src, decoded, TEST_BLCKSZ) != 0; compressed[0] = old; } add_result(names[2], ok ? "ok" : "fail", ok ? "damaged stream rejected/mismatched" : "damaged stream undetected"); ok = base_ok; if (ok) { dsize = 0; rc = codec->decompress(state, compressed, csize - 1, decoded, TEST_BLCKSZ, TEST_BLCKSZ, &dsize); ok = rc != CFS_CODEC_OK; } add_result(names[3], ok ? "ok" : "fail", ok ? "truncated stream rejected" : "truncation accepted"); ok = base_ok; if (ok) { memset(decoded + TEST_BLCKSZ - 1, 0xA5, 17); dsize = 0; rc = codec->decompress(state, compressed, csize, decoded, TEST_BLCKSZ - 1, TEST_BLCKSZ, &dsize); ok = rc != CFS_CODEC_OK; for (i = TEST_BLCKSZ - 1; i < TEST_BLCKSZ + 16; i++) ok = ok && decoded[i] == 0xA5; memset(compressed, 0xCC, 16); rc = codec->compress(state, src, TEST_BLCKSZ, compressed, 0, 1, &csize); ok = ok && rc != CFS_CODEC_OK; for (i = 0; i < 16; i++) ok = ok && compressed[i] == 0xCC; } add_result(names[4], ok ? "ok" : "fail", ok ? "short buffers rejected; canaries intact" : "short buffer/guard failure"); /* Reuse a single codec state after the negative cases. */ ok = true; for (i = 0; i < 32; i++) { int j; if (i & 1) fill_sequential(src, TEST_BLCKSZ); else fill_constant(src, TEST_BLCKSZ, (unsigned char) i); csize = dsize = 0; memset(compressed + bound, 0xA5, 16); memset(decoded + TEST_BLCKSZ, 0xA5, 16); rc = codec->compress(state, src, TEST_BLCKSZ, compressed, bound, 1, &csize); if (rc != CFS_CODEC_OK || csize == 0 || csize > bound || codec->decompress(state, compressed, csize, decoded, TEST_BLCKSZ, TEST_BLCKSZ, &dsize) != CFS_CODEC_OK || dsize != TEST_BLCKSZ || memcmp(src, decoded, TEST_BLCKSZ) != 0) { ok = false; break; } for (j = 0; j < 16; j++) if (compressed[bound + j] != 0xA5 || decoded[TEST_BLCKSZ + j] != 0xA5) ok = false; if (!ok) break; } add_result(names[5], ok ? "ok" : "fail", ok ? "32 reused cycles; canaries intact" : "state reuse/guard mismatch"); done: if (state != NULL) CfsCodecStateDestroy(algo); if (scratch != NULL) pfree(scratch); if (decoded != NULL) pfree(decoded); if (compressed != NULL) pfree(compressed); if (src != NULL) pfree(src); } /* * LZ4 level range: every user level 1..12 must round-trip. Levels * 1..2 use the fast encoder (two accelerations), levels 3..12 use LZ4 HC. */ static void test_lz4_level_roundtrip(void) { char detail[128]; int level; if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4)) { add_result("lz4_level_roundtrip", "skip", "LZ4 not compiled in"); return; } for (level = 1; level <= CFS_LZ4_LEVEL_MAX; level++) { unsigned char page[TEST_BLCKSZ]; fill_sequential(page, sizeof(page)); if (!codec_roundtrip(CFS_ALGORITHM_LZ4, page, sizeof(page), level, detail, sizeof(detail))) { snprintf(detail, sizeof(detail), "round-trip failed at level %d", level); add_result("lz4_level_roundtrip", "fail", detail); return; } } add_result("lz4_level_roundtrip", "ok", "round-trip levels 1..12"); } /* * Per-algorithm level ceiling (NB1): CfsCodecMaxLevel must report each * codec's native maximum — LZ4 caps at 12 while Zstd reaches the global 22. * For Zstd the ceiling is the runtime library maximum clamped to the format * bound (ZSTD_maxCLevel() may be lower than CFS_ZSTD_LEVEL_MAX). */ static void test_codec_max_level(void) { bool ok = true; ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_LZ4) == CFS_LZ4_LEVEL_MAX); #ifdef USE_ZSTD ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_ZSTD) == Min(CFS_ZSTD_LEVEL_MAX, ZSTD_maxCLevel())); #else ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_ZSTD) == CFS_ZSTD_LEVEL_MAX); #endif ok &= (CfsCodecMaxLevel(CFS_ALGORITHM_RAW) == CFS_COMPRESS_LEVEL_MAX); if (ok) add_result("codec_max_level", "ok", "per-algorithm level ceiling"); else add_result("codec_max_level", "fail", "unexpected level ceiling"); } /* * Fallback write policy (NB1): cfs_default_write_opts picks the first * available codec and leaves every tunable field unset. The fallback is * not an explicit user choice, so level and minimum gain must keep the 0 * sentinel with their set-flags cleared: consumers re-resolve them from * their own GUCs at write time, and a published fallback (shared memory / * WAL) must carry nothing computed from the writer's session GUC. */ static void test_default_write_opts_level(void) { CfsEffectiveOptions opts; char detail[128]; bool ok = true; cfs_default_write_opts(&opts); ok &= (opts.level == 0 && opts.min_gain_bytes == 0); ok &= !opts.level_set && !opts.min_gain_bytes_set; ok &= (opts.algorithm == CFS_ALGORITHM_RAW || CfsCodecAvailable(opts.algorithm)); if (ok) add_result("default_write_opts_level", "ok", "tunables unset, set-flags cleared"); else { snprintf(detail, sizeof(detail), "level %d, min_gain %d, flags %d/%d, algo %d", opts.level, opts.min_gain_bytes, (int) opts.level_set, (int) opts.min_gain_bytes_set, (int) opts.algorithm); add_result("default_write_opts_level", "fail", detail); } } /* * Per-algorithm default level lookup: cfs_default_level_for must return * each algorithm's own GUC, read fresh at call time — the runtime-resolve * contract (nothing is cached between calls, a GUC change affects the very * next call). */ static void test_default_level_for(void) { int saved_lz4 = cfs_default_lz4_level; int saved_zstd = cfs_default_zstd_level; bool ok = true; cfs_default_lz4_level = 7; cfs_default_zstd_level = 17; ok &= (cfs_default_level_for(CFS_ALGORITHM_LZ4) == 7); ok &= (cfs_default_level_for(CFS_ALGORITHM_ZSTD) == 17); /* Re-read after a change: no caching between calls. */ cfs_default_lz4_level = 2; ok &= (cfs_default_level_for(CFS_ALGORITHM_LZ4) == 2); cfs_default_lz4_level = saved_lz4; cfs_default_zstd_level = saved_zstd; if (ok) add_result("default_level_for", "ok", "per-algorithm GUC lookup"); else add_result("default_level_for", "fail", "wrong per-algorithm level"); } /* * Explicit-only policy with set-flags survives a publish/read roundtrip * through the shared-memory slot, and a flag-only change (unset level * becoming explicit) is a policy change: the generation must be bumped. */ static void test_policy_flags_roundtrip(void) { RelFileLocatorBackend rlb; CfsEffectiveOptions in; CfsEffectiveOptions out; uint64 gen1; uint64 gen2; bool ok = true; rlb.locator.spcOid = InvalidOid; rlb.locator.dbOid = InvalidOid; rlb.locator.relNumber = 99998; rlb.backend = INVALID_PROC_NUMBER; memset(&in, 0, sizeof(in)); in.is_cfs = true; in.algorithm = CFS_ALGORITHM_ZSTD; in.level_set = false; in.min_gain_bytes_set = false; gen1 = cfs_publish_options(rlb, MAIN_FORKNUM, &in); ok &= cfs_get_options(rlb, MAIN_FORKNUM, &out); ok &= (out.algorithm == CFS_ALGORITHM_ZSTD); ok &= (!out.level_set && out.level == 0); ok &= (!out.min_gain_bytes_set && out.min_gain_bytes == 0); /* An unset level becoming explicit is a policy change. */ in.level = 5; in.level_set = true; gen2 = cfs_publish_options(rlb, MAIN_FORKNUM, &in); ok &= (gen2 != gen1); ok &= cfs_get_options(rlb, MAIN_FORKNUM, &out); ok &= (out.level_set && out.level == 5); cfs_forget_options(rlb, MAIN_FORKNUM); if (ok) add_result("policy_flags_roundtrip", "ok", "set-flags roundtrip and generation bump"); else add_result("policy_flags_roundtrip", "fail", "set-flags lost or generation not bumped"); } /* * Explicit RAW through the page functions: algorithm = RAW must * round-trip via the codec table, producing a RAW record (is_raw set). */ static void test_raw_page_roundtrip(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; CfsDecompressResult dres; CfsDecompressStatus dstatus; char detail[128]; scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); fill_pseudo_random(page, sizeof(page)); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_RAW; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; opts.explicit_algorithm = true; opts.allow_raw_fallback = false; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); if (!cres.is_raw || cres.algorithm_used != CFS_ALGORITHM_RAW) { add_result("raw_page_roundtrip", "fail", "explicit RAW not stored as RAW"); pfree(scratch); return; } dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), &dres); if (dstatus != CFS_DECOMPRESS_OK || dres.decompressed_size != sizeof(page) || memcmp(page, decompressed, sizeof(page)) != 0) { snprintf(detail, sizeof(detail), "RAW decompress status=%d", (int) dstatus); add_result("raw_page_roundtrip", "fail", detail); pfree(scratch); return; } add_result("raw_page_roundtrip", "ok", "explicit RAW round-trip ok"); pfree(scratch); } static void test_compress_page_lz4(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; CfsDecompressStatus dstatus; char detail[128]; if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4)) { add_result("compress_page_lz4", "skip", "LZ4 not compiled in"); return; } scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); /* Highly compressible page. */ fill_constant(page, sizeof(page), 0xBB); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_LZ4; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); if (cres.is_raw || cres.algorithm_used != CFS_ALGORITHM_LZ4 || cres.compressed_size >= sizeof(page)) { snprintf(detail, sizeof(detail), "expected LZ4, got algo=%d raw=%d", (int) cres.algorithm_used, cres.is_raw); add_result("compress_page_lz4", "fail", detail); pfree(scratch); return; } dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); if (dstatus != CFS_DECOMPRESS_OK) { snprintf(detail, sizeof(detail), "decompress status=%d", (int) dstatus); add_result("compress_page_lz4", "fail", detail); pfree(scratch); return; } if (memcmp(page, decompressed, sizeof(page)) != 0) { add_result("compress_page_lz4", "fail", "decompressed page mismatch"); pfree(scratch); return; } snprintf(detail, sizeof(detail), "payload %u bytes (raw=%d)", cres.compressed_size, cres.is_raw); add_result("compress_page_lz4", "ok", detail); pfree(scratch); } static void test_incompressible_raw_fallback(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; CfsDecompressStatus dstatus; char detail[128]; scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); /* Incompressible data + a high min-gain requirement -> must be RAW. */ fill_pseudo_random(page, sizeof(page)); memset(&opts, 0, sizeof(opts)); opts.algorithm = CfsCodecAvailable(CFS_ALGORITHM_LZ4) ? CFS_ALGORITHM_LZ4 : CFS_ALGORITHM_RAW; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = CFS_MIN_GAIN_BYTES_DEFAULT; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); if (!cres.is_raw || cres.algorithm_used != CFS_ALGORITHM_RAW) { snprintf(detail, sizeof(detail), "expected RAW fallback, got algo=%d raw=%d", (int) cres.algorithm_used, cres.is_raw); add_result("incompressible_raw_fallback", "fail", detail); pfree(scratch); return; } dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); if (dstatus != CFS_DECOMPRESS_OK || memcmp(page, decompressed, sizeof(page)) != 0) { snprintf(detail, sizeof(detail), "RAW decompress status=%d", (int) dstatus); add_result("incompressible_raw_fallback", "fail", detail); pfree(scratch); return; } snprintf(detail, sizeof(detail), "stored as RAW (%u bytes)", cres.compressed_size); add_result("incompressible_raw_fallback", "ok", detail); pfree(scratch); } static void test_crc_corruption_detection(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; CfsDecompressStatus dstatus; CfsCompressedBlockHeader *hdr; uint32 saved_crc; char detail[128]; scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); fill_constant(page, sizeof(page), 0x5A); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_RAW; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); /* Corrupt the header CRC and expect BAD_HDR on decompression. */ hdr = (CfsCompressedBlockHeader *) cres.result_data; saved_crc = hdr->hdr_crc; hdr->hdr_crc = 0xDEADBEEFu; dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); hdr->hdr_crc = saved_crc; if (dstatus == CFS_DECOMPRESS_BAD_HDR) { snprintf(detail, sizeof(detail), "detected header CRC mismatch"); add_result("crc_corruption_detection", "ok", detail); } else { snprintf(detail, sizeof(detail), "expected BAD_HDR, got %d", (int) dstatus); add_result("crc_corruption_detection", "fail", detail); } pfree(scratch); } /* * original_size contract: a header whose original_size differs from * CFS_BLCKSZ must be rejected even when its hdr_crc is recomputed to match. * Otherwise a CRC-consistent sub-8 kB header would decompress only part of * the page and leave the tail of out_page holding stale bytes. */ static void test_decompress_original_size_rejected(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; CfsDecompressStatus dstatus; CfsCompressedBlockHeader *hdr; uint32 saved_original_size; char detail[128]; scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); fill_constant(page, sizeof(page), 0x6C); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_RAW; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); hdr = (CfsCompressedBlockHeader *) cres.result_data; saved_original_size = hdr->original_size; hdr->original_size = CFS_BLCKSZ - 1; hdr->hdr_crc = CfsCrc32cHeader(hdr); dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); hdr->original_size = saved_original_size; if (dstatus == CFS_DECOMPRESS_BAD_HDR) { snprintf(detail, sizeof(detail), "sub-8kB original_size rejected"); add_result("decompress_original_size_rejected", "ok", detail); } else { snprintf(detail, sizeof(detail), "expected BAD_HDR, got %d", (int) dstatus); add_result("decompress_original_size_rejected", "fail", detail); } pfree(scratch); } /* * Unavailable codec on the read path: a block compressed with a * codec this build lacks must surface as a status (CFS_DECOMPRESS_ERROR), * not as a hard ERROR, so the caller's corruption policy can apply. We * simulate a codec-less build via the cfs_debug_disable_codecs fault * injection instead of actually rebuilding. */ static void test_decompress_codec_unavailable(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; CfsDecompressStatus dstatus; char detail[128]; if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4)) { add_result("decompress_codec_unavailable", "skip", "LZ4 not compiled in"); return; } scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); /* Highly compressible page -> a genuinely LZ4-compressed record. */ fill_constant(page, sizeof(page), 0x42); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_LZ4; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; opts.explicit_algorithm = true; opts.allow_raw_fallback = false; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); if (cres.is_raw || cres.algorithm_used != CFS_ALGORITHM_LZ4) { add_result("decompress_codec_unavailable", "fail", "page unexpectedly stored as RAW"); pfree(scratch); return; } /* Pretend LZ4 was not compiled in, then try to read it back. */ cfs_debug_disable_codecs |= (1 << CFS_ALGORITHM_LZ4); dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); cfs_debug_disable_codecs &= ~(1 << CFS_ALGORITHM_LZ4); if (dstatus == CFS_DECOMPRESS_ERROR) { snprintf(detail, sizeof(detail), "unavailable codec returned status"); add_result("decompress_codec_unavailable", "ok", detail); } else { snprintf(detail, sizeof(detail), "expected DECOMPRESS_ERROR, got %d", (int) dstatus); add_result("decompress_codec_unavailable", "fail", detail); } pfree(scratch); } /* * test_record_padding_zeroed * Reproduce the .cfp padding leak: the per-relation compress scratch is * allocated with palloc() (not palloc0) and reused across writes, so any * record byte that is neither explicitly assigned nor covered by a CRC * would carry stale backend memory unless CfsCompressPage() zeroes it * before the record is appended to .cfp. Two regions are checked: * * (a) CfsCompressedBlockHeader trailing struct padding -- the header * is 40 bytes but hdr_crc ends at offset 36, so bytes [36,40) * are written to disk, never assigned, and not covered by any CRC. * * (b) the 0..7 alignment bytes after the compressed payload, also * outside the CRC-covered payload range. * * We mirror the leak by garbage-filling the scratch before each compress and * then requiring (1) both padding regions to be all-zero, and (2) two * independent compressions -- into scratch buffers filled with *different* * garbage -- to produce byte-identical full records, which rules out any * non-determinism across the whole record, not just the payload padding. A * RAW record is exactly page-sized and therefore has zero payload padding, so * it cannot exercise (b); a real compression codec is required. (a) still * applies to RAW records, but we only assert it here when a codec produced a * genuinely compressed record, matching the rest of the test's scope. */ static void test_record_padding_zeroed(void) { unsigned char page[TEST_BLCKSZ]; unsigned char *scratch1; unsigned char *scratch2; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres1; CfsCompressResult cres2; CfsAlgorithm algo; char detail[128]; size_t pad_off; size_t pad_len; size_t i; bool padding_clean = true; if (CfsCodecAvailable(CFS_ALGORITHM_LZ4)) algo = CFS_ALGORITHM_LZ4; else if (CfsCodecAvailable(CFS_ALGORITHM_ZSTD)) algo = CFS_ALGORITHM_ZSTD; else { add_result("record_padding_zeroed", "skip", "no compression codec available"); return; } scratch_sz = CfsCompressScratchSize(sizeof(page)); /* Highly compressible page -> small, non-aligned compressed payload. */ fill_constant(page, sizeof(page), 0xBB); memset(&opts, 0, sizeof(opts)); opts.algorithm = algo; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; /* * Garbage-fill both scratch buffers with *different* patterns, mimicking * a reused buffer that still holds a previous, unrelated record. Using * distinct fill bytes (0xA5 vs 0x5A) makes the final full-record memcmp * catch any byte that was left untouched -- in the payload padding, in * the header trailing padding, or anywhere else -- rather than passing * just because both buffers happened to hold identical garbage. */ scratch1 = palloc(scratch_sz); scratch2 = palloc(scratch_sz); memset(scratch1, 0xA5, scratch_sz); memset(scratch2, 0x5A, scratch_sz); CfsCompressPage(page, sizeof(page), &opts, scratch1, scratch_sz, &cres1); /* Only a genuinely compressed record carries padding worth checking. */ if (cres1.is_raw) { add_result("record_padding_zeroed", "skip", "page stored as RAW (no padding)"); pfree(scratch1); pfree(scratch2); return; } /* * Header trailing struct padding: CfsCompressedBlockHeader is 40 bytes * but hdr_crc (the last field) ends at offset 36, so bytes [36,40) are * written to disk yet neither assigned by CfsFillBlockHeader() nor * covered by any CRC. Require them to be zero. Computed via offsetof so * the range tracks the layout automatically. */ { size_t hdr_pad_off = offsetof(CfsCompressedBlockHeader, hdr_crc) + sizeof(uint32); size_t hdr_pad_len = sizeof(CfsCompressedBlockHeader) - hdr_pad_off; for (i = 0; i < hdr_pad_len; i++) { if (scratch1[hdr_pad_off + i] != 0) { snprintf(detail, sizeof(detail), "header trailing padding not zeroed " "(off %zu, %zu bytes leaked)", hdr_pad_off, hdr_pad_len); add_result("record_padding_zeroed", "fail", detail); pfree(scratch1); pfree(scratch2); return; } } } /* Payload padding spans [payload end, aligned record end). */ pad_off = CFS_BLOCK_HEADER_SIZE + cres1.compressed_size; pad_len = cres1.total_size - pad_off; if (pad_len == 0) { snprintf(detail, sizeof(detail), "payload %u already aligned (no padding)", cres1.compressed_size); add_result("record_padding_zeroed", "skip", detail); pfree(scratch1); pfree(scratch2); return; } for (i = 0; i < pad_len; i++) { if (scratch1[pad_off + i] != 0) { padding_clean = false; break; } } if (!padding_clean) { snprintf(detail, sizeof(detail), "padding not zeroed (payload %u, pad %zu bytes leaked)", cres1.compressed_size, pad_len); add_result("record_padding_zeroed", "fail", detail); pfree(scratch1); pfree(scratch2); return; } /* * Determinism: compress the same page into the second scratch (filled * with a *different* garbage pattern) and require the two full records -- * header, payload and all padding -- to be byte-identical. Distinct fill * bytes make any left-over untouched byte fail this memcmp. */ CfsCompressPage(page, sizeof(page), &opts, scratch2, scratch_sz, &cres2); if (cres2.total_size != cres1.total_size || memcmp(scratch1, scratch2, cres1.total_size) != 0) { snprintf(detail, sizeof(detail), "non-deterministic record (payload %u, pad %zu)", cres1.compressed_size, pad_len); add_result("record_padding_zeroed", "fail", detail); pfree(scratch1); pfree(scratch2); return; } snprintf(detail, sizeof(detail), "payload %u bytes, header + payload padding all zero", cres1.compressed_size); add_result("record_padding_zeroed", "ok", detail); pfree(scratch1); pfree(scratch2); } /* * Padding verification on read: the header trailing struct padding * and the payload alignment padding are written as zero and must stay zero. * A nonzero byte in either region (covered by no CRC) must be flagged as * BAD_HDR / BAD_DATA respectively. */ static void test_record_padding_checked(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; CfsCompressedBlockHeader *hdr; CfsDecompressStatus dstatus; size_t hdr_pad_off; size_t payload_pad_off; size_t payload_pad_len; char detail[128]; if (!CfsCodecAvailable(CFS_ALGORITHM_LZ4)) { add_result("record_padding_checked", "skip", "LZ4 not compiled in"); return; } scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); /* Highly compressible page -> a compressed record with payload padding. */ fill_constant(page, sizeof(page), 0xBB); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_LZ4; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; opts.explicit_algorithm = true; opts.allow_raw_fallback = false; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); if (cres.is_raw) { add_result("record_padding_checked", "fail", "page unexpectedly stored as RAW"); pfree(scratch); return; } hdr = (CfsCompressedBlockHeader *) cres.result_data; /* * The whole 28-byte header is covered by hdr_crc, so there is no header * padding left to corrupt: flipping any header byte must trip the header * CRC check. Use the byte just past the header (the first payload byte) * as the stand-in: the payload CRC must reject it as BAD_DATA. */ hdr_pad_off = offsetof(CfsCompressedBlockHeader, hdr_crc); ((unsigned char *) hdr)[hdr_pad_off] ^= 0xFF; dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); ((unsigned char *) hdr)[hdr_pad_off] ^= 0xFF; if (dstatus != CFS_DECOMPRESS_BAD_HDR) { snprintf(detail, sizeof(detail), "header byte corruption: expected BAD_HDR, got %d", (int) dstatus); add_result("record_padding_checked", "fail", detail); pfree(scratch); return; } /* Corrupt one byte of the record tail padding. */ payload_pad_off = CFS_BLOCK_HEADER_SIZE + cres.compressed_size; payload_pad_len = cres.total_size - payload_pad_off; if (payload_pad_len == 0) { add_result("record_padding_checked", "fail", "compressed payload unexpectedly aligned (no padding)"); pfree(scratch); return; } ((unsigned char *) cres.result_data)[payload_pad_off] ^= 0xFF; dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); if (dstatus == CFS_DECOMPRESS_BAD_DATA) { add_result("record_padding_checked", "ok", "header and record tail padding rejected"); } else { snprintf(detail, sizeof(detail), "record tail padding corruption: expected BAD_DATA, got %d", (int) dstatus); add_result("record_padding_checked", "fail", detail); } pfree(scratch); } static void test_scratch_and_alignment(void) { char detail[128]; size_t sz = CfsCompressScratchSize(TEST_BLCKSZ); bool ok = true; if (sz <= CFS_BLOCK_HEADER_SIZE) ok = false; if (sz > CFS_BLOCK_HEADER_SIZE + TEST_BLCKSZ + CFS_BLOCK_ALIGN + 1024) ok = false; if (!(CFS_ALIGN_UP(1) == 8 && CFS_ALIGN_UP(8) == 8 && CFS_ALIGN_UP(9) == 16 && CFS_RECORD_SIZE(10) == CFS_ALIGN_UP(CFS_BLOCK_HEADER_SIZE + 10))) ok = false; if (ok) { snprintf(detail, sizeof(detail), "scratch=%zu align ok", sz); add_result("scratch_and_alignment", "ok", detail); } else { snprintf(detail, sizeof(detail), "scratch=%zu align check failed", sz); add_result("scratch_and_alignment", "fail", detail); } } /* * page_size contract: CfsCompressPage() must reject any page size * other than CFS_BLCKSZ, not merely sizes larger than it. A smaller size * used to be accepted and written into the header as a sub-8 kB * original_size that the format validator would later reject. */ static void test_compress_page_size_rejected(void) { unsigned char page[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres; bool raised = false; scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); fill_constant(page, sizeof(page), 0x42); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_RAW; opts.min_gain_bytes = 1; PG_TRY(); { CfsCompressPage(page, CFS_BLCKSZ / 2, &opts, scratch, scratch_sz, &cres); } PG_CATCH(); { ErrorData *edata; MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); edata = CopyErrorData(); raised = (edata->sqlerrcode == ERRCODE_INTERNAL_ERROR); MemoryContextSwitchTo(oldcontext); FlushErrorState(); } PG_END_TRY(); if (!raised) { add_result("compress_page_size_rejected", "fail", "sub-8kB page_size accepted by CfsCompressPage"); pfree(scratch); return; } add_result("compress_page_size_rejected", "ok", "page_size != CFS_BLCKSZ rejected"); pfree(scratch); } /* ================================================================ * On-disk format serialisation/validation, * sidecar path helpers and structural fsck. * ================================================================ */ /* ------------------------------------------------------------------ * Format layer tests * ------------------------------------------------------------------ */ static void test_format_map_header(void) { CfsMapPrologue prologue; char detail[128]; cfs_map_prologue_init(&prologue); if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_OK) { add_result("format_map_header", "fail", "valid prologue rejected"); return; } prologue.magic ^= 0x1; if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_MAGIC) { add_result("format_map_header", "fail", "bad magic not detected"); return; } prologue.magic ^= 0x1; prologue.version = (uint16) (CFS_MAP_VERSION + 1); if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_VERSION) { add_result("format_map_header", "fail", "bad version not detected"); return; } prologue.version = CFS_MAP_VERSION; /* nonzero _reserved is a field error. */ prologue._reserved = 1; if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_FIELD) { add_result("format_map_header", "fail", "nonzero reserved not detected"); return; } prologue._reserved = 0; snprintf(detail, sizeof(detail), "magic/version/reserved checks pass"); add_result("format_map_header", "ok", detail); } static void test_format_map_entry(void) { CfsMapEntry e; char detail[128]; cfs_map_entry_init(&e); if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_OK) { add_result("format_map_entry", "fail", "empty entry rejected"); return; } e.physical_offset = 4096; e.compressed_size = 2048; e.generation = 3; cfs_map_entry_crc_set(&e); if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_OK) { add_result("format_map_entry", "fail", "live entry rejected"); return; } e.entry_crc ^= 0x1; if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_BAD_CRC) { add_result("format_map_entry", "fail", "bad CRC not detected"); return; } e.entry_crc ^= 0x1; /* compressed_size beyond the page size is a field error. */ e.compressed_size = CFS_BLCKSZ + 1; cfs_map_entry_crc_set(&e); if (cfs_map_entry_validate(&e, true) != CFS_FORMAT_BAD_FIELD) { add_result("format_map_entry", "fail", "oversized compressed_size not detected"); return; } snprintf(detail, sizeof(detail), "entry CRC round-trip ok"); add_result("format_map_entry", "ok", detail); } static void test_format_journal_header(void) { CfsJournalFileHeader hdr; char detail[128]; cfs_journal_header_init(&hdr); if (cfs_journal_header_validate(&hdr) != CFS_FORMAT_OK) { add_result("format_journal_header", "fail", "valid header rejected"); return; } hdr.magic ^= 0x1; if (cfs_journal_header_validate(&hdr) != CFS_FORMAT_BAD_MAGIC) { add_result("format_journal_header", "fail", "bad magic not detected"); return; } hdr.magic ^= 0x1; hdr.hdr_crc ^= 0x1; if (cfs_journal_header_validate(&hdr) != CFS_FORMAT_BAD_CRC) { add_result("format_journal_header", "fail", "bad CRC not detected"); return; } snprintf(detail, sizeof(detail), "journal header checks pass"); add_result("format_journal_header", "ok", detail); } static void test_format_journal_entry(void) { CfsMapEntry e; CfsJournalEntry upd; CfsJournalEntry del; char detail[128]; cfs_map_entry_init(&e); e.physical_offset = 8192; e.compressed_size = 4096; cfs_map_entry_crc_set(&e); cfs_journal_entry_init_update(&upd, 42, &e); if (cfs_journal_entry_validate(&upd) != CFS_FORMAT_OK) { add_result("format_journal_entry", "fail", "UPDATE record rejected"); return; } cfs_journal_entry_init_delete(&del, 42); if (cfs_journal_entry_validate(&del) != CFS_FORMAT_OK) { add_result("format_journal_entry", "fail", "DELETE record rejected"); return; } /* nonzero _reserved is a field error even with a valid CRC. */ upd._reserved[0] = 1; cfs_journal_entry_crc_set(&upd); if (cfs_journal_entry_validate(&upd) != CFS_FORMAT_BAD_FIELD) { add_result("format_journal_entry", "fail", "nonzero reserved not detected"); return; } upd._reserved[0] = 0; cfs_journal_entry_crc_set(&upd); upd.entry_crc ^= 0x1; if (cfs_journal_entry_validate(&upd) != CFS_FORMAT_BAD_CRC) { add_result("format_journal_entry", "fail", "bad CRC not detected"); return; } snprintf(detail, sizeof(detail), "UPDATE/DELETE records ok"); add_result("format_journal_entry", "ok", detail); } static void test_format_block_header(void) { unsigned char page[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT; CfsCompressResult cres; CfsCompressedBlockHeader *bh; char detail[128]; scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); fill_constant(page, sizeof(page), 0x33); opts.algorithm = CFS_ALGORITHM_RAW; opts.min_gain_bytes = 1; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); bh = (CfsCompressedBlockHeader *) cres.result_data; if (cfs_block_header_validate(bh) != CFS_FORMAT_OK) { add_result("format_block_header", "fail", "valid block rejected"); pfree(scratch); return; } bh->magic ^= 0x1; if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_MAGIC) { add_result("format_block_header", "fail", "bad magic not detected"); pfree(scratch); return; } bh->magic ^= 0x1; /* Oversized fields must be rejected before the CRC is computed. */ bh->compressed_size = CFS_BLCKSZ + 1; if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_FIELD) { add_result("format_block_header", "fail", "oversized compressed_size not detected"); pfree(scratch); return; } bh->compressed_size = CFS_BLCKSZ; bh->original_size = CFS_BLCKSZ + 1; if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_FIELD) { add_result("format_block_header", "fail", "non-page original_size not detected"); pfree(scratch); return; } bh->original_size = CFS_BLCKSZ; bh->hdr_crc ^= 0x1; if (cfs_block_header_validate(bh) != CFS_FORMAT_BAD_CRC) { add_result("format_block_header", "fail", "bad CRC not detected"); pfree(scratch); return; } snprintf(detail, sizeof(detail), "block header magic/version/CRC ok"); add_result("format_block_header", "ok", detail); pfree(scratch); } /* ------------------------------------------------------------------ * Path helper tests * ------------------------------------------------------------------ */ static bool cfs_test_ends_with(const char *s, const char *suffix) { size_t ls = strlen(s); size_t lf = strlen(suffix); return ls >= lf && strcmp(s + ls - lf, suffix) == 0; } static void test_path_helpers(void) { RelFileLocatorBackend rl; char *p; CfsFileKind kind; bool ok = true; char detail[160]; /* Default tablespace, permanent relation. */ rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = 16384; rl.locator.relNumber = 12345; rl.backend = INVALID_PROC_NUMBER; p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA); if (p == NULL || !cfs_test_ends_with(p, "/12345.cfp") || strstr(p, "base/") == NULL) ok = false; if (p) pfree(p); p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP); if (p == NULL || !cfs_test_ends_with(p, "/12345.cfsmap")) ok = false; if (p) pfree(p); p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL); if (p == NULL || !cfs_test_ends_with(p, "/12345.cfsjrn")) ok = false; if (p) pfree(p); p = cfs_make_segment_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA, 2); if (p == NULL || !cfs_test_ends_with(p, "/12345.cfp.2")) ok = false; if (p) pfree(p); /* Non-default tablespace. */ rl.locator.spcOid = 99999; p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA); if (p == NULL || strstr(p, "pg_tblspc/") == NULL || !cfs_test_ends_with(p, "/12345.cfp")) ok = false; if (p) pfree(p); /* Temporary (backend-local) locator must be unsupported. */ rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.backend = 1; /* any non-INVALID_PROC_NUMBER value */ p = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA); if (p != NULL) { ok = false; pfree(p); } rl.backend = INVALID_PROC_NUMBER; /* Suffix parsing. */ if (!cfs_sidecar_kind_from_suffix("12345.cfp", &kind) || kind != CFS_FILE_DATA) ok = false; if (!cfs_sidecar_kind_from_suffix("12345.cfsmap", &kind) || kind != CFS_FILE_MAP) ok = false; if (!cfs_sidecar_kind_from_suffix("12345.cfsjrn", &kind) || kind != CFS_FILE_JOURNAL) ok = false; if (!cfs_sidecar_kind_from_suffix("base/16384/12345.cfp.7", &kind) || kind != CFS_FILE_DATA) ok = false; if (cfs_sidecar_kind_from_suffix("12345", &kind)) ok = false; if (cfs_sidecar_kind_from_suffix("12345.dat", &kind)) ok = false; if (!cfs_is_sidecar_filename("12345.cfp")) ok = false; snprintf(detail, sizeof(detail), "default/non-default/temp/suffix cases"); add_result("path_helpers", ok ? "ok" : "fail", detail); } /* ------------------------------------------------------------------ * fsck tests * ------------------------------------------------------------------ */ typedef enum CfsFsckTestMode { FSCK_MODE_CLEAN, FSCK_MODE_BAD_MAP_CRC, FSCK_MODE_TRUNC_JOURNAL, FSCK_MODE_OFFSET_OOB } CfsFsckTestMode; typedef struct CfsFsckFixture { char *dir; char *cfp_path; char *map_path; char *jrn_path; } CfsFsckFixture; static bool cfs_test_write_file(const char *path, const void *data, size_t len) { int fd = BasicOpenFile(path, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY); const char *p = (const char *) data; size_t off = 0; if (fd < 0) return false; while (off < len) { ssize_t n = write(fd, p + off, len - off); if (n < 0) { if (errno == EINTR) continue; close(fd); return false; } off += n; } close(fd); return true; } static bool cfs_fsck_setup(CfsFsckFixture * fx, const char *casename, CfsFsckTestMode mode) { unsigned char page[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT; CfsCompressResult cres; CfsMapEntry e; CfsMapPrologue mhdr; CfsJournalFileHeader jhdr; CfsJournalEntry je; char mapbuf[CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE]; char jrnbuf[CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE]; memset(fx, 0, sizeof(CfsFsckFixture)); fx->dir = psprintf("%s/cfs_fsck_test_%d_%s", DataDir, (int) MyProcPid, casename); if (mkdir(fx->dir, 0700) != 0 && errno != EEXIST) { pfree(fx->dir); fx->dir = NULL; return false; } fx->cfp_path = psprintf("%s/%s.cfp", fx->dir, casename); fx->map_path = psprintf("%s/%s.cfsmap", fx->dir, casename); fx->jrn_path = psprintf("%s/%s.cfsjrn", fx->dir, casename); scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); fill_constant(page, sizeof(page), 0x77); opts.algorithm = CFS_ALGORITHM_RAW; opts.min_gain_bytes = 1; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); /* * Build a single live map entry pointing at the compressed block. Real * records start at CFS_CFP_BASE_OFFSET, so offset 0 stays reserved as the * "absent" sentinel. */ cfs_map_entry_init(&e); e.physical_offset = (mode == FSCK_MODE_OFFSET_OOB) ? 999999 : CFS_CFP_BASE_OFFSET; e.compressed_size = cres.compressed_size; e.generation = 1; cfs_map_entry_crc_set(&e); if (mode == FSCK_MODE_BAD_MAP_CRC) e.entry_crc ^= 0x1; cfs_map_prologue_init(&mhdr); memcpy(mapbuf, &mhdr, sizeof(mhdr)); memcpy(mapbuf + sizeof(mhdr), &e, sizeof(e)); cfs_journal_header_init(&jhdr); cfs_journal_entry_init_update(&je, 0, &e); memcpy(jrnbuf, &jhdr, sizeof(jhdr)); memcpy(jrnbuf + sizeof(jhdr), &je, sizeof(je)); /* * .cfp = reserved lead-in (zero) followed by the compressed record at * CFS_CFP_BASE_OFFSET. */ { size_t tlen = CFS_CFP_BASE_OFFSET + cres.total_size; char *cfpbuf = palloc(tlen); bool ok; MemSet(cfpbuf, 0, CFS_CFP_BASE_OFFSET); memcpy(cfpbuf + CFS_CFP_BASE_OFFSET, cres.result_data, cres.total_size); ok = cfs_test_write_file(fx->cfp_path, cfpbuf, tlen); pfree(cfpbuf); if (!ok) { pfree(scratch); return false; } } if (!cfs_test_write_file(fx->map_path, mapbuf, sizeof(mapbuf))) { pfree(scratch); return false; } if (mode == FSCK_MODE_TRUNC_JOURNAL) { /* Write a torn final record: header + only the first 8 bytes. */ if (!cfs_test_write_file(fx->jrn_path, jrnbuf, sizeof(jhdr) + 8)) { pfree(scratch); return false; } } else { if (!cfs_test_write_file(fx->jrn_path, jrnbuf, sizeof(jrnbuf))) { pfree(scratch); return false; } } pfree(scratch); return true; } static void cfs_fsck_teardown(CfsFsckFixture * fx) { if (fx->cfp_path) { unlink(fx->cfp_path); pfree(fx->cfp_path); } if (fx->map_path) { unlink(fx->map_path); pfree(fx->map_path); } if (fx->jrn_path) { unlink(fx->jrn_path); pfree(fx->jrn_path); } if (fx->dir) { rmdir(fx->dir); pfree(fx->dir); } } static void test_fsck_clean_relation(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; if (!cfs_fsck_setup(&fx, "clean", FSCK_MODE_CLEAN)) { add_result("fsck_clean_relation", "fail", "setup failed"); return; } cfs_fsck_result_init(&res); cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); cfs_fsck_cfp_file(fx.cfp_path, &opts, &res); if (res.errors == 0 && res.live_entries == 1 && res.journal_records == 1 && res.cfp_records == 1) snprintf(detail, sizeof(detail), "live=%llu jrn=%llu cfp=%llu", (unsigned long long) res.live_entries, (unsigned long long) res.journal_records, (unsigned long long) res.cfp_records); else snprintf(detail, sizeof(detail), "errors=%llu live=%llu jrn=%llu cfp=%llu", (unsigned long long) res.errors, (unsigned long long) res.live_entries, (unsigned long long) res.journal_records, (unsigned long long) res.cfp_records); add_result("fsck_clean_relation", (res.errors == 0) ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } static void test_fsck_corrupt_map(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; if (!cfs_fsck_setup(&fx, "badmap", FSCK_MODE_BAD_MAP_CRC)) { add_result("fsck_corrupt_map", "fail", "setup failed"); return; } cfs_fsck_result_init(&res); cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL); snprintf(detail, sizeof(detail), "crc_failures=%llu", (unsigned long long) res.crc_failures); add_result("fsck_corrupt_map", (res.crc_failures > 0) ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } static void test_fsck_torn_journal(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; if (!cfs_fsck_setup(&fx, "truncjrn", FSCK_MODE_TRUNC_JOURNAL)) { add_result("fsck_torn_journal", "fail", "setup failed"); return; } cfs_fsck_result_init(&res); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); snprintf(detail, sizeof(detail), "torn_tails=%llu errors=%llu", (unsigned long long) res.torn_tails, (unsigned long long) res.errors); add_result("fsck_torn_journal", (res.torn_tails == 1 && res.errors == 0) ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } /* * A .cfp file whose last (short) segment ends with a partial block header is * a torn write after a crash, not corruption: it must be reported as a soft * torn_tails status, not as an error. */ static void test_fsck_torn_cfp_header(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; char buf[CFS_CFP_BASE_OFFSET + 20]; bool ok = true; if (!cfs_fsck_setup(&fx, "torncfp", FSCK_MODE_CLEAN)) { add_result("fsck_torn_cfp_header", "fail", "setup failed"); return; } /* Lead-in + a partial (20-byte) block header. */ memset(buf, 0, CFS_CFP_BASE_OFFSET); memset(buf + CFS_CFP_BASE_OFFSET, 0xAB, sizeof(buf) - CFS_CFP_BASE_OFFSET); if (!cfs_test_write_file(fx.cfp_path, buf, sizeof(buf))) ok = false; if (ok) { cfs_fsck_result_init(&res); cfs_fsck_cfp_file(fx.cfp_path, &opts, &res); if (res.torn_tails != 1 || res.errors != 0) ok = false; } snprintf(detail, sizeof(detail), "torn_tails=%llu errors=%llu", (unsigned long long) res.torn_tails, (unsigned long long) res.errors); add_result("fsck_torn_cfp_header", ok ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } /* * A .cfp file whose last (short) segment ends with a valid record header * whose payload was cut off by a crash is a torn tail, not corruption: the * engine never reads the bytes past the last record, and compaction will * reclaim the space. Once a next segment exists, the same layout means real * truncation and must stay a hard error. */ static void test_fsck_torn_cfp_record(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; CfsCompressedBlockHeader bh; char buf[CFS_CFP_BASE_OFFSET + sizeof(bh)]; pg_crc32c crc; char *seg1_path; bool ok = true; if (!cfs_fsck_setup(&fx, "torncfprec", FSCK_MODE_CLEAN)) { add_result("fsck_torn_cfp_record", "fail", "setup failed"); return; } /* Lead-in + a valid RAW record header with the payload missing. */ MemSet(&bh, 0, sizeof(bh)); bh.magic = CFS_BLOCK_MAGIC; bh.version = CFS_FORMAT_VERSION; bh.algorithm = CFS_ALGORITHM_RAW; bh.compressed_size = CFS_BLCKSZ; bh.original_size = CFS_BLCKSZ; INIT_CRC32C(crc); COMP_CRC32C(crc, &bh, offsetof(CfsCompressedBlockHeader, hdr_crc)); FIN_CRC32C(crc); bh.hdr_crc = crc; memset(buf, 0, CFS_CFP_BASE_OFFSET); memcpy(buf + CFS_CFP_BASE_OFFSET, &bh, sizeof(bh)); if (!cfs_test_write_file(fx.cfp_path, buf, sizeof(buf))) ok = false; /* Case 1: single-segment chain — the torn record must be soft. */ if (ok) { cfs_fsck_result_init(&res); cfs_fsck_cfp_file(fx.cfp_path, &opts, &res); if (res.torn_tails != 1 || res.errors != 0 || res.truncated_records != 0) ok = false; } /* * Case 2: a ".cfp.1" makes segment 0 non-final — the same layout is a * hard truncated record. */ seg1_path = psprintf("%s.1", fx.cfp_path); if (ok) { int fd = BasicOpenFile(seg1_path, O_CREAT | O_WRONLY | PG_BINARY); if (fd < 0) ok = false; else close(fd); } if (ok) { cfs_fsck_result_init(&res); cfs_fsck_cfp_file(fx.cfp_path, &opts, &res); if (res.errors < 1 || res.truncated_records < 1) ok = false; /* * Case 3: with ".cfp.1" gone the chain is single-segment again — * the classification must return to a soft torn tail. */ if (unlink(seg1_path) != 0) ok = false; else { cfs_fsck_result_init(&res); cfs_fsck_cfp_file(fx.cfp_path, &opts, &res); if (res.torn_tails != 1 || res.errors != 0 || res.truncated_records != 0) ok = false; } } snprintf(detail, sizeof(detail), "torn_tails=%llu errors=%llu truncated=%llu", (unsigned long long) res.torn_tails, (unsigned long long) res.errors, (unsigned long long) res.truncated_records); add_result("fsck_torn_cfp_record", ok ? "ok" : "fail", detail); unlink(seg1_path); pfree(seg1_path); cfs_fsck_teardown(&fx); } /* * An invalid *full* record in the middle of the .cfp stream is still a hard * error; only a torn tail at the very end is soft. */ static void test_fsck_corrupt_cfp_record(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; int fd; unsigned char b; bool ok = true; if (!cfs_fsck_setup(&fx, "corruptcfp", FSCK_MODE_CLEAN)) { add_result("fsck_corrupt_cfp_record", "fail", "setup failed"); return; } /* Corrupt the magic byte of the single full record in the .cfp. */ fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; if (ok) { if (pread(fd, &b, 1, CFS_CFP_BASE_OFFSET) != 1) ok = false; else { b ^= 0xFF; if (pwrite(fd, &b, 1, CFS_CFP_BASE_OFFSET) != 1) ok = false; } close(fd); } if (ok) { cfs_fsck_result_init(&res); cfs_fsck_cfp_file(fx.cfp_path, &opts, &res); /* * The corrupted byte is part of the header magic, not of the * CRC-covered content: the failure must land in field_failures. */ if (res.field_failures < 1 || res.crc_failures != 0 || res.errors < 1) ok = false; } snprintf(detail, sizeof(detail), "field_failures=%llu errors=%llu", (unsigned long long) res.field_failures, (unsigned long long) res.errors); add_result("fsck_corrupt_cfp_record", ok ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } /* * Synthetic relation locators in these tests bypass smgr's relation-drop * cleanup. Drain their pending sync requests before unlinking sidecars: * otherwise a later real CHECKPOINT can PANIC attempting to fsync an already * removed test file (e.g. 999090.cfsjrn). */ static void cfs_test_unlink_synthetic(RelFileLocatorBackend rlocator) { cfs_forget_sync_requests(rlocator, MAIN_FORKNUM); cfs_unlink(rlocator, MAIN_FORKNUM); } /* * Deep fsck cross-checks every live map entry against the .cfp record header * it points at: an entry whose offset lands in the middle of a record, or * whose fields disagree with the header, is corruption that the independent * map and .cfp scans cannot see. * * The relation is created through the real storage engine so the files live * at their locator-derived paths, then its .cfsmap is corrupted on disk (with * a recomputed entry_crc, so the map scan itself sees nothing wrong). */ static void test_fsck_cross_check(void) { RelFileLocatorBackend rl; CfsRelation *cfs; CfsWriteOptions wopts = CFS_WRITE_OPTIONS_INIT; unsigned char page[TEST_BLCKSZ]; char *map_path; CfsMapEntry e; CfsFsckResult res; CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT; uint64 orig_off; int fd; bool ok = true; /* RAW records: deterministic 8232-byte records, no codec involved. */ wopts.algorithm = CFS_ALGORITHM_RAW; wopts.explicit_algorithm = true; wopts.allow_raw_fallback = true; wopts.min_gain_bytes = 1; rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = 999091; rl.backend = INVALID_PROC_NUMBER; cfs_test_unlink_synthetic(rl); cfs = cfs_create(rl, MAIN_FORKNUM); if (cfs == NULL) { add_result("fsck_cross_check", "fail", "create failed"); return; } /* Two blocks -> two real records in .cfp. */ memset(page, 0x30, sizeof(page)); if (cfs_write_page(cfs, 0, (const char *) page, &wopts) != CFS_STORAGE_OK || cfs_write_page(cfs, 1, (const char *) page, &wopts) != CFS_STORAGE_OK) ok = false; if (ok) { cfs_map_save_snapshot(cfs); test_journal_reset(cfs, ERROR); } cfs_close(cfs); map_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP); /* Baseline: deep fsck on the clean relation must be green. */ if (ok) { cfs_fsck_result_init(&res); cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res); if (res.errors != 0 || res.cross_check_failures != 0) ok = false; } /* * Corrupt block 0's entry: shift the offset 8 bytes into its own record, * so the "header" there is garbage. The CRC is recomputed, so only the * cross-check can see the problem. */ if (ok) { fd = BasicOpenFile(map_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; if (ok) { if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; else { orig_off = e.physical_offset; e.physical_offset = orig_off + CFS_BLOCK_ALIGN; cfs_map_entry_crc_set(&e); if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; } close(fd); } } /* Deep fsck: the bogus offset must surface as a cross-check failure. */ if (ok) { cfs_fsck_result_init(&res); cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res); if (res.cross_check_failures < 1 || res.errors < 1) ok = false; } /* * Restore the offset, then corrupt the compressed_size instead: the * record header is the single source of truth for the payload size, so * the map/header disagreement must surface in the cross-check. */ if (ok) { fd = BasicOpenFile(map_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; if (ok) { if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; else { e.physical_offset = orig_off; e.compressed_size -= 1; /* disagrees with the record header */ cfs_map_entry_crc_set(&e); if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; } close(fd); } } /* Deep fsck: the compressed_size mismatch must surface too. */ if (ok) { cfs_fsck_result_init(&res); cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res); if (res.cross_check_failures < 1 || res.errors < 1) ok = false; } /* Non-deep fsck: no .cfp pass, no cross-check — nothing is detected. */ if (ok) { fopts.verify_block_headers = false; cfs_fsck_result_init(&res); cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res); if (res.cross_check_failures != 0 || res.errors != 0) ok = false; } pfree(map_path); cfs_test_unlink_synthetic(rl); add_result("fsck_cross_check", ok ? "ok" : "fail", ok ? "cross-check flags bogus offsets, deep mode only" : "cross-check failed"); } /* * A shrink RESIZE followed by a grow must stay healable in the dropped * interval: replay applies RESIZE records in order, so the shrink zeroes the * slots it drops and the later grow leaves them sparse. A corrupt map row in * [target, old_nblocks) is therefore healed by the journal even though the * relation grew back over the slot; fsck must not look at the last RESIZE * target alone. * * With an empty journal the same row is real damage, so the fixture also runs * that control to prove the corruption itself is detected. */ static void test_fsck_resize_shrink_grow(void) { RelFileLocatorBackend rl; CfsRelation *cfs; CfsWriteOptions wopts = CFS_WRITE_OPTIONS_INIT; unsigned char page[TEST_BLCKSZ]; char *map_path; char *jrn_path; CfsMapEntry e; CfsFsckResult res; CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT; CfsJournalFileHeader jhdr; int fd; int blk; bool ok = true; /* RAW records: deterministic 8232-byte records, no codec involved. */ wopts.algorithm = CFS_ALGORITHM_RAW; wopts.explicit_algorithm = true; wopts.allow_raw_fallback = true; wopts.min_gain_bytes = 1; rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = 999094; rl.backend = INVALID_PROC_NUMBER; cfs_test_unlink_synthetic(rl); cfs = cfs_create(rl, MAIN_FORKNUM); if (cfs == NULL) { add_result("fsck_resize_shrink_grow", "fail", "create failed"); return; } /* Four blocks -> four rows in the map snapshot. */ memset(page, 0x50, sizeof(page)); for (blk = 0; blk < 4; blk++) { if (cfs_write_page(cfs, blk, (const char *) page, &wopts) != CFS_STORAGE_OK) ok = false; } if (ok) { cfs_map_save_snapshot(cfs); test_journal_reset(cfs, ERROR); } cfs_close(cfs); map_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP); jrn_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL); /* * Journal: shrink to 2 (drops blocks 2 and 3), then grow back to 4. The * replay clears the dropped slots on the shrink and leaves them sparse on * the grow, so block 2's row is healed by the journal, not by its bytes. */ if (ok) { char jrnbuf[CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE]; CfsJournalEntry resize; cfs_journal_header_init(&jhdr); memcpy(jrnbuf, &jhdr, sizeof(jhdr)); cfs_journal_entry_init_resize(&resize, 2); memcpy(jrnbuf + sizeof(jhdr), &resize, sizeof(resize)); cfs_journal_entry_init_resize(&resize, 4); memcpy(jrnbuf + sizeof(jhdr) + sizeof(resize), &resize, sizeof(resize)); if (!cfs_test_write_file(jrn_path, jrnbuf, sizeof(jrnbuf))) ok = false; } /* Corrupt block 2's entry_crc; every role field stays intact. */ if (ok) { fd = BasicOpenFile(map_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; if (ok) { off_t row_off = cfs_map_row_off(2); if (pread(fd, &e, sizeof(e), row_off) != sizeof(e)) ok = false; else { e.entry_crc ^= 0x1; if (pwrite(fd, &e, sizeof(e), row_off) != sizeof(e)) ok = false; } close(fd); } } /* The shrink-then-grow journal heals the row: no damage, one heal. */ if (ok) { cfs_fsck_result_init(&res); cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res); if (res.healed_entries != 1 || res.errors != 0 || res.cross_check_failures != 0) ok = false; } /* Control: with an empty journal the same row is real damage. */ if (ok) { cfs_journal_header_init(&jhdr); if (!cfs_test_write_file(jrn_path, &jhdr, sizeof(jhdr))) ok = false; } if (ok) { cfs_fsck_result_init(&res); cfs_fsck_relation(rl, MAIN_FORKNUM, &fopts, &res); if (res.errors < 1 || res.healed_entries != 0) ok = false; } pfree(map_path); pfree(jrn_path); cfs_test_unlink_synthetic(rl); add_result("fsck_resize_shrink_grow", ok ? "ok" : "fail", ok ? "shrink then grow keeps the dropped slot healable" : "shrink-then-grow coverage failed"); } /* * The recovery scan must use the strict sidecar-name parser: a journal * renamed to a leading-zero name ("0999092.cfsjrn") is ignored — the engine * never creates such names — while the valid name is replayed as usual. * * The relation lives at its locator-derived paths in the real database * directory, so the public CfsReplayAllJournals() scan finds it. A lenient * parser would map the decoy onto the relation and open it, recreating the * journal file; the strict parser must leave both files untouched. */ static void test_recovery_scan_strict_names(void) { RelFileLocatorBackend rl; CfsRelation *cfs; CfsWriteOptions wopts = CFS_WRITE_OPTIONS_INIT; unsigned char page[TEST_BLCKSZ]; char *jrn_path; char *decoy_path; struct stat st; bool ok = true; wopts.algorithm = CFS_ALGORITHM_RAW; wopts.explicit_algorithm = true; wopts.allow_raw_fallback = true; wopts.min_gain_bytes = 1; rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = 999092; rl.backend = INVALID_PROC_NUMBER; cfs_test_unlink_synthetic(rl); cfs = cfs_create(rl, MAIN_FORKNUM); if (cfs == NULL) { add_result("recovery_scan_strict_names", "fail", "create failed"); return; } /* One write leaves an UPDATE record pending in the journal. */ memset(page, 0x40, sizeof(page)); if (cfs_write_page(cfs, 0, (const char *) page, &wopts) != CFS_STORAGE_OK) ok = false; cfs_close(cfs); jrn_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL); { const char *slash = strrchr(jrn_path, '/'); decoy_path = psprintf("%.*s/0999092.cfsjrn", (int) (slash - jrn_path), jrn_path); } /* Hide the journal under a leading-zero name the engine never creates. */ if (ok && rename(jrn_path, decoy_path) != 0) ok = false; if (ok) { CfsReplayAllJournals(); /* * The decoy must be ignored entirely: its content untouched, and the * relation never opened (a recreated journal file would prove the * lenient name mapping). */ if (stat(decoy_path, &st) != 0 || st.st_size <= (off_t) CFS_JOURNAL_HEADER_SIZE) ok = false; if (stat(jrn_path, &st) == 0) ok = false; /* must not have been recreated */ } /* Restore the valid name. */ if (ok && rename(decoy_path, jrn_path) != 0) ok = false; if (ok) { CfsReplayAllJournals(); /* Valid name: replayed, journal truncated back to the bare header. */ if (stat(jrn_path, &st) != 0 || st.st_size != (off_t) CFS_JOURNAL_HEADER_SIZE) ok = false; } unlink(decoy_path); pfree(jrn_path); pfree(decoy_path); cfs_test_unlink_synthetic(rl); add_result("recovery_scan_strict_names", ok ? "ok" : "fail", ok ? "leading-zero journal ignored, valid name replayed" : "recovery scan name handling broken"); } static void test_fsck_offset_out_of_range(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; if (!cfs_fsck_setup(&fx, "oob", FSCK_MODE_OFFSET_OOB)) { add_result("fsck_offset_out_of_range", "fail", "setup failed"); return; } cfs_fsck_result_init(&res); cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL); snprintf(detail, sizeof(detail), "offset_oob=%llu", (unsigned long long) res.offset_out_of_range); add_result("fsck_offset_out_of_range", (res.offset_out_of_range > 0) ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } /* * A map with live entries but a missing/empty .cfp chain must be flagged in * both deep and non-deep modes; the per-entry EOF check only runs when * cfp_size > 0, so this case is caught by a dedicated end-of-scan check. */ static void test_fsck_live_entries_missing_cfp(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; bool ok = true; if (!cfs_fsck_setup(&fx, "live_nocfp", FSCK_MODE_CLEAN)) { add_result("fsck_live_entries_missing_cfp", "fail", "setup failed"); return; } /* Remove the .cfp data file: the live map entry now points nowhere. */ if (unlink(fx.cfp_path) != 0) ok = false; pfree(fx.cfp_path); fx.cfp_path = NULL; /* Non-deep mode. */ cfs_fsck_result_init(&res); opts.verify_block_headers = false; cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL); if (res.live_entries < 1 || res.missing_files < 1 || res.errors < 1) ok = false; /* Deep mode. */ cfs_fsck_result_init(&res); opts.verify_block_headers = true; cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL); if (res.live_entries < 1 || res.missing_files < 1 || res.errors < 1) ok = false; add_result("fsck_live_entries_missing_cfp", ok ? "ok" : "fail", ok ? "live map + missing .cfp is an error in both modes" : "live map + missing .cfp not detected"); cfs_fsck_teardown(&fx); } /* * A fully empty map (no entries) without a .cfp file is a clean relation, * not an error. */ static void test_fsck_empty_map_no_cfp(void) { char *dir; char *map_path; CfsMapPrologue mhdr; char mapbuf[CFS_MAP_HEADER_SIZE]; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; bool ok = true; dir = psprintf("%s/cfs_fsck_empty_%d", DataDir, (int) MyProcPid); if (mkdir(dir, 0700) != 0 && errno != EEXIST) { pfree(dir); add_result("fsck_empty_map_no_cfp", "fail", "setup failed"); return; } map_path = psprintf("%s/empty.cfsmap", dir); cfs_map_prologue_init(&mhdr); memcpy(mapbuf, &mhdr, sizeof(mhdr)); if (!cfs_test_write_file(map_path, mapbuf, sizeof(mapbuf))) ok = false; cfs_fsck_result_init(&res); opts.verify_block_headers = false; cfs_fsck_map_file(map_path, NULL, &opts, &res, NULL); if (res.errors != 0 || res.live_entries != 0) ok = false; unlink(map_path); pfree(map_path); rmdir(dir); pfree(dir); add_result("fsck_empty_map_no_cfp", ok ? "ok" : "fail", ok ? "empty map without .cfp is clean" : "empty map without .cfp misreported"); } /* ================================================================ * autonomous storage layer * ================================================================ */ typedef struct CfsStorageFixture { char *dir; char *cfp_path; char *map_path; char *jrn_path; RelFileLocatorBackend rl; /* synthetic, for diagnostics only */ } CfsStorageFixture; static void cfs_storage_setup(CfsStorageFixture * fx, const char *casename) { MemoryContext oldcontext; memset(fx, 0, sizeof(*fx)); /* * A test may catch an expected ERROR and keep using the fixture. An * ERROR resets the query context, so keep the paths in the same durable * context the backend uses for CFS handles; teardown pfrees them. */ oldcontext = MemoryContextSwitchTo(TopMemoryContext); fx->dir = psprintf("%s/cfs_storage_test_%d_%s", DataDir, (int) MyProcPid, casename); if (mkdir(fx->dir, 0700) != 0 && errno != EEXIST) { pfree(fx->dir); fx->dir = NULL; MemoryContextSwitchTo(oldcontext); return; } fx->cfp_path = psprintf("%s/%s.cfp", fx->dir, casename); fx->map_path = psprintf("%s/%s.cfsmap", fx->dir, casename); fx->jrn_path = psprintf("%s/%s.cfsjrn", fx->dir, casename); MemoryContextSwitchTo(oldcontext); fx->rl.locator.spcOid = DEFAULTTABLESPACE_OID; fx->rl.locator.dbOid = 16384; fx->rl.locator.relNumber = 99990; fx->rl.backend = INVALID_PROC_NUMBER; } static void cfs_storage_teardown(CfsStorageFixture * fx) { /* * Drop every shared cache trace of the fixture's relation before its * files go away: an unpinned leftover slot would carry an IDLE .cfp * tail that describes the unlinked files, and the next fixture that * reuses this relNumber must not inherit it (the cfs_write_page() * contract requires no slot without a pin, cfs_storage.h). */ cfs_map_cache_invalidate(fx->rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx->rl, MAIN_FORKNUM); /* * The fixture uses a synthetic relfilenumber with sidecar files outside * the normal relation path. Writes can enqueue fsync requests using the * synthetic locator; if left pending, a later CHECKPOINT would attempt * to fsync base//99990.cfp instead of these fixture paths and * PANIC after the files have been removed. Cancel only this fixture's * registered requests before unlinking its files. */ if (fx->rl.locator.relNumber != 0) cfs_forget_sync_requests(fx->rl, MAIN_FORKNUM); if (fx->cfp_path) { /* Remove the whole segment chain (".cfp", ".cfp.1", ...). */ uint32 segno; for (segno = 0;; segno++) { char *seg = (segno == 0) ? pstrdup(fx->cfp_path) : psprintf("%s.%u", fx->cfp_path, segno); if (unlink(seg) != 0) { pfree(seg); break; } pfree(seg); } pfree(fx->cfp_path); } if (fx->map_path) { unlink(fx->map_path); pfree(fx->map_path); } if (fx->jrn_path) { unlink(fx->jrn_path); pfree(fx->jrn_path); } if (fx->dir) { rmdir(fx->dir); pfree(fx->dir); } } /* * Open (creating) a fresh CfsRelation from a fixture. The handle lives in * TopMemoryContext like a backend smgr handle, so a test that catches an * expected ERROR can still close it (and its paths) afterwards. */ static CfsRelation * cfs_storage_open_new(const CfsStorageFixture * fx) { CfsRelation *cfs; MemoryContext oldcontext; oldcontext = MemoryContextSwitchTo(TopMemoryContext); cfs = cfs_open_paths(fx->rl, MAIN_FORKNUM, fx->cfp_path, fx->map_path, fx->jrn_path, CFS_OPEN_RDWR | CFS_OPEN_CREATE); MemoryContextSwitchTo(oldcontext); return cfs; } /* * Open a lazy handle in TopMemoryContext, the way the smgr bridge does. * These tests catch an expected ERROR from the read path and keep using the * handle; a handle allocated in the query context is already freed by then. */ static CfsRelation * cfs_test_open_lazy(RelFileLocatorBackend rl, const char *cfp_path, const char *map_path, const char *jrn_path) { CfsRelation *cfs; MemoryContext oldcontext; oldcontext = MemoryContextSwitchTo(TopMemoryContext); cfs = cfs_open_paths(rl, MAIN_FORKNUM, cfp_path, map_path, jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP); MemoryContextSwitchTo(oldcontext); return cfs; } /* Fill a page with a deterministic, compressible pattern tagged by 'tag'. */ static void cfs_test_fill_page(unsigned char *page, unsigned char tag) { size_t i; for (i = 0; i < TEST_BLCKSZ; i++) page[i] = (unsigned char) ((tag + i) & 0x7F); } static CfsWriteOptions cfs_test_write_opts(void) { CfsWriteOptions opts = CFS_WRITE_OPTIONS_INIT; opts.algorithm = CfsCodecAvailable(CFS_ALGORITHM_LZ4) ? CFS_ALGORITHM_LZ4 : CFS_ALGORITHM_RAW; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; return opts; } static void test_storage_create_open(void) { CfsStorageFixture fx; CfsRelation *cfs; char detail[128]; cfs_storage_setup(&fx, "create"); if (fx.dir == NULL) { add_result("storage_create_open", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); if (cfs == NULL || cfs_map_nblocks(cfs) != 0) { snprintf(detail, sizeof(detail), "nblocks=%u", cfs ? cfs_map_nblocks(cfs) : 0); add_result("storage_create_open", "fail", detail); if (cfs) cfs_close(cfs); cfs_storage_teardown(&fx); return; } cfs_close(cfs); /* Reopen without CREATE and verify headers validate. */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs == NULL || cfs_map_nblocks(cfs) != 0) { snprintf(detail, sizeof(detail), "reopen nblocks=%u", cfs ? cfs_map_nblocks(cfs) : 0); add_result("storage_create_open", "fail", detail); if (cfs) cfs_close(cfs); cfs_storage_teardown(&fx); return; } cfs_close(cfs); snprintf(detail, sizeof(detail), "create+reopen, nblocks=0"); add_result("storage_create_open", "ok", detail); cfs_storage_teardown(&fx); } static void test_storage_write_read(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; cfs_storage_setup(&fx, "rw"); if (fx.dir == NULL) { add_result("storage_write_read", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x10); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) { add_result("storage_write_read", "fail", "write_page failed"); cfs_close(cfs); cfs_storage_teardown(&fx); return; } /* After an append the in-memory entry must be CRC-consistent. */ if (cfs_map_entry_validate(&cfs->map[0], true) != CFS_FORMAT_OK || !CFS_MAP_ENTRY_VALID(&cfs->map[0])) { add_result("storage_write_read", "fail", "map header CRC inconsistent after append"); cfs_close(cfs); cfs_storage_teardown(&fx); return; } if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) { add_result("storage_write_read", "fail", "read mismatch"); cfs_close(cfs); cfs_storage_teardown(&fx); return; } snprintf(detail, sizeof(detail), "write+read block 0 ok, nblocks=%u", cfs_map_nblocks(cfs)); add_result("storage_write_read", "ok", detail); cfs_close(cfs); cfs_storage_teardown(&fx); } static void test_storage_update_generation(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pageA[TEST_BLCKSZ]; unsigned char pageB[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; bool ok = true; cfs_storage_setup(&fx, "gen"); if (fx.dir == NULL) { add_result("storage_update_generation", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(pageA, 0x20); cfs_test_fill_page(pageB, 0x30); cfs_write_page(cfs, 0, (const char *) pageA, &opts); cfs_write_page(cfs, 0, (const char *) pageB, &opts); /* Latest generation must be read back. */ if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(pageB, back, TEST_BLCKSZ) != 0) ok = false; /* The header watermark must cover every entry it will persist. */ if (cfs->map == NULL || cfs_map_nblocks(cfs) < 1 || cfs->map_hdr.max_generation < cfs->map[0].generation) ok = false; /* Close and reopen: the journal must replay to the latest version. */ cfs_close(cfs); cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(pageB, back, TEST_BLCKSZ) != 0) ok = false; if (cfs->map == NULL || cfs_map_nblocks(cfs) < 1 || cfs->map_hdr.max_generation < cfs->map[0].generation) ok = false; /* An old on-disk version must be rejected, never silently upgraded. */ { CfsMapPrologue prologue; cfs_map_prologue_init(&prologue); prologue.version = CFS_MAP_VERSION - 1; if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_BAD_VERSION) ok = false; } cfs_close(cfs); snprintf(detail, sizeof(detail), "generation=%s", ok ? "latest" : "stale"); add_result("storage_update_generation", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * The checkpoint fold must apply the replay's durability policy: an UPDATE * record whose referenced .cfp record is missing is skipped, not frozen * into the map right before the journal reset erases the evidence. */ static void test_storage_fold_skips_missing_cfp(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry bogus; CfsJournalFoldResult res; off_t jrn_size; int64 folded; bool ok = true; cfs_storage_setup(&fx, "foldskip"); if (fx.dir == NULL) { add_result("storage_fold_skips_missing_cfp", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x42); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK || cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK) ok = false; test_journal_reset(cfs, ERROR); /* * A structurally valid UPDATE that points at a .cfp offset which was * never written: the record itself is durable, its data is not. */ cfs_map_entry_init(&bogus); bogus.physical_offset = CFS_CFP_BASE_OFFSET + 1024 * 1024; bogus.compressed_size = 8; bogus.generation = cfs->map_hdr.max_generation + 1; cfs_map_entry_crc_set(&bogus); cfs_journal_append_update(cfs, 0, &bogus); jrn_size = cfs_fd_size(cfs->jrn_fd); if (jrn_size < (off_t) CFS_JOURNAL_HEADER_SIZE) ok = false; folded = ok ? cfs_journal_fold(cfs, CFS_JOURNAL_HEADER_SIZE, jrn_size, 1, &res) : -1; if (folded != 0 || res.superseded_pages != 0) ok = false; /* The persisted row must still point at the original page. */ if (ok) { cfs_close(cfs); cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; } cfs_close(cfs); add_result("storage_fold_skips_missing_cfp", ok ? "ok" : "fail", ok ? "row preserved" : "record was folded"); cfs_storage_teardown(&fx); } /* * The apply engine's sink contract: an UPDATE whose update_usable hook * rejects it is not written but still occupies its generation, and a * RESIZE records its target. One policy drives every replay path. */ static void test_apply_write_row(void *arg, BlockNumber block, const CfsMapEntry *row) { uint64 *n = (uint64 *) arg; (*n)++; (void) block; (void) row; } static void test_apply_resize(void *arg, BlockNumber target) { (void) arg; (void) target; } static bool test_apply_never_usable(void *arg, const CfsJournalEntry *je) { (void) arg; (void) je; return false; } static void test_cfs_journal_apply_sink(void) { CfsStorageFixture fx; CfsRelation *cfs; CfsMapEntry entry; CfsJournalEntry je; CfsJournalSink sink; uint64 written = 0; bool ok = true; cfs_storage_setup(&fx, "applysink"); if (fx.dir == NULL) { add_result("journal_apply_policy", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); memset(&sink, 0, sizeof(sink)); sink.write_row = test_apply_write_row; sink.resize = test_apply_resize; sink.update_usable = test_apply_never_usable; sink.arg = &written; memset(&je, 0, sizeof(je)); je.op = CFS_JRN_OP_UPDATE; je.blocknum = 7; cfs_map_entry_init(&entry); entry.generation = 41; cfs_map_entry_crc_set(&entry); je.new_entry = entry; cfs_journal_apply_record(cfs, &je, &sink); if (written != 0 || sink.max_generation != 41) ok = false; /* skipped, but the generation counts */ je.op = CFS_JRN_OP_RESIZE; je.blocknum = 3; cfs_journal_apply_record(cfs, &je, &sink); if (!sink.have_resize || sink.resize_target != 3) ok = false; cfs_close(cfs); add_result("journal_apply_policy", ok ? "ok" : "fail", ok ? "one policy" : "sink contract broken"); cfs_storage_teardown(&fx); } static void cfs_test_seg_cb(BlockNumber blocknum, const CfsMapEntry *entry, void *arg) { uint64 *applied = (uint64 *) arg; (void) blocknum; (void) entry; (*applied)++; } /* * The segment replay is where the pool sync and the scratch fallback reach the * journal, so it must reject a journal whose header does not validate before * it interprets any bytes as records. After a reset the header is always * present, so a failure here is corruption, not a legitimate empty journal. * The error must be the corrupt-journal one and no record may reach the * callback. */ static void test_storage_segment_replay_header(void) { CfsStorageFixture fx; CfsRelation *cfs; CfsJournalFileHeader hdr; unsigned char page[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); MemoryContext oldcontext = CurrentMemoryContext; uint64 applied = 0; char detail[128]; bool rejected = false; bool ok = true; cfs_storage_setup(&fx, "jreplayhdr"); if (fx.dir == NULL) { add_result("storage_replay_bad_header", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x5a); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; /* A real journal now exists; corrupt its magic in place. */ if (ok && cfs_pread_all(cfs->jrn_fd, &hdr, sizeof(hdr), 0) != CFS_STORAGE_OK) ok = false; if (ok) { hdr.magic ^= 0xFF; if (cfs_pwrite_all(cfs->jrn_fd, &hdr, sizeof(hdr), 0) != CFS_STORAGE_OK) ok = false; } if (ok) { PG_TRY(); { (void) cfs_journal_replay_segment(cfs, CFS_JOURNAL_HEADER_SIZE, 0, cfs_test_seg_cb, &applied); } PG_CATCH(); { ErrorData *edata; /* * An ERROR leaves CurrentMemoryContext on ErrorContext; switch * back before copying, or the CopyErrorData assert trips. * * Outside recovery the header rejection is routed through * cfs_report_corruption() (QDB-1507 U8), so accept both the * historical direct message and the centralised one. */ MemoryContextSwitchTo(oldcontext); edata = CopyErrorData(); rejected = (edata->sqlerrcode == ERRCODE_DATA_CORRUPTED && edata->message != NULL && (strstr(edata->message, "corrupt page map journal") != NULL || strstr(edata->message, "checksum or format corruption") != NULL)); FreeErrorData(edata); FlushErrorState(); } PG_END_TRY(); } if (!rejected || applied != 0) ok = false; cfs_close(cfs); if (ok) strlcpy(detail, "header rejected before any record", sizeof(detail)); else snprintf(detail, sizeof(detail), "rejected=%d records=%llu", rejected ? 1 : 0, (unsigned long long) applied); add_result("storage_replay_bad_header", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Journal an UPDATE for blocknum carrying the given generation. The * production write path journals every generation it allocates under the * same append lock; the counter test has to do the same, otherwise an * allocated-but-never-journaled value has no on-disk trace to be monotonic * against. */ static void cfs_test_journal_generation(CfsRelation *cfs, BlockNumber blocknum, uint32 generation) { CfsMapEntry entry; cfs_map_entry_init(&entry); entry.physical_offset = CFS_CFP_BASE_OFFSET; entry.compressed_size = 8; entry.generation = generation; cfs_map_entry_crc_set(&entry); cfs_journal_append_update(cfs, blocknum, &entry); } /* * Relation-wide generation allocator (E1): the first value handed out must be * strictly above every generation the snapshot header or the journal still * holds, and values must never repeat, including after the metadata slot is * dropped and the counter re-seeds. The test exercises the allocator * directly: cfs_write_page() is a single-threaded test/compaction helper that * keeps deriving the generation from the local map, the shared counter is * consumed by cfs_write_page_cached(). */ static void test_storage_next_generation(void) { CfsStorageFixture fx; CfsRelation *h; CfsRelation *lazy; unsigned char page[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[160]; uint32 g1 = 0; uint32 g2 = 0; uint32 g3 = 0; uint32 g4 = 0; bool ok = true; cfs_storage_setup(&fx, "nextgen"); if (fx.dir == NULL) { add_result("storage_next_generation", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800760; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); h = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x51); cfs_write_page(h, 0, (const char *) page, &opts); /* generation 1 */ cfs_write_page(h, 0, (const char *) page, &opts); /* generation 2 */ if (cfs_map_save_snapshot(h) != CFS_STORAGE_OK) /* header watermark 2 */ ok = false; /* Generation 3 stays journal-only: the on-disk header keeps 2. */ cfs_write_page(h, 0, (const char *) page, &opts); cfs_close(h); /* * Drop the metadata slot. The on-disk header still says 2 while the * journal tail holds 3: seeding from the header alone would return 3 and * reuse a generation the journal already carries. */ cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); lazy = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP); if (lazy == NULL) ok = false; else { cfs_append_lock_acquire(fx.rl, MAIN_FORKNUM, LW_EXCLUSIVE); g1 = cfs_map_cache_next_generation(lazy); cfs_test_journal_generation(lazy, 0, g1); g2 = cfs_map_cache_next_generation(lazy); cfs_test_journal_generation(lazy, 0, g2); cfs_append_lock_release(fx.rl, MAIN_FORKNUM); /* Losing the slot must not recycle the generations just journaled. */ cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); cfs_append_lock_acquire(fx.rl, MAIN_FORKNUM, LW_EXCLUSIVE); g3 = cfs_map_cache_next_generation(lazy); cfs_test_journal_generation(lazy, 0, g3); g4 = cfs_map_cache_next_generation(lazy); cfs_append_lock_release(fx.rl, MAIN_FORKNUM); cfs_close(lazy); } if (g1 <= 3 || g2 <= g1 || g3 <= g2 || g4 <= g3) ok = false; cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "generations %u/%u/%u/%u %s", g1, g2, g3, g4, ok ? "monotonic above journal" : "reused or below journal"); add_result("storage_next_generation", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Crash-recovery simulation: write several pages, close WITHOUT checkpoint * (so the .cfsmap snapshot stays empty and only the journal has the data), * then reopen and verify that journal replay reconstructs every page. */ static void test_storage_journal_replay(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pages[5][TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; int i; bool ok = true; cfs_storage_setup(&fx, "replay"); if (fx.dir == NULL) { add_result("storage_journal_replay", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); for (i = 0; i < 5; i++) { cfs_test_fill_page(pages[i], (unsigned char) (0x40 + i)); if (cfs_write_page(cfs, i, (const char *) pages[i], &opts) != CFS_STORAGE_OK) { ok = false; break; } } cfs_close(cfs); /* Reopen: snapshot is empty, journal must be replayed. */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_map_nblocks(cfs) != 5) ok = false; for (i = 0; ok && i < 5; i++) { if (cfs_read_page(cfs, i, (char *) back) != CFS_STORAGE_OK || memcmp(pages[i], back, TEST_BLCKSZ) != 0) ok = false; } /* Idempotency: replay again must not change anything. */ { off_t stop_off; bool mid_file_stop = false; (void) cfs_journal_replay(cfs, &stop_off, &mid_file_stop, NULL, 0, CFS_LOAD_NORMAL); /* A fully valid journal must never be classified as mid-file torn. */ if (mid_file_stop) ok = false; } for (i = 0; ok && i < 5; i++) { if (cfs_read_page(cfs, i, (char *) back) != CFS_STORAGE_OK || memcmp(pages[i], back, TEST_BLCKSZ) != 0) ok = false; } cfs_close(cfs); snprintf(detail, sizeof(detail), "5 pages replayed %s", ok ? "ok" : "failed"); add_result("storage_journal_replay", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Checkpoint: after writing, save a snapshot and truncate the journal, then * reopen and confirm the snapshot alone reproduces the data (0 replays). */ static void test_storage_checkpoint(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; bool ok = true; cfs_storage_setup(&fx, "ckpt"); if (fx.dir == NULL) { add_result("storage_checkpoint", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x50); cfs_write_page(cfs, 0, (const char *) page, &opts); cfs_write_page(cfs, 1, (const char *) page, &opts); /* Checkpoint: snapshot + journal reset. */ cfs_map_save_snapshot(cfs); test_journal_reset(cfs, ERROR); cfs_close(cfs); /* Reopen: snapshot holds the data, journal is empty. */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_map_nblocks(cfs) != 2) ok = false; if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; if (cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; cfs_close(cfs); snprintf(detail, sizeof(detail), "checkpoint+reopen %s", ok ? "ok" : "failed"); add_result("storage_checkpoint", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * A map entry whose compressed_size exceeds the page size (with a valid, * recomputed entry_crc — a "malicious" corruption) must be rejected at read * time as corruption instead of driving a palloc sized off the bogus field. */ static void test_read_record_size_guard(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry e; int fd; bool ok = true; cfs_storage_setup(&fx, "sizeguard"); if (fx.dir == NULL) { add_result("read_record_size_guard", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x11); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; /* Persist a snapshot and drop the journal so the entry survives reopen. */ if (ok) { cfs_map_save_snapshot(cfs); test_journal_reset(cfs, ERROR); } cfs_close(cfs); /* Inflate the on-disk entry's compressed_size and fix up its CRC. */ fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; if (ok) { if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; else { e.compressed_size = CFS_BLCKSZ + 1; cfs_map_entry_crc_set(&e); if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; } close(fd); } /* The corrupted entry must come back as corruption, without OOM. */ if (ok) { cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_CORRUPT) ok = false; cfs_close(cfs); } add_result("read_record_size_guard", ok ? "ok" : "fail", ok ? "inflated compressed_size rejected as CORRUPT" : "oversized record was not rejected"); cfs_storage_teardown(&fx); } /* * A sparse hole (an all-zero row) is a legal * never-written block and reads as a zero page, not as corruption. */ static void test_map_sparse_hole_zero_page(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; unsigned char zero[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry hole; int fd; bool ok = true; cfs_storage_setup(&fx, "sparsehole"); if (fx.dir == NULL) { add_result("map_sparse_hole_zero_page", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x31); MemSet(zero, 0, sizeof(zero)); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK) ok = false; if (ok) test_journal_reset(cfs, ERROR); cfs_close(cfs); /* Append an all-zero row for block 1, extending the file by one row. */ if (ok) { fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; else { MemSet(&hole, 0, sizeof(hole)); if (pwrite(fd, &hole, sizeof(hole), CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE) != sizeof(hole)) ok = false; close(fd); } } /* The hole reads as a zero page; the written block keeps its data. */ if (ok) { cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_map_nblocks(cfs) != 2 || cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK || memcmp(zero, back, TEST_BLCKSZ) != 0 || cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; cfs_close(cfs); } add_result("map_sparse_hole_zero_page", ok ? "ok" : "fail", ok ? "sparse hole reads as a zero page" : "sparse hole mishandled"); cfs_storage_teardown(&fx); } /* * A corrupt row whose block the journal still covers is * healed by the replay - the map reads back the correct data. */ static void test_map_corrupt_row_healed(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry e; int fd; bool ok = true; cfs_storage_setup(&fx, "maphealed"); if (fx.dir == NULL) { add_result("map_corrupt_row_healed", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x52); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; /* Snapshot only: the journal record for block 0 stays in place. */ if (ok && cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK) ok = false; cfs_close(cfs); /* Break the on-disk row CRC; the journal record still covers block 0. */ if (ok) { fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; else { if (pread(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; else { e.physical_offset ^= UINT64_C(1); if (pwrite(fd, &e, sizeof(e), CFS_MAP_HEADER_SIZE) != sizeof(e)) ok = false; } close(fd); } } /* The replay must heal the row: the read returns the written data. */ if (ok) { cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; cfs_close(cfs); } add_result("map_corrupt_row_healed", ok ? "ok" : "fail", ok ? "covering journal record healed the corrupt row" : "healing failed"); cfs_storage_teardown(&fx); } /* * Crash-after-cfp simulation: write two blocks, then physically truncate the * last journal record (as if the process died after the .cfp append but * before the journal was durable). After reopen the lost block must be * absent while the earlier block survives. */ static void test_storage_crash_after_cfp(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page0[TEST_BLCKSZ]; unsigned char page1[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; bool ok = true; cfs_storage_setup(&fx, "crash"); if (fx.dir == NULL) { add_result("storage_crash_after_cfp", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page0, 0x60); cfs_test_fill_page(page1, 0x70); cfs_write_page(cfs, 0, (const char *) page0, &opts); cfs_write_page(cfs, 1, (const char *) page1, &opts); cfs_close(cfs); /* * Remove block 1's journal records (its RESIZE + UPDATE), simulating a * crash that left block 1's journal entry torn. Each extend-write now * appends a RESIZE followed by an UPDATE, so block 0 occupies the first * two records of the journal. */ { off_t keep = CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE; if (pg_truncate(fx.jrn_path, keep) != 0) ok = false; } /* Reopen: only block 0 should be recoverable. */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_map_nblocks(cfs) != 1) ok = false; if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page0, back, TEST_BLCKSZ) != 0) ok = false; cfs_close(cfs); snprintf(detail, sizeof(detail), "nblocks=%u after trunc", ok ? 1u : 0u); add_result("storage_crash_after_cfp", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } static void test_storage_zero_extend_truncate(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char back[TEST_BLCKSZ]; unsigned char zero[TEST_BLCKSZ]; off_t jrn_after_extend; char detail[160]; bool ok = true; cfs_storage_setup(&fx, "ext"); if (fx.dir == NULL) { add_result("storage_zero_extend_truncate", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); MemSet(zero, 0, TEST_BLCKSZ); /* Extend by 4 zero blocks. */ if (cfs_zero_extend(cfs, 0, 4) != CFS_STORAGE_OK || cfs_map_nblocks(cfs) != 4) ok = false; /* * zero_extend must journal only a single RESIZE record (header + one * entry), not one UPDATE per extended block. A larger journal would mean * the per-block UPDATE loop is back. */ jrn_after_extend = cfs->jrn_write_off; if (jrn_after_extend != (off_t) (CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE)) ok = false; /* Zero blocks must read back as all-zero pages. */ if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK || memcmp(back, zero, TEST_BLCKSZ) != 0)) ok = false; /* Truncate to 1 block. */ if (ok && cfs_truncate(cfs, 1) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_nblocks(cfs) != 1) ok = false; cfs_close(cfs); snprintf(detail, sizeof(detail), "extend+truncate %s (journal after extend=%lld, expect=%lld)", ok ? "ok" : "failed", (long long) jrn_after_extend, (long long) (CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE)); add_result("storage_zero_extend_truncate", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * cfs_zero_extend must reject a start/count pair whose sum overflows * BlockNumber (and would otherwise wrap to a tiny nblocks), instead of * silently extending to a wrong size. */ static void test_storage_zero_extend_overflow(void) { CfsStorageFixture fx; CfsRelation *cfs; MemoryContext oldcontext = CurrentMemoryContext; bool raised = false; bool ok = true; cfs_storage_setup(&fx, "ext_ovf"); if (fx.dir == NULL) { add_result("storage_zero_extend_overflow", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); /* * MaxBlockNumber - 2 + 4 exceeds MaxBlockNumber: this must raise an ERROR * (ERRCODE_PROGRAM_LIMIT_EXCEEDED) rather than wrap around. */ PG_TRY(); { cfs_zero_extend(cfs, (BlockNumber) (MaxBlockNumber - 2), 4); raised = false; } PG_CATCH(); { ErrorData *edata; MemoryContextSwitchTo(oldcontext); edata = CopyErrorData(); raised = (edata->sqlerrcode == ERRCODE_PROGRAM_LIMIT_EXCEEDED); FlushErrorState(); } PG_END_TRY(); if (!raised) ok = false; /* * A start beyond MaxBlockNumber must also be rejected. With only "count * > MaxBlockNumber - start" the subtraction wraps when start is * InvalidBlockNumber, the guard passes, and end = start + count silently * wraps to a tiny nblocks. start=InvalidBlockNumber, count=2 -> end=1. */ PG_TRY(); { cfs_zero_extend(cfs, InvalidBlockNumber, 2); raised = false; } PG_CATCH(); { ErrorData *edata; MemoryContextSwitchTo(oldcontext); edata = CopyErrorData(); raised = (edata->sqlerrcode == ERRCODE_PROGRAM_LIMIT_EXCEEDED); FlushErrorState(); } PG_END_TRY(); if (!raised) ok = false; /* The overflow must be rejected before any state change: nblocks == 0. */ if (ok && cfs_map_nblocks(cfs) != 0) ok = false; cfs_close(cfs); cfs_storage_teardown(&fx); add_result("storage_zero_extend_overflow", ok ? "ok" : "fail", ok ? "overflow rejected with ERRCODE_PROGRAM_LIMIT_EXCEEDED" : "overflow not rejected"); } /* * TRUNCATE must journal a single RESIZE (whose replay invalidates the * dropped slots), not one DELETE per removed block. Verify the journal has * no DELETE records, replay restores nblocks and invalidates the dropped * slots, and re-extending does not resurrect the truncated entries. */ static void test_storage_truncate_journal_resize_only(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char zero[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); off_t off; int n_resizes = 0; int n_deletes = 0; char detail[160]; int i; bool ok = true; cfs_storage_setup(&fx, "trjrn"); if (fx.dir == NULL) { add_result("storage_truncate_journal_resize_only", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x71); MemSet(zero, 0, TEST_BLCKSZ); /* Write 6 live blocks so the old code path would have journaled DELETEs. */ for (i = 0; i < 6 && ok; i++) { if (cfs_write_page(cfs, i, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; } /* Truncate to 2 blocks. */ if (ok && cfs_truncate(cfs, 2) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_nblocks(cfs) != 2) ok = false; /* The journal must contain no DELETE records. */ for (off = CFS_JOURNAL_HEADER_SIZE; ok; off += sizeof(CfsJournalEntry)) { CfsJournalEntry je; ssize_t n; n = pread(cfs->jrn_fd, &je, sizeof(je), off); if (n != (ssize_t) sizeof(je)) break; if (cfs_journal_entry_validate(&je) != CFS_FORMAT_OK) break; if (je.op == CFS_JRN_OP_RESIZE) n_resizes++; else if (je.op == CFS_JRN_OP_DELETE) n_deletes++; } if (ok && (n_resizes < 1 || n_deletes != 0)) ok = false; /* Reopen: replay must restore nblocks=2 and invalidate dropped slots. */ cfs_close(cfs); cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (ok && cfs_map_nblocks(cfs) != 2) ok = false; if (ok && cfs->map[4].physical_offset != CFS_ENTRY_INVALID_OFFSET) ok = false; /* dropped slot must be invalid */ /* Re-extending must not resurrect the truncated block. */ if (ok && cfs_zero_extend(cfs, 2, 4) != CFS_STORAGE_OK) ok = false; if (ok && (cfs_read_page(cfs, 4, (char *) back) != CFS_STORAGE_OK || memcmp(back, zero, TEST_BLCKSZ) != 0)) ok = false; /* pre-truncate content resurrected */ cfs_close(cfs); snprintf(detail, sizeof(detail), "resizes=%d deletes=%d %s", n_resizes, n_deletes, ok ? "replay+reextend ok" : "failed"); add_result("storage_truncate_journal_resize_only", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * A failure inside cfs_reopen() must close every descriptor it has * opened so far and reset it to -1, so a later cfs_close() never closes a * recycled fd number. The handle itself stays owned by the caller. */ static void test_storage_reopen_closes_fds_on_error(void) { CfsStorageFixture fx; CfsRelation *cfs; MemoryContext oldcontext = CurrentMemoryContext; bool raised = false; bool ok = true; cfs_storage_setup(&fx, "reopen"); if (fx.dir == NULL) { add_result("storage_reopen_closes_fds_on_error", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); /* Drop the .cfsmap so the reopen fails after opening .cfp/.cfsjrn. */ if (unlink(fx.map_path) != 0) ok = false; PG_TRY(); { cfs_reopen(cfs); } PG_CATCH(); { MemoryContextSwitchTo(oldcontext); FlushErrorState(); raised = true; } PG_END_TRY(); if (!raised) ok = false; /* After the ERROR every descriptor must be reset to -1. */ if (ok && (cfs->cfp_fd != -1 || cfs->cfp_read_fd != -1 || cfs->map_fd != -1 || cfs->jrn_fd != -1)) ok = false; cfs_close(cfs); cfs_storage_teardown(&fx); add_result("storage_reopen_closes_fds_on_error", ok ? "ok" : "fail", raised ? "fds reset after reopen error" : "reopen error not raised"); } /* * cfs_unlink must also remove the artifacts of an interrupted * compaction swap (the .cfsswap commit marker plus the .new / .tmp * candidates of the map and of every .cfp segment), so a dropped relation * leaves a clean directory even after a failed compaction. */ static void test_storage_unlink_swap_artifacts(void) { RelFileLocatorBackend rl; CfsRelation *cfs; char *paths[8]; bool ok = true; int i; /* Use a high relNumber in the current database to avoid collisions. */ rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = 999089; rl.backend = INVALID_PROC_NUMBER; cfs_test_unlink_synthetic(rl); cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR | CFS_OPEN_CREATE); if (cfs == NULL) { add_result("storage_unlink_swap_artifacts", "fail", "open failed"); return; } /* Simulate the artifacts of an interrupted compaction swap. */ paths[0] = psprintf("%s%s", cfs->cfp_path, ".cfsswap"); paths[1] = psprintf("%s%s", cfs->cfp_path, ".new"); paths[2] = psprintf("%s.tmp", cfs->cfp_path); paths[3] = psprintf("%s%s", cfs->map_path, ".new"); paths[4] = psprintf("%s.tmp", cfs->map_path); paths[5] = pstrdup(cfs->cfp_path); paths[6] = pstrdup(cfs->map_path); paths[7] = pstrdup(cfs->jrn_path); for (i = 0; i < 5; i++) { const char junk = 'x'; if (!cfs_test_write_file(paths[i], &junk, 1)) ok = false; } cfs_close(cfs); cfs_test_unlink_synthetic(rl); /* Nothing of the sidecar trio or the swap artifacts may survive. */ for (i = 0; i < 8; i++) { struct stat st; if (ok && stat(paths[i], &st) == 0) ok = false; pfree(paths[i]); } add_result("storage_unlink_swap_artifacts", ok ? "ok" : "fail", ok ? "marker and .new/.tmp candidates removed" : "swap artifacts survived the drop"); } /* * Scan the journal of 'cfs' and report how many RESIZE records it holds plus * the nblocks value of the last one (0 when none). The single-block extend * path (cfs_write_page) must emit a RESIZE so that journal replay restores * nblocks deterministically, independent of the order UPDATE records are * applied. */ static void cfs_test_count_journal_resizes(CfsRelation *cfs, int *n_resizes, uint32 *last_nblocks) { off_t off; int count = 0; uint32 last = 0; for (off = CFS_JOURNAL_HEADER_SIZE;; off += sizeof(CfsJournalEntry)) { CfsJournalEntry je; ssize_t n; n = pread(cfs->jrn_fd, &je, sizeof(je), off); if (n != (ssize_t) sizeof(je)) break; if (cfs_journal_entry_validate(&je) != CFS_FORMAT_OK) break; if (je.op == CFS_JRN_OP_RESIZE) { count++; last = je.blocknum; } } *n_resizes = count; *last_nblocks = last; } /* * A pure map lookup must never change the logical size of the relation: * cfs_map_get_entry() may grow the internal array capacity, but nblocks is an * explicit operation performed only at genuine extend points. */ static void test_storage_lookup_no_implicit_growth(void) { CfsStorageFixture fx; CfsRelation *cfs; char detail[128]; bool ok = true; cfs_storage_setup(&fx, "lookup"); if (fx.dir == NULL) { add_result("storage_lookup_no_implicit_growth", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); /* A lookup beyond the current size must not grow nblocks. */ (void) cfs_map_get_entry(cfs, 10); if (cfs_map_nblocks(cfs) != 0) ok = false; snprintf(detail, sizeof(detail), "lookup nblocks=%u (expect 0)", cfs_map_nblocks(cfs)); add_result("storage_lookup_no_implicit_growth", ok ? "ok" : "fail", detail); cfs_close(cfs); cfs_storage_teardown(&fx); } /* * A single-block extend through cfs_write_page() (the path taken by, e.g., * index builds via cfs_smgr_extend) must journal an explicit RESIZE record, * exactly like cfs_zero_extend() does, so recovery restores nblocks without * depending on the order UPDATE records are replayed. */ static void test_storage_write_page_journals_resize(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); int n_resizes = 0; uint32 last_resize = 0; char detail[160]; bool ok = true; cfs_storage_setup(&fx, "wresize"); if (fx.dir == NULL) { add_result("storage_write_page_journals_resize", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x60); /* Extend by a single block at index 5 (nblocks 0 -> 6). */ if (cfs_write_page(cfs, 5, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_nblocks(cfs) != 6) ok = false; /* The journal must contain a RESIZE record to nblocks=6. */ cfs_test_count_journal_resizes(cfs, &n_resizes, &last_resize); if (ok && (n_resizes < 1 || last_resize != 6)) ok = false; snprintf(detail, sizeof(detail), "nblocks=%u resizes=%d last_resize=%u (expect nblocks=6, resize=6)", cfs_map_nblocks(cfs), n_resizes, last_resize); add_result("storage_write_page_journals_resize", ok ? "ok" : "fail", detail); cfs_close(cfs); cfs_storage_teardown(&fx); } /* * Compaction test using the relation-locator API. Updates one block many * times to accumulate dead records, compacts, and verifies the live data is * intact and the .cfp shrank. */ static void test_storage_compaction(void) { RelFileLocatorBackend rl; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsCompactOptions copts = CFS_COMPACT_OPTIONS_DEFAULT; CfsCompactResult cres; CfsRelation *cfs; uint64 old_cfp = 0; char detail[160]; bool ok = true; int i; /* Use a high relNumber in the current database to avoid collisions. */ rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = 999090; rl.backend = INVALID_PROC_NUMBER; cfs_test_unlink_synthetic(rl); cfs = cfs_create(rl, MAIN_FORKNUM); cfs_test_fill_page(page, 0x90); /* Repeatedly update block 0 to create many dead records. */ for (i = 0; i < 60; i++) { page[0] = (unsigned char) i; if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) { ok = false; break; } } old_cfp = cfs->cfp_write_off; cfs_close(cfs); if (ok && cfs_compact_relation(rl, MAIN_FORKNUM, &copts, &cres, InvalidOid) != CFS_STORAGE_OK) ok = false; if (ok) { cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR); if (cfs == NULL) ok = false; else { if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; if (cfs->cfp_write_off >= (off_t) old_cfp) ok = false; /* compaction must shrink .cfp */ cfs_close(cfs); } } cfs_test_unlink_synthetic(rl); snprintf(detail, sizeof(detail), "cfp %llu -> %llu bytes, live=%llu", (unsigned long long) old_cfp, (unsigned long long) cres.new_cfp_size, (unsigned long long) cres.live_blocks); add_result("storage_compaction", ok ? "ok" : "fail", detail); } /* * The dead-space accounting must not count the .cfp segments' rollover * padding as dead bytes: a record never crosses a segment boundary, so a * closed segment simply ends short of CFS_SEGMENT_SIZE, and that unwritten * tail is neither live data nor reclaimable by compaction. The chain is * crafted directly as sparse files (the sizes matter, the content does * not): seg0 short by exactly PAD bytes, seg1 the small, still-growing * tail. */ static void test_storage_chain_padding(void) { CfsStorageFixture fx; uint64 total = 0; uint64 padding = ~(uint64) 0; const uint64 pad = 4096; uint64 pad_exact = ~(uint64) 0; uint64 pad_short = ~(uint64) 0; char detail[160]; bool ok = true; int fd; cfs_storage_setup(&fx, "chainpad"); if (fx.dir == NULL) { add_result("storage_chain_padding", "fail", "setup failed"); return; } /* Case 1: seg0 closed PAD bytes short, seg1 the growing tail. */ fd = BasicOpenFile(fx.cfp_path, O_CREAT | O_RDWR | PG_BINARY); if (fd < 0 || ftruncate(fd, (off_t) CFS_SEGMENT_SIZE - (off_t) pad) != 0) ok = false; if (fd >= 0) close(fd); { char *seg1 = psprintf("%s.1", fx.cfp_path); fd = BasicOpenFile(seg1, O_CREAT | O_RDWR | PG_BINARY); if (fd < 0 || ftruncate(fd, 8192) != 0) ok = false; if (fd >= 0) close(fd); pfree(seg1); } if (ok && (!cfs_cfp_chain_stat(fx.cfp_path, &total, &padding) || total != (uint64) CFS_SEGMENT_SIZE + 8192 || padding != pad)) { snprintf(detail, sizeof(detail), "two segments: total=%llu padding=%llu (want %llu/%llu)", (unsigned long long) total, (unsigned long long) padding, (unsigned long long) ((uint64) CFS_SEGMENT_SIZE + 8192), (unsigned long long) pad); add_result("storage_chain_padding", "fail", detail); cfs_storage_teardown(&fx); return; } /* * Case 2: a single segment filled EXACTLY to the boundary - the lazy * rollover state (the next segment appears on the next append). Its tail * must not be padding: an underflow here used to wrap the unsigned * arithmetic and report a huge value. */ fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY); if (fd < 0 || ftruncate(fd, (off_t) CFS_SEGMENT_SIZE) != 0) ok = false; if (fd >= 0) close(fd); { char *seg1 = psprintf("%s.1", fx.cfp_path); unlink(seg1); pfree(seg1); } if (ok && (!cfs_cfp_chain_stat(fx.cfp_path, &total, &padding) || total != (uint64) CFS_SEGMENT_SIZE || padding != 0)) ok = false; pad_exact = padding; /* Case 3: a single short segment has no closed segment at all. */ if (ok) { fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY); if (fd < 0 || ftruncate(fd, (off_t) CFS_SEGMENT_SIZE - 8192) != 0) ok = false; if (fd >= 0) close(fd); if (!cfs_cfp_chain_stat(fx.cfp_path, &total, &padding) || total != (uint64) CFS_SEGMENT_SIZE - 8192 || padding != 0) ok = false; pad_short = padding; } snprintf(detail, sizeof(detail), "exact-full pad=%llu, short-single pad=%llu", (unsigned long long) pad_exact, (unsigned long long) pad_short); add_result("storage_chain_padding", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Journal ABA hardening: a backend whose delta-replay cursor points into a * journal that was reset (checkpoint truncate / compaction swap) and then * grew back past the old cursor must not replay from the stale offset - * records sitting between the header and the cursor belong to the new * journal incarnation and would be silently skipped. The refresh must * detect the incarnation change and do a full reload instead. * * Layout (journal records are 48 bytes, header 24): * - h1 writes blocks 0..2 -> journal size 168, replay cursor synced=168 * - journal reset -> size 24 (incarnation bumped, when supported) * - h2 appends 5 records -> size 264 > 168: the ABA state * A size-only check replays from offset 168 of the NEW journal, skipping * the RESIZE and the block-0/block-3 updates. */ static void test_storage_journal_incarnation(void) { CfsStorageFixture fx; CfsRelation *h1; CfsRelation *h2; unsigned char page0_v1[TEST_BLCKSZ]; unsigned char page0_v2[TEST_BLCKSZ]; unsigned char page3[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; bool ok = true; cfs_storage_setup(&fx, "jrninc"); if (fx.dir == NULL) { add_result("storage_journal_incarnation", "fail", "setup failed"); return; } h1 = cfs_storage_open_new(&fx); /* Baseline: three writes, a snapshot, and a synced replay cursor. */ cfs_test_fill_page(page0_v1, 0x41); if (cfs_write_page(h1, 0, (const char *) page0_v1, &opts) != CFS_STORAGE_OK || cfs_write_page(h1, 1, (const char *) page0_v1, &opts) != CFS_STORAGE_OK || cfs_write_page(h1, 2, (const char *) page0_v1, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(h1) != CFS_STORAGE_OK) ok = false; if (ok && cfs_refresh_map(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ok = false; /* Another actor resets the journal (checkpoint / compaction swap). */ if (ok) cfs_journal_reset_file(fx.jrn_path, 0); /* The journal regrows past the old cursor: the ABA window. */ cfs_test_fill_page(page0_v2, 0x42); cfs_test_fill_page(page3, 0x43); h2 = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_zero_extend(h2, 3, 3) != CFS_STORAGE_OK || cfs_write_page(h2, 0, (const char *) page0_v2, &opts) != CFS_STORAGE_OK || cfs_write_page(h2, 3, (const char *) page3, &opts) != CFS_STORAGE_OK || cfs_write_page(h2, 4, (const char *) page3, &opts) != CFS_STORAGE_OK || cfs_write_page(h2, 5, (const char *) page3, &opts) != CFS_STORAGE_OK) ok = false; /* The stale handle must notice the reset, not replay from offset 168. */ if (ok && cfs_refresh_map(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ok = false; if (ok && (cfs_read_page(h1, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page0_v2, back, TEST_BLCKSZ) != 0)) ok = false; /* block 0 update was skipped */ if (ok && (cfs_read_page(h1, 3, (char *) back) != CFS_STORAGE_OK || memcmp(page3, back, TEST_BLCKSZ) != 0)) ok = false; /* block 3 update was skipped */ if (ok && cfs_map_nblocks(h1) != 6) ok = false; /* RESIZE record was skipped */ cfs_close(h2); cfs_close(h1); snprintf(detail, sizeof(detail), "truncate+regrow replay %s", ok ? "reloaded" : "started at stale offset"); add_result("storage_journal_incarnation", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Snapshot reload must not resurrect pre-truncate data. * * A stale handle whose in-memory map array still covers the pre-truncate * size reloads the map after another actor truncated the relation and * checkpointed (snapshot with the smaller nblocks + journal reset). The * reload reads only nblocks entries, so the array slots beyond nblocks keep * the pre-truncate entries unless the load re-initialises them. Extending * the relation back over those slots must yield zero pages, never the data * that lived there before the truncate. */ static void test_storage_snapshot_tail_invalidated(void) { CfsStorageFixture fx; CfsRelation *h1; CfsRelation *h2; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; unsigned char zero[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; int i; bool ok = true; cfs_storage_setup(&fx, "snaptail"); if (fx.dir == NULL) { add_result("storage_snapshot_tail_invalidated", "fail", "setup failed"); return; } h1 = cfs_storage_open_new(&fx); MemSet(zero, 0, TEST_BLCKSZ); cfs_test_fill_page(page, 0x60); /* h1: 200 written blocks, a snapshot, and a synced replay cursor. */ for (i = 0; i < 200; i++) { if (cfs_write_page(h1, i, (const char *) page, &opts) != CFS_STORAGE_OK) { ok = false; break; } } if (ok && cfs_map_save_snapshot(h1) != CFS_STORAGE_OK) ok = false; if (ok && cfs_refresh_map(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ok = false; /* Another actor truncates to 50 blocks and checkpoints. */ h2 = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (ok && cfs_truncate(h2, 50) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(h2) != CFS_STORAGE_OK) ok = false; if (ok) test_journal_reset(h2, ERROR); /* * Reload the map in h1's handle without recreating the array: only 50 * entries come from the snapshot, while the array still covers the * pre-truncate size. The snapshot save swapped the .cfsmap inode (atomic * rename), so repoint h1's descriptor at the current file first, exactly * as the non-swap full-reload branch of cfs_refresh_map() would see it. * (cfs_refresh_map() itself is not used here: the inode swap would steer * it into cfs_reopen(), which drops the whole array and cannot exhibit * the defect.) */ if (ok) { close(h1->map_fd); h1->map_fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY); if (h1->map_fd < 0 || cfs_map_load(h1, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ok = false; } if (ok && cfs_map_nblocks(h1) != 50) ok = false; /* Extending back to 200 must surface zero pages, not pre-truncate data. */ if (ok && cfs_zero_extend(h1, 50, 150) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_nblocks(h1) != 200) ok = false; if (ok && (cfs_read_page(h1, 100, (char *) back) != CFS_STORAGE_OK || memcmp(back, zero, TEST_BLCKSZ) != 0)) ok = false; /* pre-truncate content resurrected */ cfs_close(h2); cfs_close(h1); snprintf(detail, sizeof(detail), "truncate+reload+extend block 100 %s", ok ? "reads zero page" : "resurrected pre-truncate data"); add_result("storage_snapshot_tail_invalidated", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * A snapshot must record the real .cfp end-of-file, not the handle's * possibly stale append cursor. A handle that has not appended since another * backend wrote more records would otherwise persist a cfp_size smaller than * the actual data chain. */ static void test_storage_snapshot_cfp_size_from_eof(void) { CfsStorageFixture fx; CfsRelation *h1; CfsRelation *h2; unsigned char page[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); struct stat st; uint64 reported = 0; uint64 real_eof = 0; char detail[160]; int i; bool ok = true; cfs_storage_setup(&fx, "cfpsize"); if (fx.dir == NULL) { add_result("storage_snapshot_cfp_size_from_eof", "fail", "setup failed"); return; } h1 = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x70); /* h1 writes one block; its append cursor stops there. */ if (cfs_write_page(h1, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; /* * A second handle appends more blocks, advancing the real .cfp EOF past * h1's cursor. h1 never learns about these appends (its local cursor is * not refreshed), which is exactly the stale-cursor case. */ h2 = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); for (i = 1; i <= 3 && ok; i++) { if (cfs_write_page(h2, i, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; } /* h1's snapshot must record the real .cfp EOF, not its stale cursor. */ if (ok && cfs_map_save_snapshot(h1) != CFS_STORAGE_OK) ok = false; reported = h1->map_hdr.cfp_size; if (ok && stat(fx.cfp_path, &st) != 0) ok = false; real_eof = (uint64) st.st_size; if (ok && reported != real_eof) ok = false; cfs_close(h2); cfs_close(h1); snprintf(detail, sizeof(detail), "cfp_size=%llu eof=%llu %s", (unsigned long long) reported, (unsigned long long) real_eof, ok ? "match" : "mismatch"); add_result("storage_snapshot_cfp_size_from_eof", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Torn-record visibility on the delta-replay read path. * * A reader refreshing its local map stops the journal delta replay at the * first invalid (torn) record. This is the correct crash-recovery * semantics, but it is also exactly the mechanism that turns a record seen * *during* a concurrent append into a silent stale read: the reader settles * on the previous version and never sees the committed update, with no * error. The read-path append-lock coordination (cfs_read_page_cached) * ensures a reader never observes such a torn record in the first place. * * This test pins the underlying invariant that coordination relies on: a * torn trailing record yields the last *valid* version, and completing the * record makes the latest committed version visible on the next refresh. */ static void test_storage_torn_record_visibility(void) { CfsStorageFixture fx; CfsRelation *h_w; /* writer */ CfsRelation *h_r; /* reader */ unsigned char pageA[TEST_BLCKSZ]; unsigned char pageB[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[160]; bool ok = true; CfsMapEntry entryB; off_t last_rec_off = 0; cfs_storage_setup(&fx, "tornrec"); if (fx.dir == NULL) { add_result("storage_torn_record_visibility", "fail", "setup failed"); return; } h_w = cfs_storage_open_new(&fx); /* Version A fully committed. */ cfs_test_fill_page(pageA, 0x50); if (cfs_write_page(h_w, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK) ok = false; /* Reader opens after A and syncs its replay cursor to the end. */ h_r = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (ok && cfs_refresh_map(h_r, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ok = false; if (ok && (cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_OK || memcmp(pageA, back, TEST_BLCKSZ) != 0)) ok = false; /* Version B fully committed through the writer. */ cfs_test_fill_page(pageB, 0x60); if (ok && cfs_write_page(h_w, 0, (const char *) pageB, &opts) != CFS_STORAGE_OK) ok = false; if (ok) entryB = *cfs_map_get_entry(h_w, 0); /* capture B's entry */ /* * Tear B's journal record (the last one) by overwriting its lead bytes * with garbage, so CRC/magic validation fails — exactly like a reader * catching the 56-byte record mid-pwrite. The offset of the last record * is derived from the journal file size. */ if (ok) { int jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); struct stat st; if (jrn_fd >= 0 && fstat(jrn_fd, &st) == 0) { uint32 garbage = 0xDEADBEEF; last_rec_off = st.st_size - (off_t) CFS_JOURNAL_ENTRY_SIZE; if (pwrite(jrn_fd, &garbage, sizeof(garbage), last_rec_off) != (ssize_t) sizeof(garbage)) ok = false; } else ok = false; if (jrn_fd >= 0) close(jrn_fd); } /* Reader refreshes: replay applies A and stops at the torn B record. */ if (ok && cfs_refresh_map(h_r, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ok = false; if (ok && (cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_OK || memcmp(pageA, back, TEST_BLCKSZ) != 0)) ok = false; /* must see the last *valid* version A */ /* * Complete B's record (as if the writer finished the pwrite): rewrite the * valid entry at the same offset. */ if (ok) { int jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); CfsJournalEntry validB; cfs_journal_entry_init_update(&validB, 0, &entryB); if (jrn_fd >= 0) { if (pwrite(jrn_fd, &validB, sizeof(validB), last_rec_off) != (ssize_t) sizeof(validB)) ok = false; close(jrn_fd); } else ok = false; } /* Reader refreshes again: now B is the latest committed version. */ if (ok && cfs_refresh_map(h_r, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ok = false; if (ok && (cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_OK || memcmp(pageB, back, TEST_BLCKSZ) != 0)) ok = false; /* completed record must be visible */ cfs_close(h_r); cfs_close(h_w); snprintf(detail, sizeof(detail), "torn->valid refresh %s", ok ? "ok" : "stale/missing version"); add_result("storage_torn_record_visibility", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Torn tail must be physically truncated on open/replay. * * A crash mid-append leaves a garbage (torn) tail in .cfsjrn after the last * valid record. Replay correctly stops at it, but unless the file is * physically truncated to the end of that last valid record, the append * cursor — derived from the raw file size — lands past the garbage, and the * next backend appends behind it. Every later replay still stops on the * garbage, so those records are buried forever even though they are * physically present. * * This test assembles a journal with a valid prefix followed by a torn last * record, then reopens (full replay). It verifies: * (a) only the valid-prefix records are applied, * (b) the journal file is physically truncated to the valid prefix, * (c) the append cursor points at the end of the valid prefix, * (d) a new record appended after reopen is visible on the next replay. * * The torn record with valid records behind it is not a tail but corruption; * test_storage_mid_journal_preserved covers that case. */ static void test_storage_torn_tail_truncated(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pageA[TEST_BLCKSZ]; unsigned char pageB[TEST_BLCKSZ]; unsigned char pageC[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[256]; bool ok = true; off_t valid_prefix; /* end of the last valid record */ struct stat st; cfs_storage_setup(&fx, "torntail"); if (fx.dir == NULL) { add_result("storage_torn_tail_truncated", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); /* Two blocks: 4 journal records (RESIZE+UPDATE each). */ cfs_test_fill_page(pageA, 0x50); cfs_test_fill_page(pageB, 0x60); if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK || cfs_write_page(cfs, 1, (const char *) pageB, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(cfs); if (!ok) { snprintf(detail, sizeof(detail), "write setup failed"); add_result("storage_torn_tail_truncated", "fail", detail); cfs_storage_teardown(&fx); return; } /* * Build the defect scenario by hand: a torn last record, with nothing * behind it - the crash artifact of an interrupted append. */ valid_prefix = (off_t) CFS_JOURNAL_HEADER_SIZE + 4 * CFS_JOURNAL_ENTRY_SIZE; { int jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); char garbage[CFS_JOURNAL_ENTRY_SIZE]; if (jrn_fd < 0) ok = false; /* Torn tail: a full entry of zero bytes (bad CRC/magic). */ if (ok) { MemSet(garbage, 0, sizeof(garbage)); if (pwrite(jrn_fd, garbage, sizeof(garbage), valid_prefix) != (ssize_t) sizeof(garbage)) ok = false; } if (jrn_fd >= 0) close(jrn_fd); } if (!ok) { snprintf(detail, sizeof(detail), "journal tampering failed"); add_result("storage_torn_tail_truncated", "fail", detail); cfs_storage_teardown(&fx); return; } /* * Reopen simulating the single-writer recovery scan: replay must stop at * the torn tail and, because CFS_OPEN_REPAIR_TAIL is set, truncate it. * (The normal lock-free open deliberately does not repair, since a * concurrent writer may be mid-append.) */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_REPAIR_TAIL); /* (a) only the valid-prefix records are applied. */ if (cfs_map_nblocks(cfs) != 2) ok = false; /* (b) the journal file is physically truncated to the valid prefix. */ if (stat(fx.jrn_path, &st) != 0 || st.st_size != valid_prefix) ok = false; /* (c) the append cursor points at the end of the valid prefix. */ if (cfs->jrn_write_off != valid_prefix) ok = false; /* The valid-prefix data is still readable. */ if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(pageA, back, TEST_BLCKSZ) != 0 || cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK || memcmp(pageB, back, TEST_BLCKSZ) != 0) ok = false; /* * (d) A new record appended now must land right after the valid prefix * (not behind the old garbage) and survive a close/reopen replay. */ cfs_test_fill_page(pageC, 0x70); if (cfs_write_page(cfs, 2, (const char *) pageC, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(cfs); cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs_map_nblocks(cfs) != 3) ok = false; if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK || memcmp(pageC, back, TEST_BLCKSZ) != 0)) ok = false; cfs_close(cfs); snprintf(detail, sizeof(detail), "torn-tail truncation %s (nblocks=%u)", ok ? "ok" : "failed", ok ? 3u : 0u); add_result("storage_torn_tail_truncated", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Mid-journal corruption must survive the recovery open. * * A torn record with valid records behind it cannot come from a legal append * (appends only ever happen at EOF): it is corruption, and the records behind * it are the only durable trace of their changes. The recovery open still * applies the valid prefix, but must leave the journal file untouched and * mark the handle unhealed instead of cutting the valid tail off. */ static void test_storage_mid_journal_preserved(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pageA[TEST_BLCKSZ]; unsigned char pageB[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[256]; bool ok = true; off_t torn_off; off_t jrn_size; struct stat st; cfs_storage_setup(&fx, "midjrn"); if (fx.dir == NULL) { add_result("storage_mid_journal_preserved", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); /* Two blocks: 4 journal records (RESIZE+UPDATE each). */ cfs_test_fill_page(pageA, 0x80); cfs_test_fill_page(pageB, 0x90); if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK || cfs_write_page(cfs, 1, (const char *) pageB, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(cfs); torn_off = (off_t) CFS_JOURNAL_HEADER_SIZE + 4 * CFS_JOURNAL_ENTRY_SIZE; jrn_size = torn_off + 3 * (off_t) CFS_JOURNAL_ENTRY_SIZE; { int jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); char garbage[CFS_JOURNAL_ENTRY_SIZE]; CfsJournalEntry buried; if (jrn_fd < 0) ok = false; /* Torn record in the middle: a full entry of zero bytes. */ if (ok) { MemSet(garbage, 0, sizeof(garbage)); if (pwrite(jrn_fd, garbage, sizeof(garbage), torn_off) != (ssize_t) sizeof(garbage)) ok = false; } /* Valid records behind it: the durable tail that must survive. */ if (ok) { off_t off = torn_off + (off_t) CFS_JOURNAL_ENTRY_SIZE; cfs_journal_entry_init_resize(&buried, 3); if (pwrite(jrn_fd, &buried, sizeof(buried), off) != (ssize_t) sizeof(buried)) ok = false; off += (off_t) CFS_JOURNAL_ENTRY_SIZE; cfs_journal_entry_init_resize(&buried, 4); if (pwrite(jrn_fd, &buried, sizeof(buried), off) != (ssize_t) sizeof(buried)) ok = false; } if (jrn_fd >= 0) close(jrn_fd); } if (!ok) { snprintf(detail, sizeof(detail), "journal tampering failed"); add_result("storage_mid_journal_preserved", "fail", detail); cfs_storage_teardown(&fx); return; } /* * Reopen simulating the single-writer recovery scan: the valid prefix is * applied, but the journal is corruption, not a torn tail, so it is not * truncated and the handle is marked unhealed. */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_REPAIR_TAIL); if (cfs_map_nblocks(cfs) != 2) ok = false; if (stat(fx.jrn_path, &st) != 0 || st.st_size != jrn_size) ok = false; if (!cfs->unhealed_corruption) ok = false; cfs_close(cfs); snprintf(detail, sizeof(detail), "journal preserved %s (size=%lld)", ok ? "ok" : "failed", (long long) jrn_size); add_result("storage_mid_journal_preserved", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * The phase-2 tail re-check: phase 1 classifies a torn tail, then a writer * may complete it or append past it before phase 2 takes the append lock. * * The predicate is tested directly: with the journal still ending at the * torn record it reports no change; one byte appended behind that record * makes it report a change, so the checkpoint must not reset the journal. */ static void test_storage_tail_change_detected(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pageA[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[256]; bool ok = true; off_t torn_off; cfs_storage_setup(&fx, "tailchg"); if (fx.dir == NULL) { add_result("storage_tail_change_detected", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(pageA, 0xD0); if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(cfs); cfs = NULL; torn_off = (off_t) CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE; { int jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); char garbage[CFS_JOURNAL_ENTRY_SIZE]; if (jrn_fd < 0) ok = false; if (ok) { MemSet(garbage, 0, sizeof(garbage)); if (pwrite(jrn_fd, garbage, sizeof(garbage), torn_off) != (ssize_t) sizeof(garbage)) ok = false; } if (jrn_fd >= 0) close(jrn_fd); } if (ok) { cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs == NULL) ok = false; } if (ok && cfs_journal_tail_changed(cfs, torn_off)) ok = false; /* still the torn tail phase 1 saw */ /* A writer appends behind the torn record while phase 1 is parked. */ if (ok) { int jrn_fd = BasicOpenFile(fx.jrn_path, O_WRONLY | PG_BINARY); if (jrn_fd < 0) ok = false; else { if (pwrite(jrn_fd, "xx", 2, torn_off + CFS_JOURNAL_ENTRY_SIZE) != 2) ok = false; close(jrn_fd); } } if (ok && !cfs_journal_tail_changed(cfs, torn_off)) ok = false; if (cfs != NULL) cfs_close(cfs); snprintf(detail, sizeof(detail), "tail change %s", ok ? "detected" : "not detected"); add_result("storage_tail_change_detected", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * A delta refresh over mid-journal corruption must rebuild the map instead of * serving the partially synced one. * * The baseline handle synced its map when the journal ended after block 0. * A second handle then appends records for blocks 1 and 2, and the first * appended record is corrupted with valid records still behind it. The * delta replay cannot trust anything past the corruption, so it must signal * a full reload (-2); the full replay then reports the corruption and marks * the handle unhealed. Without that, the refresh returned success with a * map that silently missed every later record until a full reopen. */ static void test_storage_delta_mid_journal_reload(void) { CfsStorageFixture fx; CfsRelation *baseline = NULL; CfsRelation *writer; unsigned char pageA[TEST_BLCKSZ]; unsigned char pageB[TEST_BLCKSZ]; unsigned char pageC[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[256]; bool ok = true; off_t first_new; int rc; cfs_storage_setup(&fx, "deltamid"); if (fx.dir == NULL) { add_result("storage_delta_mid_journal_reload", "fail", "setup failed"); return; } /* Block 0: two records (RESIZE + UPDATE), the baseline journal. */ writer = cfs_storage_open_new(&fx); cfs_test_fill_page(pageA, 0xA0); if (cfs_write_page(writer, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(writer); first_new = (off_t) CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE; if (ok) { /* This handle syncs its map at the two-record journal. */ baseline = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (baseline == NULL) ok = false; } if (ok) { /* Four more records behind the baseline, two per block. */ writer = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); cfs_test_fill_page(pageB, 0xB0); cfs_test_fill_page(pageC, 0xC0); if (writer == NULL || cfs_write_page(writer, 1, (const char *) pageB, &opts) != CFS_STORAGE_OK || cfs_write_page(writer, 2, (const char *) pageC, &opts) != CFS_STORAGE_OK) ok = false; if (writer != NULL) cfs_close(writer); } /* Corrupt the first appended record; three valid records follow it. */ if (ok) { int jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); unsigned char b; if (jrn_fd < 0) ok = false; if (ok && pread(jrn_fd, &b, 1, first_new + 8) != 1) ok = false; if (ok) { b ^= 0xFF; if (pwrite(jrn_fd, &b, 1, first_new + 8) != 1) ok = false; } if (jrn_fd >= 0) close(jrn_fd); } if (ok) { rc = cfs_refresh_map(baseline, false, CFS_LOAD_NORMAL); if (rc != CFS_STORAGE_OK || !baseline->unhealed_corruption) ok = false; /* * The delta baseline must not advance past the corruption: a full * reload leaves map_synced_jrn_off alone, while the old swallow * advanced it to the journal end and then kept serving the map. */ if (baseline->map_synced_jrn_off != first_new) ok = false; } if (baseline != NULL) cfs_close(baseline); snprintf(detail, sizeof(detail), "mid-journal delta %s (unhealed=%d)", ok ? "reloaded" : "failed", ok ? 1 : 0); add_result("storage_delta_mid_journal_reload", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Crash recovery with .cfp/.cfsjrn writeback reordering. * * Between checkpoints neither .cfp nor .cfsjrn is fsync'd, so after a power * loss a journal UPDATE record can be durable while the .cfp bytes it points * at are not (the kernel flushed the journal pages ahead of the data pages). * Replay must not trust such a record blindly: the record's own CRC is * valid, but there is no genuine CfsCompressedBlockHeader at the referenced * offset. The correct handling is to skip that one record - leaving the * map entry for the block in its previous, durable state - and to keep * replaying the records that follow it (unlike a torn trailing record, * which stops the replay). Ordinary WAL redo then re-applies the lost * change on top of the old page version, exactly as it does for * uncompressed relations. */ static void test_storage_journal_skip_missing_data(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pageA[TEST_BLCKSZ]; unsigned char pageB[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char detail[128]; bool ok = true; uint64 bogus_off; size_t i; cfs_storage_setup(&fx, "jrnskip"); if (fx.dir == NULL) { add_result("storage_journal_skip_missing_data", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); /* A genuine write of block 0 (RESIZE + UPDATE journal records). */ cfs_test_fill_page(pageA, 0x70); if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK) ok = false; /* * Simulate the crash window by hand: put garbage into .cfp at an aligned * offset past the written data (no genuine record header there), then * append a journal UPDATE record for block 1 that points at it. The * record's own CRC is valid - only the referenced data is missing, * exactly what replay sees when .cfsjrn became durable ahead of the * referenced .cfp bytes. */ if (ok) { CfsMapEntry bogus; CfsJournalEntry je; unsigned char garbage[CFS_BLOCK_ALIGN]; int cfp_fd; int jrn_fd; bogus_off = CFS_ALIGN_UP((uint64) cfs->cfp_write_off) + CFS_BLOCK_ALIGN; memset(garbage, 0xA5, sizeof(garbage)); cfp_fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY); if (cfp_fd < 0 || pwrite(cfp_fd, garbage, sizeof(garbage), (off_t) bogus_off) != (ssize_t) sizeof(garbage)) ok = false; if (cfp_fd >= 0) close(cfp_fd); cfs_map_entry_init(&bogus); bogus.physical_offset = bogus_off; bogus.compressed_size = 64; bogus.generation = 1; cfs_map_entry_crc_set(&bogus); cfs_journal_entry_init_update(&je, 1, &bogus); jrn_fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); if (jrn_fd < 0 || pwrite(jrn_fd, &je, sizeof(je), cfs->jrn_write_off) != (ssize_t) sizeof(je)) ok = false; if (jrn_fd >= 0) close(jrn_fd); } /* * A genuine write of block 2 *after* the bogus record: proves that replay * continues past the skipped record instead of stopping at it. */ cfs_test_fill_page(pageB, 0x71); if (ok && cfs_write_page(cfs, 2, (const char *) pageB, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(cfs); /* Reopen without a checkpoint: the journal drives the whole map. */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs == NULL) ok = false; if (ok && cfs_map_nblocks(cfs) != 3) ok = false; /* Blocks 0 and 2 come from genuine records and must read back. */ if (ok && (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(pageA, back, TEST_BLCKSZ) != 0)) ok = false; if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK || memcmp(pageB, back, TEST_BLCKSZ) != 0)) ok = false; /* * The bogus record must NOT have been applied: block 1 keeps the * never-written state (invalid map offset, reads back as a zero page) * instead of pointing at bytes that never reached the disk. */ if (ok && cfs_map_get_entry(cfs, 1)->physical_offset != CFS_ENTRY_INVALID_OFFSET) ok = false; if (ok) { MemSet(back, 0xFF, TEST_BLCKSZ); if (cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK) ok = false; else for (i = 0; i < TEST_BLCKSZ; i++) if (back[i] != 0) { ok = false; break; } } if (cfs != NULL) cfs_close(cfs); snprintf(detail, sizeof(detail), "bogus UPDATE skipped, replay continued %s", ok ? "ok" : "FAILED"); add_result("storage_journal_skip_missing_data", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * test_storage_read_padding_garbage * The write path zeroes the record's alignment padding so that records * are canonical (see test_record_padding_zeroed). The read path * enforces the same canonicality contract: CfsDecompressPage() rejects * a record whose payload padding is not zero as corruption, so bit rot * confined to the padding bytes cannot slip through as data. The * independent .cfp fsck walk does not check the padding of individual * records (it validates record boundaries and CRC-covered regions * only), so the fsck verdict for the same damage stays clean — the * read path is the authority here. * * The test writes one compressed block, flips the record's padding bytes * in .cfp directly, and reopens: the read must fail with corruption, and * fsck must stay clean (pinning both sides of the asymmetry). */ static void test_storage_read_padding_garbage(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pageA[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsFsckResult res; CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT; char detail[160]; bool ok = true; CfsMapEntry *e; uint32 compressed_size; size_t pad_off; size_t pad_len; struct stat st; unsigned char *buf; int fd; ssize_t nread; cfs_storage_setup(&fx, "padg"); if (fx.dir == NULL) { add_result("storage_read_padding_garbage", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); /* A compressible page yields a genuinely compressed record. */ cfs_test_fill_page(pageA, 0x52); if (cfs_write_page(cfs, 0, (const char *) pageA, &opts) != CFS_STORAGE_OK) ok = false; /* * Locate the record's padding: [header (40B)][payload][pad to 8]. If the * compressed payload happens to be aligned there is no padding to * corrupt; report the case honestly instead of pretending coverage. */ if (ok) { e = cfs_map_get_entry(cfs, 0); compressed_size = e->compressed_size; pad_len = CFS_RECORD_SIZE(compressed_size) - CFS_BLOCK_HEADER_SIZE - compressed_size; } cfs_close(cfs); if (!ok) { add_result("storage_read_padding_garbage", "fail", "write failed"); cfs_storage_teardown(&fx); return; } if (pad_len == 0) { add_result("storage_read_padding_garbage", "skip", "compressed payload is 8-byte aligned, no padding"); cfs_storage_teardown(&fx); return; } /* Flip the padding bytes in .cfp (the CRC-covered payload is intact). */ if (stat(fx.cfp_path, &st) != 0) { add_result("storage_read_padding_garbage", "fail", "stat failed"); cfs_storage_teardown(&fx); return; } buf = palloc(st.st_size); fd = BasicOpenFile(fx.cfp_path, O_RDONLY | PG_BINARY); if (fd < 0 || (nread = read(fd, buf, st.st_size)) != st.st_size) ok = false; if (fd >= 0) close(fd); pad_off = CFS_CFP_BASE_OFFSET + CFS_BLOCK_HEADER_SIZE + compressed_size; if (ok) { memset(buf + pad_off, 0xAB, pad_len); ok = cfs_test_write_file(fx.cfp_path, buf, st.st_size); } pfree(buf); /* * The reader must refuse the record: the nonzero padding is corruption by * the canonicality contract, not dead space. */ if (ok) { CfsRelation *h_r = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); unsigned char back[TEST_BLCKSZ]; if (h_r == NULL || cfs_read_page(h_r, 0, (char *) back) != CFS_STORAGE_CORRUPT) ok = false; if (h_r != NULL) cfs_close(h_r); } /* * The fsck walk stays clean: it does not validate the padding of * individual records (boundaries and CRC-covered regions only). */ if (ok) { cfs_fsck_result_init(&res); cfs_fsck_cfp_file(fx.cfp_path, &fopts, &res); if (res.errors != 0 || res.torn_tails != 0) ok = false; } snprintf(detail, sizeof(detail), "read %s, fsck %s (asymmetry pinned)", ok ? "refuses garbage padding" : "ACCEPTED garbage padding", ok ? "clean" : "flagged"); add_result("storage_read_padding_garbage", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * D1 shared-tail protocol: with the relation's metadata slot pinned, the * append path takes its offset from the slot's authoritative cfp_tail and * publishes the new end back, instead of re-walking the segment chain on * every record. The exercise drives every state of the protocol: * * - a fresh slot is DIRTY, so the first append discovers the chain end; * - after a successful append the tail is IDLE and equals the published * cursor, and the next record lands exactly at that offset; * - an IN_PROGRESS slot (a writer crashed between its pwrite and the * tail publication) forces the next writer back onto the discover * path without overwriting the orphaned record's successor; * - a failed pwrite marks the slot DIRTY and the next append re-discovers; * - every page written under the protocol reads back intact. */ static void test_storage_shared_tail_protocol(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); uint64 tail = 0; CfsMapEntry *e0, *e1, *e2; off_t off1 = 0, off2 = 0; int rc; int stage = 0; char detail[160]; bool ok = true; cfs_storage_setup(&fx, "sharedtail"); if (fx.dir == NULL) { add_result("storage_shared_tail_protocol", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800770; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); cfs = cfs_storage_open_new(&fx); if (cfs == NULL) { add_result("storage_shared_tail_protocol", "fail", "open failed"); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_storage_teardown(&fx); return; } /* RAW pages: fixed 8224-byte records make the offsets predictable. */ opts.algorithm = CFS_ALGORITHM_RAW; opts.explicit_algorithm = true; opts.allow_raw_fallback = true; opts.min_gain_bytes = 1; /* * A freshly claimed slot is DIRTY: no trustworthy tail exists yet, so * this append must run the discover path and then publish the tail. */ stage = 1; cfs_test_fill_page(page, 0x61); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; stage = 2; if (ok && !cfs_cfp_tail_fetch(fx.rl, MAIN_FORKNUM, &tail)) ok = false; stage = 3; e0 = ok ? cfs_map_get_entry(cfs, 0) : NULL; if (ok && (e0 == NULL || e0->physical_offset != CFS_CFP_BASE_OFFSET)) ok = false; /* * IDLE tail: the next record must land exactly at the published tail * (no discover walk, no gap, no overwrite of the first record). */ stage = 4; if (ok) { cfs_test_fill_page(page, 0x62); if (cfs_write_page(cfs, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; } stage = 5; e1 = ok ? cfs_map_get_entry(cfs, 1) : NULL; if (ok && e1 == NULL) ok = false; if (ok) { /* * Capture the offsets while the handle (and its map array) is * still open: the print at the end must not read freed memory. */ off1 = (off_t) e1->physical_offset; /* * Crash-window simulation: mark the slot IN_PROGRESS as a writer * that died between its pwrite and the tail publication would * leave it. The next append must refuse to trust the tail and * re-discover the chain end instead. */ stage = 6; cfs_cfp_tail_begin(fx.rl, MAIN_FORKNUM); cfs_test_fill_page(page, 0x63); if (cfs_write_page(cfs, 2, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; } stage = 7; e2 = ok ? cfs_map_get_entry(cfs, 2) : NULL; if (ok && e2 == NULL) ok = false; if (ok) { off2 = (off_t) e2->physical_offset; /* Strictly increasing offsets: nothing overwrote a predecessor. */ stage = 8; if (off1 != (off_t) tail || off2 <= off1) ok = false; /* * Failed-pwrite path: the injected EIO must leave the slot DIRTY * (the published tail no longer describes the file end), and the * next append must recover through the discover path. */ stage = 9; cfs_test_fill_page(page, 0x64); cfs_debug_fail_pwrite = 1; rc = cfs_write_page(cfs, 3, (const char *) page, &opts); cfs_debug_fail_pwrite = 0; if (rc == CFS_STORAGE_OK) ok = false; stage = 10; if (ok && cfs_cfp_tail_fetch(fx.rl, MAIN_FORKNUM, &tail)) ok = false; /* DIRTY must not answer a trusted tail */ stage = 11; cfs_test_fill_page(page, 0x65); if (cfs_write_page(cfs, 3, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; } /* Read back everything written under the protocol. */ stage = 12; { unsigned char expect[4]; int blk; int tag; expect[0] = 0x61; expect[1] = 0x62; expect[2] = 0x63; expect[3] = 0x65; for (blk = 0; blk < 4 && ok; blk++) { if (cfs_read_page(cfs, blk, (char *) back) != CFS_STORAGE_OK) ok = false; else { /* cfs_test_fill_page writes the ramp (tag + i) & 0x7F. */ for (tag = 0; tag < TEST_BLCKSZ; tag++) { if (back[tag] != (unsigned char) ((expect[blk] + tag) & 0x7F)) { ok = false; break; } } } } } cfs_close(cfs); cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "stage=%d first=%llu second=%llu third=%llu %s", stage, (unsigned long long) CFS_CFP_BASE_OFFSET, ok ? (unsigned long long) off1 : 0ULL, ok ? (unsigned long long) off2 : 0ULL, ok ? "tail protocol held" : "protocol broken"); add_result("storage_shared_tail_protocol", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * D4 zero-copy RAW: CfsCompressPageNoCopy() must describe the very same * on-disk record as the contiguous CfsCompressPage() (byte-identical * gathered form, valid CRCs, correct round-trip) while pointing its * payload at the caller's page instead of copying 8 KiB into the scratch * buffer. A compressed result keeps the contiguous contract. */ static void test_compress_page_nocopy_raw(void) { unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; unsigned char *gathered; size_t scratch_sz; CfsCompressOptions opts; CfsCompressResult cres_copy; CfsCompressResult cres_vec; CfsDecompressStatus dstatus; char detail[160]; bool ok = true; scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); gathered = palloc(2 * CFS_BLCKSZ + CFS_BLOCK_HEADER_SIZE); fill_pseudo_random(page, sizeof(page)); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_RAW; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; opts.explicit_algorithm = true; opts.allow_raw_fallback = false; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres_copy); CfsCompressPageNoCopy(page, sizeof(page), &opts, scratch, scratch_sz, &cres_vec); if (!cres_copy.is_raw || !cres_vec.is_raw) ok = false; if (ok && (cres_copy.payload_external || !cres_vec.payload_external)) ok = false; /* * The no-copy descriptor must point straight at the caller's page and * carry the exact record geometry: header 28, payload 8192, padding 4, * total 8224 (all values fixed by the on-disk format). */ if (ok && (cres_vec.payload_data != page || cres_vec.padding_bytes != CFS_RECORD_SIZE(CFS_BLCKSZ) - CFS_BLOCK_HEADER_SIZE - CFS_BLCKSZ)) ok = false; /* Gather the vector form the way the record lands on disk. */ if (ok) { memset(gathered, 0, cres_vec.total_size); memcpy(gathered, cres_vec.result_data, CFS_BLOCK_HEADER_SIZE); memcpy(gathered + CFS_BLOCK_HEADER_SIZE, cres_vec.payload_data, cres_vec.compressed_size); /* the padding stays zeroed by the memset above */ } /* Byte-identical to the contiguous (pre-D4) record. */ if (ok && memcmp(gathered, cres_copy.result_data, cres_copy.total_size) != 0) ok = false; if (ok && cres_vec.total_size != cres_copy.total_size) ok = false; /* The gathered record must validate and round-trip. */ if (ok && !CfsVerifyBlockHeader( (const CfsCompressedBlockHeader *) gathered)) ok = false; if (ok) { dstatus = CfsDecompressPage(gathered, cres_vec.total_size, decompressed, sizeof(decompressed), NULL); if (dstatus != CFS_DECOMPRESS_OK || memcmp(decompressed, page, sizeof(page)) != 0) ok = false; } /* A compressed result keeps the contiguous contract in both forms. */ if (ok && CfsCodecAvailable(CFS_ALGORITHM_LZ4)) { CfsCompressResult cres_lz4; fill_constant(page, sizeof(page), 0x77); memset(&opts, 0, sizeof(opts)); opts.algorithm = CFS_ALGORITHM_LZ4; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; CfsCompressPageNoCopy(page, sizeof(page), &opts, scratch, scratch_sz, &cres_lz4); if (cres_lz4.is_raw || cres_lz4.payload_external) ok = false; if (ok) { dstatus = CfsDecompressPage(cres_lz4.result_data, cres_lz4.total_size, decompressed, sizeof(decompressed), NULL); if (dstatus != CFS_DECOMPRESS_OK || memcmp(decompressed, page, sizeof(page)) != 0) ok = false; } } snprintf(detail, sizeof(detail), "raw record %zu bytes, pad %zu, %s", cres_vec.total_size, cres_vec.padding_bytes, ok ? "byte-identical, round-trip ok" : "mismatch"); add_result("compress_page_nocopy_raw", ok ? "ok" : "fail", detail); pfree(gathered); pfree(scratch); } /* ================================================================ * Shared-memory map cache, statistics, eviction and * the cached read/write integration. * ================================================================ */ /* * Build a synthetic permanent locator with a caller-chosen relNumber so * that every test case uses a distinct cache key (the shared cache * persists across tests within one backend session). */ static RelFileLocatorBackend cfs_shmem_test_locator(Oid relnumber) { RelFileLocatorBackend rl; rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = relnumber; rl.backend = INVALID_PROC_NUMBER; return rl; } static void test_shmem_meta_pin(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800150); uint64 nblocks = 0; char detail[160]; bool ok = true; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); /* No metadata yet. */ if (cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks)) ok = false; cfs_map_cache_pin(rl, MAIN_FORKNUM); cfs_map_cache_set_meta(rl, MAIN_FORKNUM, 42); if (!cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks) || nblocks != 42) ok = false; /* Releasing drops the metadata slot. */ cfs_map_cache_release_relation(rl, MAIN_FORKNUM); if (cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks)) ok = false; snprintf(detail, sizeof(detail), "meta/pin/release %s", ok ? "ok" : "failed"); add_result("shmem_meta_pin", ok ? "ok" : "fail", detail); } static void test_shmem_stats(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800200); CfsStatsSnapshot snap; char detail[160]; bool ok = true; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); cfs_stats_reset(rl, MAIN_FORKNUM); cfs_stats_count_read(rl, MAIN_FORKNUM, 100); cfs_stats_count_write(rl, MAIN_FORKNUM, 200, false); cfs_stats_count_write(rl, MAIN_FORKNUM, 300, true); cfs_stats_count_crc_failure(rl, MAIN_FORKNUM); if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap)) ok = false; else if (snap.read_count != 1 || snap.write_count != 2 || snap.crc_failures != 1 || snap.compressed_bytes != 200 || snap.raw_bytes != 300 || snap.dead_bytes != 0 || snap.dead_pages != 0) ok = false; cfs_stats_reset(rl, MAIN_FORKNUM); if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap)) ok = false; else if (snap.read_count != 0 || snap.write_count != 0 || snap.compressed_bytes != 0 || snap.crc_failures != 0) ok = false; snprintf(detail, sizeof(detail), "counters reads=%llu writes=%llu after reset reads=%llu", (unsigned long long) snap.read_count, (unsigned long long) snap.write_count, (unsigned long long) snap.read_count); add_result("shmem_stats", ok ? "ok" : "fail", detail); } static void test_shmem_cached_io(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsStatsSnapshot snap; char detail[160]; bool ok = true; cfs_storage_setup(&fx, "cached_io"); if (fx.dir == NULL) { add_result("shmem_cached_io", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800300; cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs = cfs_storage_open_new(&fx); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); cfs_stats_reset(fx.rl, MAIN_FORKNUM); cfs_test_fill_page(page, 0xA0); if (cfs_write_page_cached(cfs, 0, (const char *) page, &opts) != 0) ok = false; /* First read populates the cache; second read is a cache hit. */ if (ok && cfs_read_page_cached(cfs, 0, (char *) back) != 0) ok = false; if (ok && memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; if (ok && cfs_read_page_cached(cfs, 0, (char *) back) != 0) ok = false; cfs_stats_snapshot(fx.rl, MAIN_FORKNUM, &snap); if (snap.write_count < 1 || snap.read_count < 1) ok = false; cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_close(cfs); snprintf(detail, sizeof(detail), "cached write/read reads=%llu writes=%llu", (unsigned long long) snap.read_count, (unsigned long long) snap.write_count); add_result("shmem_cached_io", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * A corrupt entry served from the shared cache (bad entry_crc) must be * rejected on the cache-hit path, with the block's cache slot dropped so the * next read falls back to the authoritative map. */ static void test_read_cached_entry_corruption(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry bad; bool ok = true; cfs_storage_setup(&fx, "cachemapcorrupt"); if (fx.dir == NULL) { add_result("read_cached_entry_corruption", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800360; cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs = cfs_storage_open_new(&fx); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); cfs_test_fill_page(page, 0x22); if (cfs_write_page_cached(cfs, 0, (const char *) page, &opts) != 0) ok = false; /* Publish an entry with a corrupted CRC into the shared segment. */ cfs_map_entry_init(&bad); bad.physical_offset = CFS_CFP_BASE_OFFSET; bad.compressed_size = 1; bad.generation = 1; cfs_map_entry_crc_set(&bad); bad.entry_crc ^= 0x1; cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 0, &bad, cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM)); /* The segment-hit read must reject the corrupt entry (ERROR by GUC). */ if (ok) { bool raised = false; PG_TRY(); { (void) cfs_read_page_cached(cfs, 0, (char *) back); } PG_CATCH(); { raised = true; FlushErrorState(); /* * The error unwinding can leave a transient context current; back * to a durable one. */ MemoryContextSwitchTo(TopMemoryContext); } PG_END_TRY(); if (!raised) ok = false; } /* The corrupt entry must have been dropped, not just refused once. */ if (ok && cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &bad, NULL)) ok = false; cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_close(cfs); add_result("read_cached_entry_corruption", ok ? "ok" : "fail", ok ? "corrupt cached entry rejected and invalidated" : "corrupt cached entry not rejected"); cfs_storage_teardown(&fx); } static void test_bg_pause_expiry(void) { CfsBgStatus st; char detail[160]; bool ok = true; /* An already-expired timed pause must self-heal on read. */ cfs_bg_pause((int64) GetCurrentTimestamp() - 1000000); if (cfs_bg_is_paused()) ok = false; MemSet(&st, 0, sizeof(st)); cfs_bg_get_status(&st); if (st.paused || st.paused_until != 0) ok = false; /* An indefinite pause must hold. */ cfs_bg_pause(0); if (!cfs_bg_is_paused()) ok = false; /* Resume clears it. */ cfs_bg_resume(); if (cfs_bg_is_paused()) ok = false; cfs_bg_resume(); /* never leave the worker paused */ snprintf(detail, sizeof(detail), "pause/expiry/status %s", ok ? "ok" : "failed"); add_result("bg_pause_expiry", ok ? "ok" : "fail", detail); } /* * A durable compaction swap replaces the .cfp inode while a writer's handle * still points at the old one (stale fds). A cache hit must reopen such a * handle before reading through the cached offset: the offset is valid in * the NEW .cfp, and reading it through the old fd returns the pre-swap * bytes (or garbage). cfs_handle_refresh_if_stale() must run on the hit * path when this handle's open_generation lags the current map generation. */ static void test_shmem_stale_handle_hit(void) { RelFileLocatorBackend rl; CfsRelation *h1; CfsRelation *h2; unsigned char v1[TEST_BLCKSZ]; unsigned char v2[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsCompactOptions copts = CFS_COMPACT_OPTIONS_DEFAULT; CfsCompactResult cres; char detail[160]; bool ok = true; rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = 999091; rl.backend = INVALID_PROC_NUMBER; cfs_test_unlink_synthetic(rl); cfs_map_cache_invalidate(rl, MAIN_FORKNUM); h1 = cfs_create(rl, MAIN_FORKNUM); cfs_map_cache_pin(rl, MAIN_FORKNUM); cfs_test_fill_page(v1, 0x10); cfs_test_fill_page(v2, 0x20); /* h1 publishes block 0 = v1 and reads it back (cache populated). */ if (cfs_write_page_cached(h1, 0, (const char *) v1, &opts) != 0) ok = false; if (ok && cfs_read_page_cached(h1, 0, (char *) back) != 0) ok = false; if (ok && memcmp(back, v1, TEST_BLCKSZ) != 0) ok = false; /* Durable compaction swap: generation +1, h1 now holds stale fds. */ if (ok && cfs_compact_relation(rl, MAIN_FORKNUM, &copts, &cres, InvalidOid) != CFS_STORAGE_OK) ok = false; /* h2 opens at the current generation and rewrites block 0 = v2. */ h2 = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR); if (h2 == NULL) ok = false; else { if (cfs_write_page_cached(h2, 0, (const char *) v2, &opts) != 0) ok = false; cfs_close(h2); } /* h1 (stale fds) must reopen on the cache hit and read v2, not v1. */ if (ok && cfs_read_page_cached(h1, 0, (char *) back) != 0) ok = false; if (ok && memcmp(back, v2, TEST_BLCKSZ) != 0) ok = false; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); cfs_map_cache_release_relation(rl, MAIN_FORKNUM); cfs_close(h1); cfs_test_unlink_synthetic(rl); snprintf(detail, sizeof(detail), "stale handle reopened on hit %s", ok ? "ok" : "failed"); add_result("shmem_stale_handle_hit", ok ? "ok" : "fail", detail); } /* * Publish guard: cfs_map_cache_publish_if_not_stale() must never * overwrite a cache entry that carries a newer per-block generation, so a * reader that fell behind a concurrent writer of the same block cannot * poison the shared cache with its older local entry. */ /* * Generation tagging: a publication must stamp the cache cell with the map * generation the entry's offsets belong to (the one captured when the * publishing reader refreshed its map), never with the generation current * at publication time. Scenario: the reader captures the generation, a * compaction sweeps the cells and bumps the generation, and only then does * the reader publish offsets of the old generation. The cell must carry * the captured (old) generation, so the lookup validation rejects it; * stamping it with the current one would serve a stale offset against the * new sidecar files. */ /* * Shared block-map segment pool API: store/lookup round trip, INVALID * sentinel miss, segment boundaries, truncate-range handling and relation * invalidation with the pool counters. */ static void test_shared_map_api(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800710); CfsMapEntry in; CfsMapEntry out; uint64 in_use = 0; uint64 in_use0 = 0; uint64 loads = 0; uint64 evictions = 0; uint64 evictions0 = 0; uint64 capacity = 0; char detail[160]; bool ok = true; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_shared_map_stats(&in_use0, &loads, &evictions0, &capacity); if (capacity == 0) { add_result("shared_map_api", "skip", "pool disabled"); return; } /* Other relations may hold segments; assert on deltas. */ /* A lookup before any store must miss. */ if (cfs_shared_map_lookup(rl, MAIN_FORKNUM, 10, &out, NULL)) ok = false; /* Store into block 10 and look it back up. */ cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 1234; in.generation = 1; cfs_map_entry_crc_set(&in); if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 10, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM))) ok = false; if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 10, &out, NULL)) ok = false; else if (ok && (out.physical_offset != in.physical_offset || out.compressed_size != in.compressed_size || out.generation != in.generation)) ok = false; /* An untouched block of the same segment is the INVALID sentinel. */ if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 11, &out, NULL)) ok = false; /* A block of the next segment spans a second pool segment. */ if (ok && !cfs_shared_map_store(rl, MAIN_FORKNUM, CFS_MAP_SEGMENT_BLOCKS + 5, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM))) ok = false; if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, CFS_MAP_SEGMENT_BLOCKS + 5, &out, NULL)) ok = false; cfs_shared_map_stats(&in_use, &loads, &evictions, &capacity); if (ok && in_use - in_use0 != 2) ok = false; /* Relation invalidation drops everything and counts an eviction. */ if (ok) { cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); if (cfs_shared_map_lookup(rl, MAIN_FORKNUM, 10, &out, NULL)) ok = false; cfs_shared_map_stats(&in_use, &loads, &evictions, &capacity); if (in_use - in_use0 != 0 || evictions - evictions0 == 0) ok = false; } snprintf(detail, sizeof(detail), "segment pool API %s", ok ? "ok" : "failed"); add_result("shared_map_api", ok ? "ok" : "fail", detail); } /* * The pool must not serve rows at or above the metadata slot's current * logical size. A truncate shrinks the slot (and * journals RESIZE) under the append lock but drops the resident segments * outside it, so a lookup racing in that window can still find the stale * segment; the nblocks gate must turn that into a plain miss. */ static void test_shared_map_nblocks_gate(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800740); CfsMapEntry in; CfsMapEntry out; char detail[160]; bool ok = true; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 1234; in.generation = 1; cfs_map_entry_crc_set(&in); /* Publish the logical size the way the write path does, then store. */ cfs_map_cache_set_meta(rl, MAIN_FORKNUM, 100); if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 5, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM)) || !cfs_shared_map_store(rl, MAIN_FORKNUM, 50, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM)) || !cfs_shared_map_store(rl, MAIN_FORKNUM, 95, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM))) ok = false; /* All rows are served while nblocks == 100. */ if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 95, &out, NULL)) ok = false; /* * The truncate window: the slot size (and generation) is already shrunk, * the stale segments are still resident. */ if (ok) cfs_map_cache_truncate(rl, MAIN_FORKNUM, 40); /* Rows at or above the new size must miss; rows below still hit. */ if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 50, &out, NULL)) ok = false; if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 95, &out, NULL)) ok = false; if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 5, &out, NULL)) ok = false; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "nblocks gate %s", ok ? "ok" : "served stale rows"); add_result("shared_map_nblocks_gate", ok ? "ok" : "fail", detail); } /* * Segment eviction: filling more distinct segments than the pool holds * must evict by LRU (oldest store first), keep the pool fully used and * leave evicted lookups as plain misses. */ static void test_shared_map_eviction(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800720); CfsMapEntry in; CfsMapEntry out; uint64 in_use = 0; uint64 loads = 0; uint64 evictions = 0; uint64 capacity = 0; char detail[160]; bool ok = true; int i; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_shared_map_stats(&in_use, &loads, &evictions, &capacity); if (capacity == 0) { add_result("shared_map_eviction", "skip", "pool disabled"); return; } cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); /* Fill capacity + 10 distinct segments: ten LRU evictions must occur. */ for (i = 0; i < (int) capacity + 10; i++) { if (!cfs_shared_map_store(rl, MAIN_FORKNUM, (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM))) { ok = false; break; } } if (ok) { uint64 evictions_after; cfs_shared_map_stats(&in_use, &loads, &evictions_after, &capacity); if (in_use != capacity) ok = false; if (evictions_after - evictions < 10) ok = false; } /* The very first (oldest) segment was evicted: its lookup misses. */ if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &out, NULL)) ok = false; /* The newest segment survived. */ if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, (BlockNumber) ((int) capacity + 9) * CFS_MAP_SEGMENT_BLOCKS, &out, NULL)) ok = false; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "eviction %s", ok ? "ok" : "failed"); add_result("shared_map_eviction", ok ? "ok" : "fail", detail); } /* * Eviction with a pinned relation: an open handle pins the relation's * metadata slot, but that pin protects the slot, not the pool segments. * Filling the pool beyond capacity with segments of the pinned relation * must still evict by usage_count order — otherwise a relation larger * than the pool keeps the pool exhausted forever and every further read * of the relation pays the authoritative fallback. */ static void test_shared_map_eviction_pinned(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800730); CfsMapEntry in; CfsMapEntry out; uint64 in_use = 0; uint64 evictions = 0; uint64 evictions_after = 0; uint64 capacity = 0; char detail[160]; bool ok = true; int i; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_shared_map_stats(&in_use, NULL, &evictions, &capacity); if (capacity == 0) { add_result("shared_map_eviction_pinned", "skip", "pool disabled"); return; } cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); /* The relation stays pinned for the whole fill, like an open handle. */ cfs_map_cache_pin(rl, MAIN_FORKNUM); for (i = 0; i < (int) capacity + 10; i++) { if (!cfs_shared_map_store(rl, MAIN_FORKNUM, (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM))) { ok = false; break; } } if (ok) { cfs_shared_map_stats(&in_use, NULL, &evictions_after, &capacity); if (in_use != capacity) ok = false; if (evictions_after - evictions < 10) ok = false; } /* The oldest segments were evicted even though the relation is pinned. */ if (ok && cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &out, NULL)) ok = false; if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, (BlockNumber) ((int) capacity + 9) * CFS_MAP_SEGMENT_BLOCKS, &out, NULL)) ok = false; cfs_map_cache_unpin(rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "pinned eviction %s", ok ? "ok" : "failed"); add_result("shared_map_eviction_pinned", ok ? "ok" : "fail", detail); } /* * A repeated store of an already resident key must be a plain update, not a * victim search: with a full pool the old acquire path evicted an unrelated * segment before it even looked the key up. */ static void test_shared_map_resident_store_no_evict(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800810); CfsMapEntry in; uint64 capacity = 0; uint64 ev0 = 0; uint64 ev1 = 0; uint64 gen; char detail[160]; bool ok = true; int i; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity < 2) { add_result("shared_map_resident_store_no_evict", "skip", "pool too small"); return; } cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); gen = cfs_map_cache_get_generation(rl, MAIN_FORKNUM); cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); /* * Fill the pool with distinct keys. Other tests may already hold * segments, so use the last key inserted as the guaranteed resident one * rather than assuming key 0 survived the fill. */ for (i = 0; i < (int) capacity; i++) if (!cfs_shared_map_store(rl, MAIN_FORKNUM, (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS, &in, gen)) ok = false; /* Make the target resident, then measure only the repeated stores. */ if (!cfs_shared_map_store(rl, MAIN_FORKNUM, (BlockNumber) (capacity - 1) * CFS_MAP_SEGMENT_BLOCKS, &in, gen)) ok = false; cfs_shared_map_stats(NULL, NULL, &ev0, NULL); for (i = 0; i < 10; i++) if (!cfs_shared_map_store(rl, MAIN_FORKNUM, (BlockNumber) (capacity - 1) * CFS_MAP_SEGMENT_BLOCKS, &in, gen)) ok = false; cfs_shared_map_stats(NULL, NULL, &ev1, NULL); if (ok && ev1 != ev0) ok = false; if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, (BlockNumber) (capacity - 1) * CFS_MAP_SEGMENT_BLOCKS, &in, NULL)) ok = false; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "resident store evictions %llu", (unsigned long long) (ev1 - ev0)); add_result("shared_map_resident_store_no_evict", ok ? "ok" : "fail", detail); } /* * Clock sweep: a segment touched by a hit must survive the next victim * selection even with a full pool; an untouched segment is evicted instead. */ static void test_shared_map_clock_sweep(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800830); CfsMapEntry in; uint64 capacity = 0; uint64 gen; char detail[160]; bool ok = true; int i; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity < 3) { add_result("shared_map_clock_sweep", "skip", "pool too small"); return; } cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); gen = cfs_map_cache_get_generation(rl, MAIN_FORKNUM); cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); for (i = 0; i < (int) capacity; i++) if (!cfs_shared_map_store(rl, MAIN_FORKNUM, (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS, &in, gen)) ok = false; /* Key 0 becomes the recently used segment. */ if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &in, NULL)) ok = false; /* A new key needs a victim: key 0 must not be the one. */ if (ok && !cfs_shared_map_store(rl, MAIN_FORKNUM, (BlockNumber) capacity * CFS_MAP_SEGMENT_BLOCKS, &in, gen)) ok = false; if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &in, NULL)) ok = false; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "clock sweep %s", ok ? "kept the hot segment" : "evicted the hot segment"); add_result("shared_map_clock_sweep", ok ? "ok" : "fail", detail); } /* * Segment loading: cfs_shared_map_ensure() reads a segment straight from * the .cfsmap snapshot. After a checkpoint the loaded entries must match * the authoritative per-handle map, and blocks beyond the snapshot stay * INVALID (a miss, filled by the journal-replay path). */ static void test_shared_map_ensure(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry out; uint64 capacity = 0; uint64 loads_before = 0; uint64 loads_after = 0; char detail[160]; bool ok = true; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_ensure", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "segload"); if (fx.dir == NULL) { add_result("shared_map_ensure", "fail", "setup failed"); return; } cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x71); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK || cfs_write_page(cfs, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok) { /* Checkpoint: snapshot + journal reset. */ cfs_map_save_snapshot(cfs); test_journal_reset(cfs, ERROR); } cfs_close(cfs); if (!ok) { snprintf(detail, sizeof(detail), "ensure setup failed"); add_result("shared_map_ensure", "fail", detail); cfs_storage_teardown(&fx); return; } /* Fresh handle: its own map load is the reference for the segment. */ cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); if (cfs == NULL) { add_result("shared_map_ensure", "fail", "reopen failed"); cfs_storage_teardown(&fx); return; } cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); /* Load the segment covering blocks 0..1 from the snapshot. */ if (cfs_shared_map_ensure(cfs, 0) != CFS_STORAGE_OK) ok = false; /* The loaded entry must match the handle's authoritative map. */ if (ok && !cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &out, NULL)) ok = false; if (ok && (out.physical_offset != cfs->map[0].physical_offset || out.compressed_size != cfs->map[0].compressed_size || out.generation != cfs->map[0].generation)) ok = false; /* * A second ensure on the same segment is a cheap residency hit (no new * snapshot load); a block beyond the snapshot inside the loaded segment * stays INVALID. */ cfs_shared_map_stats(NULL, &loads_before, NULL, NULL); if (ok && cfs_shared_map_ensure(cfs, 1) != CFS_STORAGE_OK) ok = false; cfs_shared_map_stats(NULL, &loads_after, NULL, NULL); if (loads_after != loads_before) ok = false; if (ok && cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 100, &out, NULL)) ok = false; cfs_close(cfs); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_storage_teardown(&fx); snprintf(detail, sizeof(detail), "segment load %s", ok ? "ok" : "failed"); add_result("shared_map_ensure", ok ? "ok" : "fail", detail); } /* * A resident segment tagged with an older relation generation must never * satisfy a read through a handle opened after the generation bump: the * old offsets belong to the pre-truncate sidecar pair. The reader has to * retry through eviction/reload and return the real page, not a zero page. */ static void test_shared_map_generation_gate(void) { CfsStorageFixture fx; CfsRelation *h; CfsRelation *lazy; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char cfp_path[MAXPGPATH]; char map_path[MAXPGPATH]; char jrn_path[MAXPGPATH]; char detail[160]; bool ok = true; cfs_storage_setup(&fx, "seggengate"); if (fx.dir == NULL) { add_result("shared_map_generation_gate", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800745; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path)); strlcpy(map_path, fx.map_path, sizeof(map_path)); strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path)); h = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x77); if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; /* A snapshot lets the stale segment be reloaded after the bump. */ if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK) ok = false; if (ok) cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 1); cfs_close(h); /* Warm the segment under the old generation. */ lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL || cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; if (lazy) cfs_close(lazy); /* * Bump the generation without invalidating the pool: the segment stays * resident with the old rel_generation, while a new handle opens with the * new one. The stale segment must be evicted and reloaded, not treated * as proof that block 0 was never written. */ cfs_map_cache_truncate(fx.rl, MAIN_FORKNUM, 1); lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; else { if (cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; cfs_close(lazy); } cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "generation gate %s", ok ? "ok" : "served a zero/stale page"); add_result("shared_map_generation_gate", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } static void test_shared_map_short_read(void) { CfsStorageFixture fx; CfsRelation *h; CfsRelation *lazy; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); char cfp_path[MAXPGPATH]; char map_path[MAXPGPATH]; char jrn_path[MAXPGPATH]; uint64 in_use_before = 0; uint64 in_use_after = 0; char detail[160]; bool ok = true; int fd; cfs_storage_setup(&fx, "segshort"); if (fx.dir == NULL) { add_result("shared_map_short_read", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800747; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path)); strlcpy(map_path, fx.map_path, sizeof(map_path)); strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path)); h = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x66); if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK || cfs_write_page(h, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK) ok = false; cfs_close(h); /* Keep the header but cut the entry range in half. */ fd = open(fx.map_path, O_WRONLY); if (fd < 0 || ftruncate(fd, CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE / 2) != 0) ok = false; if (fd >= 0) close(fd); cfs_shared_map_stats(&in_use_before, NULL, NULL, NULL); lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; else { /* * A partial trailing row is a torn write and the loader ignores it * (the row count is the floored file size). The journal still holds * the covering record, so the torn block reads back healed - never as * a fabricated zero page and never as an error. */ if (cfs_read_page_cached(lazy, 0, (char *) back) != 0 || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; cfs_close(lazy); } cfs_shared_map_stats(&in_use_after, NULL, NULL, NULL); /* * A torn tail no longer aborts the segment load; the journal-healed * segment legitimately lands in the pool. */ cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "torn tail ignored, healed from journal (%s)", ok ? "healed" : "data lost"); add_result("shared_map_short_read", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * A corrupt journal record with valid records after it is not a torn tail. * The segment replay used to stop at it with DEBUG1 and then mark the * segment journal_synced, so the pool served the stale snapshot entry to * every backend. It must escalate like the full replay does and leave the * segment unsynchronised instead. */ static void test_shared_map_segment_replay_corruption(void) { CfsStorageFixture fx; CfsRelation *h; CfsRelation *lazy = NULL; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsJournalEntry je; uint64 capacity = 0; char cfp_path[MAXPGPATH]; char map_path[MAXPGPATH]; char jrn_path[MAXPGPATH]; char detail[160]; bool raised = false; bool ok = true; int fd = -1; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_replay_corruption", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "segjrncorrupt"); if (fx.dir == NULL) { add_result("shared_map_replay_corruption", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800749; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path)); strlcpy(map_path, fx.map_path, sizeof(map_path)); strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path)); h = cfs_storage_open_new(&fx); /* Snapshot version A of block 0. */ cfs_test_fill_page(page, 0xA1); if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK) ok = false; if (ok) test_journal_reset(h, ERROR); /* Journal now holds version B of block 0, then a valid block-1 record. */ cfs_test_fill_page(page, 0xB2); if (ok && cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; cfs_test_fill_page(page, 0xC3); if (ok && cfs_write_page(h, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(h); /* * Corrupt the first record, leaving the second one valid: this is the * non-tail shape a legal append cannot produce. */ if (ok) { struct stat st; uint32 garbage = 0xDEADBEEF; fd = BasicOpenFile(fx.jrn_path, O_RDWR | PG_BINARY); if (fd < 0) ok = false; else if (fstat(fd, &st) != 0 || st.st_size < (off_t) (CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE) || pread(fd, &je, sizeof(je), CFS_JOURNAL_HEADER_SIZE) != sizeof(je) || je.op != CFS_JRN_OP_UPDATE || je.blocknum != 0) ok = false; else if (pwrite(fd, &garbage, sizeof(garbage), CFS_JOURNAL_HEADER_SIZE) != sizeof(garbage)) ok = false; } if (fd >= 0) close(fd); if (ok) { cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; else lazy->strict = true; } if (ok) { MemoryContext oldcontext = TopMemoryContext; ResourceOwner oldowner = CurrentResourceOwner; MemoryContextSwitchTo(TopMemoryContext); /* * The read raises while holding the append lock, so use an internal * subtransaction to get the full cleanup and keep testing. */ BeginInternalSubTransaction(NULL); PG_TRY(); { (void) cfs_read_page_cached(lazy, 0, (char *) back); ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; } PG_CATCH(); { ErrorData *edata; MemoryContextSwitchTo(oldcontext); edata = CopyErrorData(); raised = (edata->message != NULL && strstr(edata->message, "corruption") != NULL); FreeErrorData(edata); FlushErrorState(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcontext); CurrentResourceOwner = oldowner; } PG_END_TRY(); } if (lazy != NULL) cfs_close(lazy); if (ok && !raised) ok = false; cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "mid-journal corruption %s", raised ? "rejected" : "served stale page"); add_result("shared_map_replay_corruption", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * Journal incarnation vs the segment sync cursor. A checkpoint truncates * the journal (bumping its incarnation) while a pool segment survives with * a stale jrn_synced_off; two shapes must be handled: * * - shrink: the journal shrank below the segment's cursor and a written * block now lives only in the fresh .cfsmap snapshot — the segment must * re-merge it instead of answering "never written"; * - regrow (ABA): the new-incarnation journal grows back past the stale * cursor — replaying from the stale cursor silently skips the records * below it. * * The full handle's storage-layer writes (cfs_write_page) append journal * records without publishing into the pool segment — exactly the * journal-only situation a failed store produces in production. */ static void test_shared_map_journal_aba(void) { CfsStorageFixture fx; CfsRelation *h; CfsRelation *lazy; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry bad; uint64 capacity = 0; char cfp_path[MAXPGPATH]; char map_path[MAXPGPATH]; char jrn_path[MAXPGPATH]; char detail[160]; bool ok = true; int i; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_journal_aba", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "segjrnbump"); if (fx.dir == NULL) { add_result("shared_map_journal_aba", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800730; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path)); strlcpy(map_path, fx.map_path, sizeof(map_path)); strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path)); h = cfs_storage_open_new(&fx); /* * Phase A: snapshot v1, truncate the journal, warm the segment and * advance its sync cursor to the current journal end. */ cfs_test_fill_page(page, 0x11); if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK) ok = false; if (ok) test_journal_reset(h, WARNING); if (ok) { lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL || cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; if (lazy) cfs_close(lazy); } cfs_test_fill_page(page, 0x22); if (ok && cfs_write_page(h, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok) cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 2); if (ok) { lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL || cfs_read_page_cached(lazy, 1, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; if (lazy) cfs_close(lazy); } /* * Phase B (shrink): block 2 is written journal-only, then snapshot v2 * absorbs it and the journal is truncated. Reading it must resolve * through the fresh snapshot, not return a zero page. */ cfs_test_fill_page(page, 0x33); if (ok && cfs_write_page(h, 2, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok) cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 3); if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK) ok = false; if (ok) test_journal_reset(h, WARNING); if (ok) { lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL || cfs_read_page_cached(lazy, 2, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; if (lazy) cfs_close(lazy); } /* * Phase C (ABA): rewrite block 1 (its record lands near the journal * header, below the stale cursor), regrow the journal past the cursor * with block-0 rewrites, then force a block-1 miss with a poisoned * (bad-CRC) entry. The miss path must replay from the journal header and * return the rewrite. */ cfs_test_fill_page(page, 0x44); if (ok && cfs_write_page(h, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; cfs_test_fill_page(page, 0x55); for (i = 0; ok && i < 10; i++) { if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; } if (ok) { cfs_map_entry_init(&bad); bad.physical_offset = CFS_CFP_BASE_OFFSET; bad.compressed_size = 1; bad.generation = 1; cfs_map_entry_crc_set(&bad); bad.entry_crc ^= 0x1; cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 1, &bad, cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM)); /* * First read rejects the poisoned entry (ERROR); the retry must * resolve through the journal replay. */ lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; else { bool raised = false; PG_TRY(); { (void) cfs_read_page_cached(lazy, 1, (char *) back); } PG_CATCH(); { raised = true; FlushErrorState(); /* * The error unwinding can leave a transient context current; * back to a durable one. */ MemoryContextSwitchTo(TopMemoryContext); } PG_END_TRY(); if (!raised) ok = false; /* The retry must resolve the rewrite (payload 0x44). */ cfs_test_fill_page(page, 0x44); if (ok && (cfs_read_page_cached(lazy, 1, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0)) ok = false; cfs_close(lazy); } } cfs_close(h); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_storage_teardown(&fx); snprintf(detail, sizeof(detail), "journal truncation vs segment sync %s", ok ? "ok" : "failed"); add_result("shared_map_journal_aba", ok ? "ok" : "fail", detail); } /* * Truncate vs snapshot merge: a segment's RESIZE-cleared slots must not be * resurrected by a later .cfsmap merge. The storage-layer truncate * journals RESIZE (the smgr path then drops the relation's segments), but * the on-disk .cfsmap stays wide until the next checkpoint — publishing or * merging a segment from it refills the cleared slots with pre-truncate * entries unless the journal (whose RESIZE is the only post-truncate * truth) is replayed after the merge. */ static void test_shared_map_truncate_resurrect(void) { CfsStorageFixture fx; CfsRelation *h; CfsRelation *lazy; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; unsigned char zeros[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry bad; uint64 capacity = 0; char cfp_path[MAXPGPATH]; char map_path[MAXPGPATH]; char jrn_path[MAXPGPATH]; char detail[160]; bool ok = true; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_truncate_resurrect", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "segtruncres"); if (fx.dir == NULL) { add_result("shared_map_truncate_resurrect", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800740; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); MemSet(zeros, 0, sizeof(zeros)); /* * Snapshot the fixture paths into stack buffers: a PG_CATCH elsewhere in * the run can leave CurrentMemoryContext pointing at a context that a * later error unwinds, and psprintf'd path copies allocated there must * not outlive it. */ strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path)); strlcpy(map_path, fx.map_path, sizeof(map_path)); strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path)); h = cfs_storage_open_new(&fx); /* Three written blocks; the (wide) snapshot v1 covers them all. */ cfs_test_fill_page(page, 0x11); if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; cfs_test_fill_page(page, 0x22); if (ok && cfs_write_page(h, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; cfs_test_fill_page(page, 0x33); if (ok && cfs_write_page(h, 2, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK) ok = false; /* * Truncate to one block (journal RESIZE; the smgr path mirrors this with * a segment invalidation and a meta update), then read block 0: the * replay applies the resize and clears blocks 1-2. */ if (ok) cfs_truncate(h, 1); if (ok) { cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 1); lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); cfs_test_fill_page(page, 0x11); if (lazy == NULL || cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; if (lazy) cfs_close(lazy); } /* * A corrupt block-0 entry drops the slot and un-loads the snapshot part, * exactly like a failed store would. */ if (ok) { cfs_map_entry_init(&bad); bad.physical_offset = CFS_CFP_BASE_OFFSET; bad.compressed_size = 1; bad.generation = 1; cfs_map_entry_crc_set(&bad); bad.entry_crc ^= 0x1; cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 0, &bad, cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM)); lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; else { bool raised = false; PG_TRY(); { (void) cfs_read_page_cached(lazy, 0, (char *) back); } PG_CATCH(); { raised = true; FlushErrorState(); /* * The error unwinding can leave a transient context current; * back to a durable one. */ MemoryContextSwitchTo(TopMemoryContext); } PG_END_TRY(); if (!raised) ok = false; cfs_close(lazy); } } /* * Re-extend back to three blocks (journal RESIZE only, no writes): blocks * 1-2 are extension gaps and must read as zero pages, and block 0 must * resolve back to its payload — never to the truncated pre-truncate * entries the stale wide .cfsmap still carries. */ if (ok && cfs_zero_extend(h, 1, 2) != CFS_STORAGE_OK) ok = false; if (ok) { cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 3); lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; else { if (cfs_read_page_cached(lazy, 1, (char *) back) != CFS_STORAGE_OK || memcmp(back, zeros, TEST_BLCKSZ) != 0) ok = false; cfs_test_fill_page(page, 0x11); if (ok && (cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0)) ok = false; cfs_close(lazy); } } cfs_close(h); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_storage_teardown(&fx); snprintf(detail, sizeof(detail), "truncate resurrection %s", ok ? "ok" : "failed"); add_result("shared_map_truncate_resurrect", ok ? "ok" : "fail", detail); } /* * Pool exhaustion: every segment held by one pinned relation must make * another relation's allocation fail gracefully (no crash, no double * mapping), and releasing the pin must make room again. */ /* * A pinned relation must not exhaust the pool: with the pool full of the * pinned relation's segments a competitor is still admitted — the slot * pin protects the metadata slot, not the segments, and cold segments * are evicted by the clock sweep. (This used to assert the opposite: * before the policy change the competitor's store failed and the read * degraded to the authoritative fallback forever.) */ static void test_shared_map_pool_exhaustion(void) { RelFileLocatorBackend rl1 = cfs_shmem_test_locator(800750); RelFileLocatorBackend rl2 = cfs_shmem_test_locator(800760); CfsMapEntry in; uint64 in_use = 0; uint64 evictions = 0; uint64 evictions0 = 0; uint64 capacity = 0; char detail[160]; bool ok = true; int i; cfs_shared_map_invalidate_relation(rl1, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rl2, MAIN_FORKNUM); cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_pool_exhaustion", "skip", "pool disabled"); return; } cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); /* Fill the whole pool with rl1's segments and keep rl1 pinned. */ cfs_map_cache_pin(rl1, MAIN_FORKNUM); for (i = 0; i < (int) capacity; i++) { if (!cfs_shared_map_store(rl1, MAIN_FORKNUM, i * CFS_MAP_SEGMENT_BLOCKS + 1, &in, cfs_map_cache_get_generation(rl1, MAIN_FORKNUM))) ok = false; } cfs_shared_map_stats(&in_use, NULL, NULL, &capacity); if (ok && in_use != capacity) ok = false; cfs_shared_map_stats(NULL, NULL, &evictions0, NULL); /* rl2 is still admitted: a cold rl1 segment is evicted for it. */ if (ok && !cfs_shared_map_store(rl2, MAIN_FORKNUM, 1, &in, cfs_map_cache_get_generation(rl2, MAIN_FORKNUM))) ok = false; if (ok && !cfs_shared_map_lookup(rl2, MAIN_FORKNUM, 1, &in, NULL)) ok = false; cfs_shared_map_stats(&in_use, NULL, &evictions, NULL); if (ok && (in_use != capacity || evictions <= evictions0)) ok = false; cfs_map_cache_unpin(rl1, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rl1, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rl2, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "pinned admission %s", ok ? "ok" : "failed"); add_result("shared_map_pool_exhaustion", ok ? "ok" : "fail", detail); } /* * The write path must not resolve the old entry through the segment pool: * with the relation-wide generation it no longer calls ensure(), so a pure * write stream loads no .cfsmap segments at all (the former write path paid * a full segment replay after every eviction). Reads still go through the * ensure/sync path and must return what was written. */ static void test_shared_map_write_no_load(void) { CfsStorageFixture fx; CfsRelation *h; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); uint64 capacity = 0; uint64 loads0 = 0; uint64 loads1 = 0; char detail[160]; bool ok = true; int i; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_write_no_load", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "writenoload"); if (fx.dir == NULL) { add_result("shared_map_write_no_load", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800770; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); h = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x61); cfs_shared_map_stats(NULL, &loads0, NULL, NULL); for (i = 0; i < 100; i++) { if (cfs_write_page_cached(h, i, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; } cfs_shared_map_stats(NULL, &loads1, NULL, NULL); if (loads1 != loads0) ok = false; for (i = 0; ok && i < 100; i++) { if (cfs_read_page_cached(h, i, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; } cfs_close(h); cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "write loaded %llu segments, reads %s", (unsigned long long) (loads1 - loads0), ok ? "ok" : "failed"); add_result("shared_map_write_no_load", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); } /* * E2: a pool whose every segment is pinned by relation A cannot serve * relation B, so the read must degrade to the authoritative private map * instead of failing. The data comes back, no ERROR is raised, and * fallback_reads accounts for the degradation. */ static void test_shared_map_fallback_read(void) { CfsStorageFixture fxB; CfsRelation *h; CfsRelation *lazy; RelFileLocatorBackend rlA = cfs_shmem_test_locator(800780); unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry in; uint64 capacity = 0; uint64 in_use = 0; uint64 fb0; uint64 fb1; char detail[160]; bool ok = true; int i; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity < 2) { add_result("shared_map_fallback_read", "skip", "pool too small"); return; } cfs_storage_setup(&fxB, "fallback"); if (fxB.dir == NULL) { add_result("shared_map_fallback_read", "fail", "setup failed"); return; } fxB.rl.locator.relNumber = 800790; cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fxB.rl, MAIN_FORKNUM); /* Relation B: one block on disk, journal-only. */ cfs_map_cache_pin(fxB.rl, MAIN_FORKNUM); h = cfs_storage_open_new(&fxB); cfs_test_fill_page(page, 0x71); if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; cfs_close(h); /* Relation A: pin it and occupy every pool segment. */ cfs_map_cache_pin(rlA, MAIN_FORKNUM); cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); for (i = 0; ok && i < (int) capacity; i++) { if (!cfs_shared_map_store(rlA, MAIN_FORKNUM, (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS, &in, cfs_map_cache_get_generation(rlA, MAIN_FORKNUM))) ok = false; } cfs_shared_map_stats(&in_use, NULL, NULL, &capacity); if (ok && in_use != capacity) ok = false; /* * A pinned relation no longer protects its segments, so simulate a * genuinely unallocatable pool (all segments reserved) with the test-only * switch: the read must degrade to the authoritative fallback and still * return the data. */ fb0 = cfs_shared_map_fallback_reads(); cfs_test_pool_block_victim = true; lazy = cfs_open_paths(fxB.rl, MAIN_FORKNUM, fxB.cfp_path, fxB.map_path, fxB.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP); if (lazy == NULL) ok = false; else { if (cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) ok = false; cfs_close(lazy); } cfs_test_pool_block_victim = false; fb1 = cfs_shared_map_fallback_reads(); if (ok && fb1 <= fb0) ok = false; cfs_map_cache_unpin(rlA, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fxB.rl, MAIN_FORKNUM); cfs_map_cache_invalidate(fxB.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fxB.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "fallback_reads +%llu, data %s", (unsigned long long) (fb1 - fb0), ok ? "ok" : "mismatch or ERROR"); add_result("shared_map_fallback_read", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fxB); } /* * Unhealed snapshot corruption must fail every read, in both the pool and * the authoritative fallback path, and must never come back as a zero * page. The journal is empty (a fresh checkpoint), so * nothing can heal the corrupted row. */ static void test_shared_map_unhealed_corruption(void) { CfsStorageFixture fx; CfsRelation *cfs; CfsRelation *lazy = NULL; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry out; uint64 capacity = 0; char detail[160]; bool ok = true; bool auth0_ok = false; bool auth1_ok = false; bool pool0_ok = false; bool pool1_ok = false; bool pool1_again_ok = false; bool lookup_ok = false; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_unhealed_corruption", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "unhealed"); if (fx.dir == NULL) { add_result("shared_map_unhealed_corruption", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800890; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); cfs = cfs_storage_open_new(&fx); cfs_test_fill_page(page, 0x51); if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK || cfs_write_page(cfs, 1, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok) { /* Checkpoint: snapshot + empty journal. */ cfs_map_save_snapshot(cfs); cfs_journal_reset_point(cfs, cfs_map_live_summary(cfs), ERROR); } cfs_close(cfs); if (!ok) { add_result("shared_map_unhealed_corruption", "fail", "setup write failed"); cfs_storage_teardown(&fx); return; } /* Flip one byte of block 1's row: non-zero content, bad entry_crc. */ { int fd = BasicOpenFile(fx.map_path, O_RDWR | PG_BINARY); char b; if (fd < 0 || pg_pread(fd, &b, 1, CFS_MAP_HEADER_SIZE + 1 * CFS_MAP_ENTRY_SIZE) != 1) ok = false; else { b ^= (char) 0xFF; if (pg_pwrite(fd, &b, 1, CFS_MAP_HEADER_SIZE + 1 * CFS_MAP_ENTRY_SIZE) != 1) ok = false; } if (fd >= 0) close(fd); } if (!ok) { add_result("shared_map_unhealed_corruption", "fail", "could not corrupt the map row"); cfs_storage_teardown(&fx); return; } /* * Authoritative path: the pool is forced unallocatable, so the read * resolves through the scratch segment. The healthy block 0 still reads; * the corrupted block 1 returns CORRUPT instead of a zero page. */ cfs_test_pool_block_victim = true; lazy = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP); if (lazy == NULL) ok = false; else { /* * The quarantine is per BLOCK: the healthy block 0 of the same * segment still reads, while block 1 (whose row is torn and has no * covering journal record) fails through the corruption report. */ if (cfs_read_page_cached(lazy, 0, (char *) back) == CFS_STORAGE_OK) auth0_ok = true; if (cfs_read_page_cached(lazy, 1, (char *) back) == CFS_STORAGE_CORRUPT) auth1_ok = true; cfs_close(lazy); lazy = NULL; } cfs_test_pool_block_victim = false; /* * Pool path: the segment loads with the corrupt row, is flagged and never * serves - every read of the block fails again (the repeated read is the * regression: a published segment used to hand out a zeroed page from the * second read on). */ cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); lazy = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP); if (lazy == NULL) ok = false; else { if (cfs_read_page_cached(lazy, 0, (char *) back) == CFS_STORAGE_OK) pool0_ok = true; if (cfs_read_page_cached(lazy, 1, (char *) back) == CFS_STORAGE_CORRUPT) pool1_ok = true; if (cfs_read_page_cached(lazy, 1, (char *) back) == CFS_STORAGE_CORRUPT) pool1_again_ok = true; if (!cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 1, &out, NULL)) lookup_ok = true; cfs_close(lazy); } ok = ok && auth0_ok && auth1_ok && pool0_ok && pool1_ok && pool1_again_ok && lookup_ok; snprintf(detail, sizeof(detail), "block quarantined: auth %d/%d pool %d/%d again %d lookup %d", (int) auth0_ok, (int) auth1_ok, (int) pool0_ok, (int) pool1_ok, (int) pool1_again_ok, (int) lookup_ok); add_result("shared_map_unhealed_corruption", ok ? "ok" : "fail", detail); cfs_map_cache_unpin(fx.rl, MAIN_FORKNUM); cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_storage_teardown(&fx); } /* * E4: cfs_shared_map_invalidate_relation must walk only the segments of * the requested relation (the per-relation index), not the whole pool. Two * relations share the pool; invalidating one drops exactly its segments, * leaves the other resident and is idempotent. */ static void test_shared_map_invalidate_index(void) { RelFileLocatorBackend rlA = cfs_shmem_test_locator(800855); RelFileLocatorBackend rlB = cfs_shmem_test_locator(800856); CfsMapEntry in; CfsMapEntry out; uint64 capacity = 0; uint64 gen; uint64 ev0 = 0; uint64 ev1 = 0; uint64 ev2 = 0; char detail[160]; bool ok = true; int i; cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM); cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity < 8) { add_result("shared_map_invalidate_index", "skip", "pool too small"); return; } cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); gen = cfs_map_cache_get_generation(rlA, MAIN_FORKNUM); /* * Four segments per relation. Each B segment is looked up right after * its store so the clock sweep keeps it while A is filled. */ for (i = 0; i < 4; i++) { BlockNumber blk = (BlockNumber) (1000 + i) * CFS_MAP_SEGMENT_BLOCKS; if (!cfs_shared_map_store(rlB, MAIN_FORKNUM, blk, &in, gen) || !cfs_shared_map_lookup(rlB, MAIN_FORKNUM, blk, &out, NULL)) ok = false; } for (i = 0; i < 4; i++) if (!cfs_shared_map_store(rlA, MAIN_FORKNUM, (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS, &in, gen)) ok = false; cfs_shared_map_stats(NULL, NULL, &ev0, NULL); cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM); cfs_shared_map_stats(NULL, NULL, &ev1, NULL); /* Exactly A's four segments were evicted. */ if (ok && ev1 - ev0 != 4) ok = false; /* A is gone, B is untouched. */ if (ok && cfs_shared_map_lookup(rlA, MAIN_FORKNUM, 0, &out, NULL)) ok = false; if (ok && !cfs_shared_map_lookup(rlB, MAIN_FORKNUM, (BlockNumber) 1000 * CFS_MAP_SEGMENT_BLOCKS, &out, NULL)) ok = false; /* A second invalidation finds nothing and evicts nothing. */ cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM); cfs_shared_map_stats(NULL, NULL, &ev2, NULL); if (ok && ev2 != ev1) ok = false; cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "relation index %s", ok ? "scoped the invalidation" : "touched or missed segments"); add_result("shared_map_invalidate_index", ok ? "ok" : "fail", detail); } /* * The clock-sweep usage counter belongs to the id, not to the descriptor * instance: after eviction/invalidation the id must start cold again, or a * recycled segment inherits a stale "hot" count and distorts victim * selection. */ static void test_shared_map_usage_reset(void) { #ifdef USE_ASSERT_CHECKING RelFileLocatorBackend rl = cfs_shmem_test_locator(800880); CfsMapEntry in; uint64 capacity = 0; int id; uint32 usage_before; uint32 usage_after; char detail[160]; bool ok = true; int i; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_usage_reset", "skip", "pool disabled"); return; } cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 0, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM))) ok = false; for (i = 0; ok && i < CFS_MAP_SEG_USAGE_MAX + 2; i++) if (!cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &in, NULL)) ok = false; id = cfs_shared_map_test_segment_id(rl, MAIN_FORKNUM, 0); usage_before = cfs_shared_map_test_desc_usage(id); cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); usage_after = cfs_shared_map_test_desc_usage(id); if (ok && usage_before != CFS_MAP_SEG_USAGE_MAX) ok = false; if (ok && usage_after != 0) ok = false; /* The decrement is "only if positive", so a cold id cannot underflow. */ cfs_shared_map_test_set_desc_usage(id, 1); cfs_shared_map_test_dec_desc_usage(id); cfs_shared_map_test_dec_desc_usage(id); if (ok && cfs_shared_map_test_desc_usage(id) != 0) ok = false; snprintf(detail, sizeof(detail), "usage reset %u -> %u, no underflow", usage_before, usage_after); add_result("shared_map_usage_reset", ok ? "ok" : "fail", detail); #else add_result("shared_map_usage_reset", "skip", "requires assertions"); #endif } /* * DROP DATABASE must drop only the segments of the dropped database. The * keys carry dbOid, so a full pool reset would throw away every other * database's warm segments for no correctness gain. */ static void test_shared_map_drop_database(void) { RelFileLocatorBackend rlA = cfs_shmem_test_locator(800870); RelFileLocatorBackend rlB = cfs_shmem_test_locator(800871); CfsMapEntry in; CfsMapEntry out; uint64 in_use0; uint64 in_use1; uint64 capacity = 0; uint64 genA; uint64 genB; char detail[160]; bool ok = true; int i; Oid dbA = 900001; Oid dbB = 900002; rlA.locator.dbOid = dbA; rlB.locator.dbOid = dbB; cfs_shared_map_invalidate_relation(rlA, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM); cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity < 4) { add_result("shared_map_drop_database", "skip", "pool too small"); return; } cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); genA = cfs_map_cache_get_generation(rlA, MAIN_FORKNUM); genB = cfs_map_cache_get_generation(rlB, MAIN_FORKNUM); for (i = 0; i < 2; i++) { BlockNumber blk = (BlockNumber) i * CFS_MAP_SEGMENT_BLOCKS; if (!cfs_shared_map_store(rlA, MAIN_FORKNUM, blk, &in, genA)) ok = false; if (!cfs_shared_map_store(rlB, MAIN_FORKNUM, blk, &in, genB)) ok = false; if (!cfs_shared_map_lookup(rlA, MAIN_FORKNUM, blk, &out, NULL)) ok = false; if (!cfs_shared_map_lookup(rlB, MAIN_FORKNUM, blk, &out, NULL)) ok = false; } cfs_shared_map_stats(&in_use0, NULL, NULL, NULL); cfs_drop_database_caches(dbA); cfs_shared_map_stats(&in_use1, NULL, NULL, NULL); if (in_use1 != in_use0 - 2) ok = false; if (cfs_shared_map_lookup(rlA, MAIN_FORKNUM, 0, &out, NULL)) ok = false; if (!cfs_shared_map_lookup(rlB, MAIN_FORKNUM, 0, &out, NULL)) ok = false; if (!cfs_shared_map_lookup(rlB, MAIN_FORKNUM, CFS_MAP_SEGMENT_BLOCKS, &out, NULL)) ok = false; cfs_shared_map_invalidate_relation(rlB, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "drop database %s", ok ? "kept other databases" : "reset the whole pool"); add_result("shared_map_drop_database", ok ? "ok" : "fail", detail); } /* * C2: a segment published from the .cfsmap snapshot without a journal * replay must be invisible to lookups until the sync catches it up. The * snapshot holds v1, the journal holds both v1 and the newer v2; after the * read path syncs the segment, v2 must be served (not v1, not a zero page). */ static void test_shared_map_publish_unsynced(void) { #ifdef USE_ASSERT_CHECKING CfsStorageFixture fx; CfsRelation *h; CfsRelation *lazy; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsMapEntry expected; CfsMapEntry out; uint64 capacity = 0; char cfp_path[MAXPGPATH]; char map_path[MAXPGPATH]; char jrn_path[MAXPGPATH]; char detail[160]; bool ok = true; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_publish_unsynced", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "segunsynced"); if (fx.dir == NULL) { add_result("shared_map_publish_unsynced", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800795; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path)); strlcpy(map_path, fx.map_path, sizeof(map_path)); strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path)); h = cfs_storage_open_new(&fx); /* Snapshot v1, then a journal-only v2 that the snapshot does not know. */ cfs_test_fill_page(page, 0x41); if (cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok && cfs_map_save_snapshot(h) != CFS_STORAGE_OK) ok = false; cfs_test_fill_page(page, 0x42); if (ok && cfs_write_page(h, 0, (const char *) page, &opts) != CFS_STORAGE_OK) ok = false; if (ok) expected = h->map[0]; cfs_close(h); lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; if (ok && !cfs_shared_map_test_publish_unsynced(lazy, 0)) ok = false; /* C2: the unsynced segment must be treated as a miss. */ if (ok && cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &out, NULL)) ok = false; /* The miss path syncs the segment and must serve the journal version. */ if (ok) { cfs_test_fill_page(page, 0x42); if (cfs_read_page_cached(lazy, 0, (char *) back) != CFS_STORAGE_OK || memcmp(back, page, TEST_BLCKSZ) != 0) ok = false; } /* After the sync the entry is visible and carries the newer offset. */ if (ok && (!cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 0, &out, NULL) || out.physical_offset != expected.physical_offset || out.generation != expected.generation)) ok = false; if (lazy) cfs_close(lazy); cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "unsynced segment %s", ok ? "served only after sync" : "leaked or served a stale entry"); add_result("shared_map_publish_unsynced", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); #else add_result("shared_map_publish_unsynced", "skip", "requires assertions"); #endif } /* * I4: a competitor merges the snapshot between ensure()'s buffer load and * its segment phase. The descriptor is then already loaded, so ensure() * must report success instead of pretending it lost the race and sending * the reader to the authoritative path. */ static void test_shared_map_merge_race(void) { #ifdef USE_ASSERT_CHECKING CfsStorageFixture fx; CfsRelation *lazy; CfsRelation *h; CfsMapEntry in; uint64 capacity = 0; uint64 gen; char cfp_path[MAXPGPATH]; char map_path[MAXPGPATH]; char jrn_path[MAXPGPATH]; char detail[160]; bool ok = true; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_merge_race", "skip", "pool disabled"); return; } cfs_storage_setup(&fx, "segmergerace"); if (fx.dir == NULL) { add_result("shared_map_merge_race", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800796; cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); strlcpy(cfp_path, fx.cfp_path, sizeof(cfp_path)); strlcpy(map_path, fx.map_path, sizeof(map_path)); strlcpy(jrn_path, fx.jrn_path, sizeof(jrn_path)); /* Materialise the sidecars so the lazy handle below can open them. */ h = cfs_storage_open_new(&fx); if (h == NULL) ok = false; else cfs_close(h); /* * A store-created segment holds only journaled entries: its snapshot part * is not loaded yet, which is what sends ensure() through the merge path * the hook races with. */ gen = cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM); cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); if (!cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 0, &in, gen)) ok = false; lazy = cfs_test_open_lazy(fx.rl, cfp_path, map_path, jrn_path); if (lazy == NULL) ok = false; if (ok && !cfs_shared_map_test_merge_race(lazy, 0)) ok = false; if (ok) { int ensure_rc; cfs_append_lock_acquire(fx.rl, MAIN_FORKNUM, LW_SHARED); ensure_rc = cfs_shared_map_ensure(lazy, 0); cfs_append_lock_release(fx.rl, MAIN_FORKNUM); if (ensure_rc != CFS_STORAGE_OK) ok = false; } if (lazy) cfs_close(lazy); cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); snprintf(detail, sizeof(detail), "concurrent merge %s", ok ? "reported as success" : "misreported as a miss"); add_result("shared_map_merge_race", ok ? "ok" : "fail", detail); cfs_storage_teardown(&fx); #else add_result("shared_map_merge_race", "skip", "requires assertions"); #endif } /* * I9: an in-flight reservation left behind by a backend that died before * publishing its segment must not block the next store of the same key and * must not leak a pool segment (regression guard; reaping was added with * the reservation table itself). */ static void test_shared_map_orphan_reservation(void) { #ifdef USE_ASSERT_CHECKING RelFileLocatorBackend rl = cfs_shmem_test_locator(800820); CfsMapEntry in; CfsMapEntry out; uint64 in_use0 = 0; uint64 in_use1 = 0; uint64 in_use2 = 0; uint64 capacity = 0; uint64 gen; int id0 = -1; int id1 = -1; char detail[160]; bool ok = true; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_shared_map_stats(&in_use0, NULL, NULL, &capacity); if (capacity == 0) { add_result("shared_map_orphan_reservation", "skip", "pool disabled"); return; } cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); gen = cfs_map_cache_get_generation(rl, MAIN_FORKNUM); id0 = cfs_shared_map_test_reserve_orphan(rl, MAIN_FORKNUM, 0); if (id0 < 0) ok = false; if (ok && !cfs_shared_map_store(rl, MAIN_FORKNUM, 0, &in, gen)) ok = false; if (ok) { id1 = cfs_shared_map_test_segment_id(rl, MAIN_FORKNUM, 0); if (id1 != id0) ok = false; } if (ok && !cfs_shared_map_lookup(rl, MAIN_FORKNUM, 0, &out, NULL)) ok = false; else if (ok && out.physical_offset != in.physical_offset) ok = false; /* The store owns exactly one new segment: no leak, no double mapping. */ cfs_shared_map_stats(&in_use1, NULL, NULL, NULL); if (ok && in_use1 != in_use0 + 1) ok = false; cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_shared_map_stats(&in_use2, NULL, NULL, NULL); if (ok && in_use2 != in_use0) ok = false; snprintf(detail, sizeof(detail), "orphan reservation %s (id %d -> %d)", ok ? "reused the same id without a leak" : "blocked or leaked a segment", id0, id1); add_result("shared_map_orphan_reservation", ok ? "ok" : "fail", detail); #else add_result("shared_map_orphan_reservation", "skip", "requires assertions"); #endif } static void test_shmem_invalidate(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800500); CfsMapEntry in; CfsMapEntry out; uint64 capacity = 0; char detail[160]; bool ok = true; cfs_shared_map_stats(NULL, NULL, NULL, &capacity); if (capacity == 0) { add_result("shmem_invalidate", "skip", "pool disabled"); return; } cfs_map_cache_pin(rl, MAIN_FORKNUM); cfs_map_entry_init(&in); in.physical_offset = 8192; in.compressed_size = 1000; in.generation = 1; cfs_map_entry_crc_set(&in); if (!cfs_shared_map_store(rl, MAIN_FORKNUM, 7, &in, cfs_map_cache_get_generation(rl, MAIN_FORKNUM))) ok = false; if (!cfs_shared_map_lookup(rl, MAIN_FORKNUM, 7, &out, NULL)) ok = false; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); if (cfs_shared_map_lookup(rl, MAIN_FORKNUM, 7, &out, NULL)) ok = false; /* entry must be gone after invalidation */ snprintf(detail, sizeof(detail), "invalidate %s", ok ? "ok" : "failed"); add_result("shmem_invalidate", ok ? "ok" : "fail", detail); } /* * Mirror of the static cfs_cache_hash_rel() in cfs_shmem.c, used to pick * synthetic locators that hash into the same metadata partition. Must be * kept in sync with the production hash. */ static uint32 test_cache_hash_rel(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 h; h = rlocator.locator.spcOid; h = (h << 5) - h + rlocator.locator.dbOid; h = (h << 5) - h + rlocator.locator.relNumber; h = (h << 5) - h + (uint32) rlocator.backend; h = (h << 5) - h + (uint32) forknum; return (h == 0) ? 1 : h; } /* * Metadata cache overflow: fill one metadata partition with dirty * (non-evictable) relations, then verify that a further relation hashing * to the same partition is rejected with a hard ERROR (no silent skip, * no overflow counter — the relation cannot operate without its metadata * slot, which now also carries the per-relation append lock). */ static void test_shmem_meta_overflow(void) { RelFileLocatorBackend rls[CFS_MAP_CACHE_RELS_PER_PART + 1]; CfsEffectiveOptions opts; uint32 target_part = 0; int found = 0; bool raised = false; bool ok = true; Oid rn; int i; for (rn = 810000; found <= CFS_MAP_CACHE_RELS_PER_PART && rn < 815000; rn++) { RelFileLocatorBackend rl = cfs_shmem_test_locator(rn); uint32 part = test_cache_hash_rel(rl, MAIN_FORKNUM) & (CFS_MAP_CACHE_NUM_PARTITIONS - 1); if (found == 0) target_part = part; if (part == target_part) rls[found++] = rl; } opts.is_cfs = true; opts.algorithm = CFS_ALGORITHM_LZ4; opts.level = 3; opts.min_gain_bytes = 512; /* Occupy every slot of the partition with dirty metadata. */ for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++) { cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); cfs_publish_options(rls[i], MAIN_FORKNUM, &opts); cfs_map_cache_set_meta(rls[i], MAIN_FORKNUM, 10); } /* * One more relation hashing to the same partition: the slot pool is * exhausted (all slots dirty), so cfs_meta_get_or_create must raise ERROR * instead of silently skipping the relation. */ PG_TRY(); { cfs_publish_options(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM, &opts); } PG_CATCH(); { ErrorData *edata; MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); edata = CopyErrorData(); raised = (edata->sqlerrcode == ERRCODE_CONFIGURATION_LIMIT_EXCEEDED); MemoryContextSwitchTo(oldcontext); FlushErrorState(); } PG_END_TRY(); if (!raised) ok = false; /* Clean up: make the slots evictable again and drop them. */ for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++) { cfs_map_cache_clear_dirty(rls[i], MAIN_FORKNUM); cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); } add_result("shmem_meta_overflow", ok ? "ok" : "fail", ok ? "excess relation rejected with ERROR" : "overflow not handled"); } /* * QDB-1516 T1: hash chains under collisions. Engineer many distinct keys * that share one partition (the low hash bits collide), run far past the * partition's slot capacity so the chains grow, slots evict and get * re-created, and verify find / get_or_create / eviction / invalidation * keep answering with exactly the right slot on both the metadata and the * statistics side. The LRU order within the partition is deterministic: * every key is touched exactly once, in index order, so after the loop the * partition must hold the highest-indexed keys and none of the rest. */ #define CHAIN_TEST_KEYS 64 static void test_shmem_chains(void) { RelFileLocatorBackend rls[CHAIN_TEST_KEYS]; CfsStatsSnapshot snap; uint32 target_part = 0; uint64 nblocks = 0; int found = 0; int meta_cap; int stats_cap; int i; bool ok = true; Oid rn; /* * Brute-force relfilenodes hashing into one partition, exactly like * test_shmem_meta_overflow() does (the hash mirror above must stay in * sync with cfs_cache_hash_rel()). */ for (rn = 840000; found < CHAIN_TEST_KEYS && rn < 860000; rn++) { RelFileLocatorBackend rl = cfs_shmem_test_locator(rn); uint32 part = test_cache_hash_rel(rl, MAIN_FORKNUM) & (CFS_MAP_CACHE_NUM_PARTITIONS - 1); if (found == 0) target_part = part; if (part == target_part) rls[found++] = rl; } if (found < CHAIN_TEST_KEYS) { add_result("shmem_chains", "fail", "not enough colliding keys"); return; } /* Idempotent across runs: drop any state of these keys first. */ for (i = 0; i < CHAIN_TEST_KEYS; i++) { cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); cfs_stats_reset(rls[i], MAIN_FORKNUM); } /* Fill the partition far past its metadata capacity. */ for (i = 0; i < CHAIN_TEST_KEYS; i++) cfs_map_cache_set_meta(rls[i], MAIN_FORKNUM, (uint64) (1000 + i)); meta_cap = cfs_map_cache_rels_per_partition; /* The most recent key is served through its chain. */ if (!cfs_map_cache_get_nblocks(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM, &nblocks) || nblocks != (uint64) (1000 + CHAIN_TEST_KEYS - 1)) ok = false; /* * With more keys than slots, the earliest keys were evicted (LRU) and * must not be found through anybody's chain. */ if (ok && CHAIN_TEST_KEYS > meta_cap && cfs_map_cache_get_nblocks(rls[0], MAIN_FORKNUM, &nblocks)) ok = false; /* * A long-evicted key is found again after re-creation (the chain link * of the recycled slot must follow the new key, not the victim's). * The re-created slot evicts the oldest survivor instead. */ cfs_map_cache_set_meta(rls[20], MAIN_FORKNUM, 5000); if (!cfs_map_cache_get_nblocks(rls[20], MAIN_FORKNUM, &nblocks) || nblocks != 5000) ok = false; if (ok && !cfs_map_cache_get_nblocks(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM, &nblocks)) ok = false; /* Invalidation removes exactly its own slot, chain included. */ cfs_map_cache_invalidate(rls[20], MAIN_FORKNUM); if (cfs_map_cache_get_nblocks(rls[20], MAIN_FORKNUM, &nblocks)) ok = false; if (ok && !cfs_map_cache_get_nblocks(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM, &nblocks)) ok = false; /* The statistics domain: same collision load, shared-lock accounting. */ for (i = 0; i < CHAIN_TEST_KEYS; i++) cfs_stats_count_read(rls[i], MAIN_FORKNUM, 100); stats_cap = cfs_stats_slots_per_partition; if (!cfs_stats_snapshot(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM, &snap) || snap.read_count != 1 || snap.decompress_count != 1) ok = false; if (ok && CHAIN_TEST_KEYS > stats_cap && cfs_stats_snapshot(rls[0], MAIN_FORKNUM, &snap)) ok = false; /* * Reset clears exactly one relation's counters. rls[20] was evicted * by the load above, so re-create its slot first: the reset must then * zero it while the untouched neighbor keeps its counter. */ cfs_stats_count_read(rls[20], MAIN_FORKNUM, 100); cfs_stats_reset(rls[20], MAIN_FORKNUM); if (!cfs_stats_snapshot(rls[20], MAIN_FORKNUM, &snap) || snap.read_count != 0 || snap.crc_failures != 0 || snap.last_reset == 0) ok = false; if (ok && (!cfs_stats_snapshot(rls[CHAIN_TEST_KEYS - 1], MAIN_FORKNUM, &snap) || snap.read_count != 1)) ok = false; /* Cleanup: leave no slot of these keys behind. */ for (i = 0; i < CHAIN_TEST_KEYS; i++) { cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); cfs_stats_reset(rls[i], MAIN_FORKNUM); } add_result("shmem_chains", ok ? "ok" : "fail", ok ? "64 colliding keys, chains keep exact slots" : "chain find/evict/invalidate mismatch"); } /* * Pin reaper: a slot pin left behind by a process that died hard (the * test hook records one for an already-dead pid) must not exhaust the * partition - when no slot is reclaimable, the dead owner's pins are * reaped and the next pin succeeds instead of raising the overflow * error. */ static void test_shmem_pin_reaper(void) { RelFileLocatorBackend rls[CFS_MAP_CACHE_RELS_PER_PART + 1]; char detail[160] = {0}; uint32 target_part = 0; bool raised = false; bool ok = true; Oid rn; int found = 0; int i; for (rn = 820000; found <= CFS_MAP_CACHE_RELS_PER_PART && rn < 825000; rn++) { RelFileLocatorBackend rl = cfs_shmem_test_locator(rn); uint32 part = test_cache_hash_rel(rl, MAIN_FORKNUM) & (CFS_MAP_CACHE_NUM_PARTITIONS - 1); if (found == 0) target_part = part; if (part == target_part) rls[found++] = rl; } for (i = 0; i < found; i++) cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); /* rls[0]: one orphaned pin from a dead process. */ if (cfs_map_cache_test_pin_orphan(rls[0], MAIN_FORKNUM) != (int) target_part) { ok = false; snprintf(detail, sizeof(detail), "pin reaper failed at orphan1"); } /* Live pins fill the rest of the partition. */ for (i = 1; i < CFS_MAP_CACHE_RELS_PER_PART; i++) cfs_map_cache_pin(rls[i], MAIN_FORKNUM); /* * One more relation of the same partition: every slot is pinned, but one * pin belongs to a dead process - the pin must succeed after the reaper * returns that slot, not raise the overflow error. */ PG_TRY(); { cfs_map_cache_pin(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM); } PG_CATCH(); { ErrorData *edata; MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); edata = CopyErrorData(); raised = (edata->sqlerrcode == ERRCODE_CONFIGURATION_LIMIT_EXCEEDED); MemoryContextSwitchTo(oldcontext); FlushErrorState(); } PG_END_TRY(); if (raised) { ok = false; snprintf(detail, sizeof(detail), "pin reaper failed at overflow"); } /* * Reaper invariants, checked deterministically in place of the * two-backend race the reaper guards against (I1/I2 name the broken one * in the detail line): * * I1. Idempotence: a second run must find nothing, so two reapers racing * for one record can never double-subtract from a slot. I2. Live owners * keep their pins: reaping an orphan recorded for a slot this process * also pins live must leave the live pin counted (2 -> 1), and unpinning * it must bring the refcount to zero. A reaper that wrongly swallowed * the live pin shows up as 2 -> 0, a no-op reaper as 2 -> 2. */ { const char *inv = ""; char invbuf[48]; int rc_a; int rc; if (cfs_map_cache_test_reap_dead_pins()) inv = "I1"; /* Free one slot so the next orphan can own a real slot again. */ cfs_map_cache_unpin(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM); if (cfs_map_cache_test_pin_orphan(rls[0], MAIN_FORKNUM) != (int) target_part) inv = "orphan"; cfs_map_cache_pin(rls[0], MAIN_FORKNUM); rc_a = cfs_map_cache_test_slot_refcount(rls[0], MAIN_FORKNUM); (void) cfs_map_cache_test_reap_dead_pins(); rc = cfs_map_cache_test_slot_refcount(rls[0], MAIN_FORKNUM); if (rc_a != 2 || rc != 1) { snprintf(invbuf, sizeof(invbuf), "live-refcount %d->%d", rc_a, rc); inv = invbuf; } cfs_map_cache_unpin(rls[0], MAIN_FORKNUM); if (cfs_map_cache_test_slot_refcount(rls[0], MAIN_FORKNUM) != 0) inv = "zero-refcount"; if (inv[0] != '\0') { ok = false; snprintf(detail, sizeof(detail), "pin reaper failed at %s", inv); } } /* Cleanup: drop the live pins and every slot of the partition. */ for (i = 1; i <= CFS_MAP_CACHE_RELS_PER_PART; i++) cfs_map_cache_unpin(rls[i], MAIN_FORKNUM); for (i = 0; i < found; i++) cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); if (ok) snprintf(detail, sizeof(detail), "pin reaper ok"); else if (detail[0] == '\0') snprintf(detail, sizeof(detail), "pin reaper failed"); add_result("shmem_pin_reaper", ok ? "ok" : "fail", detail); } /* * Post-commit publication must degrade instead of raising ERROR: after the * durable commit an ERROR is no longer abortable and would escalate to * PANIC ("cannot abort transaction ... it was already committed"). With * every slot of the partition dirty, the postcommit publication warns, * skips the entry, and leaves no slot behind; once the partition has room * again, the same publication goes through. */ static void test_shmem_publish_postcommit_overflow(void) { RelFileLocatorBackend rls[CFS_MAP_CACHE_RELS_PER_PART + 1]; CfsEffectiveOptions opts; CfsEffectiveOptions cached; uint32 target_part = 0; int found = 0; bool ok = true; Oid rn; int i; for (rn = 820000; found <= CFS_MAP_CACHE_RELS_PER_PART && rn < 825000; rn++) { RelFileLocatorBackend rl = cfs_shmem_test_locator(rn); uint32 part = test_cache_hash_rel(rl, MAIN_FORKNUM) & (CFS_MAP_CACHE_NUM_PARTITIONS - 1); if (found == 0) target_part = part; if (part == target_part) rls[found++] = rl; } opts.is_cfs = true; opts.algorithm = CFS_ALGORITHM_LZ4; opts.level = 3; opts.min_gain_bytes = 512; /* Occupy every slot of the partition with dirty metadata. */ for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++) { cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); cfs_publish_options(rls[i], MAIN_FORKNUM, &opts); cfs_map_cache_set_meta(rls[i], MAIN_FORKNUM, 10); } /* * The postcommit publication for one more relation of the same partition * must not raise: the WARNING path skips the entry, so no slot may appear * for it. */ cfs_publish_options_postcommit(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM, &opts); if (cfs_get_options(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM, &cached)) ok = false; /* Clean up the partition: the same publication now succeeds. */ for (i = 0; i < CFS_MAP_CACHE_RELS_PER_PART; i++) { cfs_map_cache_clear_dirty(rls[i], MAIN_FORKNUM); cfs_map_cache_invalidate(rls[i], MAIN_FORKNUM); } cfs_publish_options_postcommit(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM, &opts); if (!cfs_get_options(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM, &cached) || cached.level != opts.level || !cached.is_cfs) ok = false; cfs_map_cache_invalidate(rls[CFS_MAP_CACHE_RELS_PER_PART], MAIN_FORKNUM); add_result("shmem_publish_postcommit_overflow", ok ? "ok" : "fail", ok ? "post-commit overflow degraded to a WARNING and a skip" : "post-commit overflow not tolerated"); } /* * Truncate / invalidate of the cached relation metadata: the metadata slot * must be updated exactly once, under its own partition lock, and the * cached logical size must shrink while the relation options survive. */ static void test_shmem_truncate_meta(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800600); CfsEffectiveOptions opts; CfsEffectiveOptions out_opts; uint64 nblocks = 0; uint64 gen_before = 0; bool ok = true; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); opts.is_cfs = true; opts.algorithm = CFS_ALGORITHM_LZ4; opts.level = 3; opts.min_gain_bytes = 512; cfs_map_cache_pin(rl, MAIN_FORKNUM); cfs_publish_options(rl, MAIN_FORKNUM, &opts); cfs_map_cache_set_meta(rl, MAIN_FORKNUM, 100); gen_before = cfs_map_cache_get_generation(rl, MAIN_FORKNUM); cfs_map_cache_truncate(rl, MAIN_FORKNUM, 40); /* Logical size shrank ... */ if (!cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks) || nblocks != 40) ok = false; /* ... the generation was bumped (the truncate/compaction marker) ... */ if (cfs_map_cache_get_generation(rl, MAIN_FORKNUM) == gen_before) ok = false; /* ... and the relation options survived the truncate. */ if (!cfs_get_options(rl, MAIN_FORKNUM, &out_opts) || !out_opts.is_cfs) ok = false; /* Invalidate drops the metadata slot entirely. */ cfs_map_cache_invalidate(rl, MAIN_FORKNUM); if (cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks)) ok = false; cfs_map_cache_release_relation(rl, MAIN_FORKNUM); add_result("shmem_truncate_meta", ok ? "ok" : "fail", ok ? "truncate shrank meta, invalidate dropped it" : "truncate/invalidate metadata mishandled"); } /* * Duplicate-key hardening: after an LRU/truncate "hole" appears in a cache * partition before an existing entry, updating that entry must reuse its * current slot rather than insert a second copy into the hole. Observable * through the eviction counter: with a duplicate the partition looks full * and the next insert of a new key evicts; without it the hole absorbs the * new key and no eviction happens. */ /* * Generation check on cache hit: a cached entry published before a * truncation/compaction generation bump must not be served from the cache. * A page is written through the cached path (publishing v1), then rewritten * directly (v2, bypassing the shared cache); after a generation bump the * cached read must return v2, not the stale cached v1. */ static void test_shmem_generation_check(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char page_v1[TEST_BLCKSZ]; unsigned char page_v2[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); bool ok = true; cfs_storage_setup(&fx, "gencheck"); if (fx.dir == NULL) { add_result("shmem_generation_check", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800720; cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs = cfs_storage_open_new(&fx); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); /* v1 through the cached path: published into the shared cache. */ cfs_test_fill_page(page_v1, 0x31); if (cfs_write_page_cached(cfs, 5, (const char *) page_v1, &opts) != 0) ok = false; /* v2 directly: journal + local map move on, the segment keeps v1. */ cfs_test_fill_page(page_v2, 0x32); if (ok && cfs_write_page(cfs, 5, (const char *) page_v2, &opts) != 0) ok = false; /* * The direct write bypassed the segment pool (single-writer storage API); * drop the relation's resident segments the way a truncate does, so the * next read re-resolves them through the journal delta. */ cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); /* The read must re-resolve through the journal and serve v2. */ if (ok && (cfs_read_page_cached(cfs, 5, (char *) back) != 0 || memcmp(page_v2, back, TEST_BLCKSZ) != 0)) ok = false; /* * Segment generation tag: a publication carries the publishing * generation, so a reader can reject a hit whose tag disagrees with its * handle's. A truncate bumps the relation generation (the * compaction/truncate swap marker) without dropping pool segments — the * surviving tag must then disagree with the live generation. */ { CfsMapEntry in; CfsMapEntry out; uint64 gen_before = 0; uint64 gen_after = 0; uint64 seg_gen = 0; gen_before = cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); /* * Publish the logical size the way the production write path does: * the pool serves only blocks below the slot's nblocks, and block 7 * is otherwise beyond the size published by the single cached write * of block 5. */ cfs_map_cache_set_meta(fx.rl, MAIN_FORKNUM, 8); cfs_map_entry_init(&in); in.physical_offset = 4096; in.compressed_size = 100; in.generation = 1; cfs_map_entry_crc_set(&in); if (!cfs_shared_map_store(fx.rl, MAIN_FORKNUM, 7, &in, cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM))) ok = false; if (ok && !cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 7, &out, &seg_gen)) ok = false; if (ok && seg_gen != gen_before) ok = false; cfs_map_cache_truncate(fx.rl, MAIN_FORKNUM, 8); gen_after = cfs_map_cache_get_generation(fx.rl, MAIN_FORKNUM); if (ok && gen_after == gen_before) ok = false; if (ok && seg_gen == gen_after) ok = false; /* stale tag would be served to current * readers */ } cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_close(cfs); add_result("shmem_generation_check", ok ? "ok" : "fail", ok ? "stale-generation hit rejected" : "stale entry served"); cfs_storage_teardown(&fx); } /* * crc_failures observability: a cache invalidation must NOT reset the * relation's statistics counters; only an explicit reset may clear them. */ static void test_shmem_crc_survives_invalidate(void) { RelFileLocatorBackend rl = cfs_shmem_test_locator(800730); CfsStatsSnapshot snap; bool ok = true; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); cfs_stats_reset(rl, MAIN_FORKNUM); cfs_stats_count_crc_failure(rl, MAIN_FORKNUM); if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap) || snap.crc_failures != 1) ok = false; /* Ordinary invalidation must leave the counter alive. */ cfs_map_cache_invalidate(rl, MAIN_FORKNUM); if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap) || snap.crc_failures != 1) ok = false; /* An explicit reset still clears it. */ cfs_stats_reset(rl, MAIN_FORKNUM); if (!cfs_stats_snapshot(rl, MAIN_FORKNUM, &snap) || snap.crc_failures != 0) ok = false; add_result("shmem_crc_survives_invalidate", ok ? "ok" : "fail", ok ? "crc_failures survives invalidate, reset clears" : "invalidate wiped crc_failures"); } /* Probe context + callback for cfs_for_each_cfs_relation(). */ typedef struct CfsEnumProbe { RelFileLocatorBackend target; bool found; } CfsEnumProbe; static void test_enum_probe_cb(RelFileLocatorBackend rlocator, ForkNumber forknum, void *arg) { CfsEnumProbe *probe = (CfsEnumProbe *) arg; if (forknum == MAIN_FORKNUM && rlocator.locator.spcOid == probe->target.locator.spcOid && rlocator.locator.dbOid == probe->target.locator.dbOid && rlocator.locator.relNumber == probe->target.locator.relNumber && rlocator.backend == probe->target.backend) probe->found = true; } /* * Point invalidation on CRC failure: a CRC error while reading one cached * block must drop only that block's cache entry. The cached entries of the * other blocks of the same relation and, crucially, the relation metadata * slot (which carries the policy fields — is_cfs included — and * dirty_checkpoint for checkpoint enumeration) must survive; a repeated * read must still detect the real on-disk corruption instead of masking it. */ static void test_shmem_crc_point_invalidate(void) { CfsStorageFixture fx; CfsRelation *cfs; unsigned char pages[3][TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; CfsWriteOptions opts = cfs_test_write_opts(); CfsEffectiveOptions popts; CfsMapEntry cached; CfsMapEntry out; CfsEnumProbe probe; uint64 nblocks = 0; uint64 in_use_before = 0; uint64 in_use_after = 0; uint64 evictions_before = 0; uint64 evictions_after = 0; int rc1 = CFS_STORAGE_OK; int rc2 = CFS_STORAGE_OK; int i; bool ok = true; cfs_storage_setup(&fx, "crc_point"); if (fx.dir == NULL) { add_result("shmem_crc_point_invalidate", "fail", "setup failed"); return; } fx.rl.locator.relNumber = 800740; cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); popts.is_cfs = true; popts.algorithm = CFS_ALGORITHM_LZ4; popts.level = 3; popts.min_gain_bytes = 512; cfs = cfs_storage_open_new(&fx); cfs_map_cache_pin(fx.rl, MAIN_FORKNUM); cfs_publish_options(fx.rl, MAIN_FORKNUM, &popts); /* Write three blocks through the cached path (publishes all three). */ for (i = 0; i < 3; i++) { cfs_test_fill_page(pages[i], (unsigned char) (0x40 + i)); if (cfs_write_page_cached(cfs, i, (const char *) pages[i], &opts) != 0) { ok = false; break; } } /* * Corrupt the .cfp payload of block 1's record: flip the first payload * byte so the payload CRC check in CfsDecompressPage() fails. */ if (ok) { int cfp_fd; unsigned char b; if (!cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 1, &cached, NULL)) ok = false; cfp_fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY); if (ok && cfp_fd >= 0 && pread(cfp_fd, &b, 1, (off_t) cached.physical_offset + CFS_BLOCK_HEADER_SIZE) == 1) { b ^= 0xFF; if (pwrite(cfp_fd, &b, 1, (off_t) cached.physical_offset + CFS_BLOCK_HEADER_SIZE) != 1) ok = false; } else ok = false; if (cfp_fd >= 0) close(cfp_fd); } /* The cached read of block 1 must fail with an integrity error. */ cfs_shared_map_stats(&in_use_before, NULL, &evictions_before, NULL); if (ok) rc1 = cfs_read_page_cached(cfs, 1, (char *) back); if (rc1 != CFS_STORAGE_CORRUPT) ok = false; cfs_shared_map_stats(&in_use_after, NULL, &evictions_after, NULL); if (in_use_after != in_use_before || evictions_after != evictions_before) ok = false; /* * The corrupt entry is gone, and the segment as a whole is now a * deliberate lookup miss until the read path replays the journal again * (journal_synced == false): a bare lookup of blocks 0 and 2 must not * serve them in that window either. Their survival is verified through * the read path below, which re-syncs the segment first. */ if (cfs_shared_map_lookup(fx.rl, MAIN_FORKNUM, 1, &out, NULL)) ok = false; /* The metadata slot must survive with its logical size ... */ if (!cfs_map_cache_get_nblocks(fx.rl, MAIN_FORKNUM, &nblocks) || nblocks != 3) ok = false; /* * ... and its CFS-ness marker (is_cfs), so checkpoint enumeration still * finds it. */ probe.target = fx.rl; probe.found = false; cfs_for_each_cfs_relation(test_enum_probe_cb, &probe); if (!probe.found) ok = false; /* * A repeat read must still report the real corruption (the miss path * re-reads through the authoritative map), not mask it. */ if (ok) rc2 = cfs_read_page_cached(cfs, 1, (char *) back); if (rc2 != CFS_STORAGE_CORRUPT) ok = false; /* The surviving entries must still serve the correct pages. */ if (ok && (cfs_read_page_cached(cfs, 0, (char *) back) != 0 || memcmp(pages[0], back, TEST_BLCKSZ) != 0)) ok = false; if (ok && (cfs_read_page_cached(cfs, 2, (char *) back) != 0 || memcmp(pages[2], back, TEST_BLCKSZ) != 0)) ok = false; /* * Full cleanup: drop every leftover entry of this relation so later tests * sharing the global cache observe a deterministic slot count. */ cfs_map_cache_invalidate(fx.rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(fx.rl, MAIN_FORKNUM); cfs_map_cache_release_relation(fx.rl, MAIN_FORKNUM); cfs_close(cfs); add_result("shmem_crc_point_invalidate", ok ? "ok" : "fail", ok ? "CRC error dropped one entry; meta slot survived" : "CRC error invalidated too much (or masked corruption)"); cfs_storage_teardown(&fx); } /* ================================================================ * .cfp segmentation (RELSEG_SIZE boundary rollover) * ================================================================ */ /* * Drive the append cursor of a synthetic relation past CFS_SEGMENT_SIZE * (1 GiB) with RAW records, then verify: * - the ".cfp.1" segment exists and the tail records landed in it; * - every block reads back correctly through the global->segment offset * translation, both before and after a close/reopen cycle; * - the streaming fsck validates the whole >1 GiB chain with no errors * (this is the regression test for the MaxAllocSize palloc failure: * the old whole-file checker died on files this size); * - the journal generation stream is monotonic for a single writer. */ static void test_segment_rollover(void) { CfsStorageFixture fx; CfsRelation *cfs; CfsWriteOptions opts = CFS_WRITE_OPTIONS_INIT; unsigned char page[TEST_BLCKSZ]; unsigned char back[TEST_BLCKSZ]; uint64 nwrites = 0; struct stat st; char *seg1_path; char detail[160]; bool ok = true; const char *why = ""; cfs_storage_setup(&fx, "segroll"); if (fx.dir == NULL) { add_result("segment_rollover", "fail", "setup failed"); return; } /* RAW records: deterministic 8232-byte records, no codec involved. */ opts.algorithm = CFS_ALGORITHM_RAW; opts.explicit_algorithm = true; opts.allow_raw_fallback = true; opts.min_gain_bytes = 1; cfs = cfs_storage_open_new(&fx); /* Fill block 0 past the segment boundary. */ cfs_test_fill_page(page, 0x55); while ((uint64) cfs->cfp_write_off < (uint64) CFS_SEGMENT_SIZE) { if (cfs_write_page(cfs, 0, (const char *) page, &opts) != CFS_STORAGE_OK) { ok = false; why = "write past boundary failed"; break; } nwrites++; } /* Blocks 1 and 2 land entirely inside segment 1. */ if (ok) { cfs_test_fill_page(page, 0x66); if (cfs_write_page(cfs, 1, (const char *) page, &opts) != CFS_STORAGE_OK || cfs_write_page(cfs, 2, (const char *) page, &opts) != CFS_STORAGE_OK) { ok = false; why = "write into segment 1 failed"; } } /* The chain must span two segments now. */ seg1_path = psprintf("%s.1", fx.cfp_path); if (ok && stat(seg1_path, &st) != 0) { ok = false; why = ".cfp.1 missing after rollover"; } /* The last version of block 0 crossed the boundary. */ if (ok && cfs->map[0].physical_offset < (uint64) CFS_SEGMENT_SIZE) { ok = false; why = "block 0 tail version not in segment 1"; } /* Read back through the boundary before and after reopen. */ if (ok) { cfs_test_fill_page(page, 0x55); if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) { ok = false; why = "block 0 read-back mismatch"; } cfs_test_fill_page(page, 0x66); if (ok && (cfs_read_page(cfs, 1, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0)) { ok = false; why = "block 1 read-back mismatch"; } } cfs_close(cfs); if (ok) { cfs = cfs_open_paths(fx.rl, MAIN_FORKNUM, fx.cfp_path, fx.map_path, fx.jrn_path, CFS_OPEN_RDWR); cfs_test_fill_page(page, 0x55); if (cfs_read_page(cfs, 0, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0) { ok = false; why = "block 0 mismatch after reopen"; } cfs_test_fill_page(page, 0x66); if (ok && (cfs_read_page(cfs, 2, (char *) back) != CFS_STORAGE_OK || memcmp(page, back, TEST_BLCKSZ) != 0)) { ok = false; why = "block 2 mismatch after reopen"; } /* * Persist a real map snapshot so the fsck below validates live * entries (including offsets beyond the segment boundary) rather than * the bare header of a freshly created fixture. */ if (ok && cfs_map_save_snapshot(cfs) != CFS_STORAGE_OK) { ok = false; why = "map snapshot failed"; } cfs_close(cfs); } snprintf(detail, sizeof(detail), "writes=%llu%s%s", (unsigned long long) nwrites, ok ? "" : " FAILED: ", ok ? "" : why); add_result("segment_rollover", ok ? "ok" : "fail", detail); /* * Streaming fsck over the >1 GiB chain. The old whole-file checker died * with "invalid memory alloc request size" here. */ { CfsFsckResult res; CfsFsckOptions fopts = CFS_FSCK_OPTIONS_DEFAULT; cfs_fsck_result_init(&res); cfs_fsck_map_file(fx.map_path, fx.cfp_path, &fopts, &res, NULL); cfs_fsck_journal_file(fx.jrn_path, &fopts, &res, NULL); cfs_fsck_cfp_file(fx.cfp_path, &fopts, &res); snprintf(detail, sizeof(detail), "errors=%llu gen_anomalies=%llu cfp_records=%llu", (unsigned long long) res.errors, (unsigned long long) res.generation_violations, (unsigned long long) res.cfp_records); add_result("segment_fsck_big_file", (res.errors == 0 && res.generation_violations == 0 && res.cfp_records == nwrites + 2) ? "ok" : "fail", detail); } pfree(seg1_path); cfs_storage_teardown(&fx); } /* * A live map entry with generation == 0 is corruption: every written entry * carries generation >= 1. */ static void test_fsck_generation_zero_map(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; CfsMapEntry e; char buf[CFS_MAP_HEADER_SIZE + CFS_MAP_ENTRY_SIZE]; CfsMapPrologue mhdr; if (!cfs_fsck_setup(&fx, "gen0map", FSCK_MODE_CLEAN)) { add_result("fsck_generation_zero_map", "fail", "setup failed"); return; } /* Rewrite the map with a zero-generation live entry. */ cfs_map_entry_init(&e); e.physical_offset = CFS_CFP_BASE_OFFSET; e.compressed_size = 100; e.generation = 0; cfs_map_entry_crc_set(&e); cfs_map_prologue_init(&mhdr); memcpy(buf, &mhdr, sizeof(mhdr)); memcpy(buf + sizeof(mhdr), &e, sizeof(e)); if (!cfs_test_write_file(fx.map_path, buf, sizeof(buf))) { add_result("fsck_generation_zero_map", "fail", "rewrite failed"); cfs_fsck_teardown(&fx); return; } cfs_fsck_result_init(&res); cfs_fsck_map_file(fx.map_path, fx.cfp_path, &opts, &res, NULL); snprintf(detail, sizeof(detail), "gen_violations=%llu errors=%llu", (unsigned long long) res.generation_violations, (unsigned long long) res.errors); add_result("fsck_generation_zero_map", (res.generation_violations > 0 && res.errors > 0) ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } /* * A journal UPDATE record with generation == 0 is corruption (hard error). */ static void test_fsck_generation_zero_journal(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; CfsMapEntry e; CfsJournalEntry je; CfsJournalFileHeader jhdr; char buf[CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE]; if (!cfs_fsck_setup(&fx, "gen0jrn", FSCK_MODE_CLEAN)) { add_result("fsck_generation_zero_journal", "fail", "setup failed"); return; } cfs_map_entry_init(&e); e.physical_offset = CFS_CFP_BASE_OFFSET; e.compressed_size = 100; e.generation = 0; cfs_map_entry_crc_set(&e); cfs_journal_entry_init_update(&je, 0, &e); cfs_journal_header_init(&jhdr); memcpy(buf, &jhdr, sizeof(jhdr)); memcpy(buf + sizeof(jhdr), &je, sizeof(je)); if (!cfs_test_write_file(fx.jrn_path, buf, sizeof(buf))) { add_result("fsck_generation_zero_journal", "fail", "rewrite failed"); cfs_fsck_teardown(&fx); return; } cfs_fsck_result_init(&res); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); snprintf(detail, sizeof(detail), "gen_violations=%llu errors=%llu", (unsigned long long) res.generation_violations, (unsigned long long) res.errors); add_result("fsck_generation_zero_journal", (res.generation_violations > 0 && res.errors > 0) ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } /* * A journal UPDATE record whose outer CRC is valid but whose embedded * new_entry is invalid (offset inside the reserved lead-in, or an * oversized compressed_size) must be flagged by fsck. */ static void test_fsck_journal_bad_new_entry(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; CfsMapEntry e; CfsJournalEntry je; CfsJournalFileHeader jhdr; char buf[CFS_JOURNAL_HEADER_SIZE + CFS_JOURNAL_ENTRY_SIZE]; bool ok = true; if (!cfs_fsck_setup(&fx, "badnewentry", FSCK_MODE_CLEAN)) { add_result("fsck_journal_bad_new_entry", "fail", "setup failed"); return; } /* Case 1: new_entry offset inside the reserved lead-in. */ cfs_map_entry_init(&e); e.physical_offset = 1; /* < CFS_CFP_BASE_OFFSET */ e.compressed_size = 100; e.generation = 1; cfs_map_entry_crc_set(&e); cfs_journal_entry_init_update(&je, 0, &e); cfs_journal_header_init(&jhdr); memcpy(buf, &jhdr, sizeof(jhdr)); memcpy(buf + sizeof(jhdr), &je, sizeof(je)); if (!cfs_test_write_file(fx.jrn_path, buf, sizeof(buf))) ok = false; if (ok) { cfs_fsck_result_init(&res); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); if (res.offset_out_of_range < 1 || res.errors < 1) ok = false; } /* * Case 2: new_entry with an oversized compressed_size (a field error). */ cfs_map_entry_init(&e); e.physical_offset = CFS_CFP_BASE_OFFSET; e.compressed_size = CFS_BLCKSZ + 1; /* invalid */ e.generation = 1; cfs_map_entry_crc_set(&e); cfs_journal_entry_init_update(&je, 0, &e); cfs_journal_header_init(&jhdr); memcpy(buf, &jhdr, sizeof(jhdr)); memcpy(buf + sizeof(jhdr), &je, sizeof(je)); if (!cfs_test_write_file(fx.jrn_path, buf, sizeof(buf))) ok = false; if (ok) { cfs_fsck_result_init(&res); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); /* * The entry CRC was recomputed, so this single record must be counted * as a field failure only, never as a CRC failure. */ if (res.field_failures < 1 || res.crc_failures != 0 || res.errors < 1) ok = false; } add_result("fsck_journal_bad_new_entry", ok ? "ok" : "fail", ok ? "bad new_entry offset/field flagged" : "bad new_entry not flagged"); cfs_fsck_teardown(&fx); } /* * A non-increasing generation sequence in the journal is flagged as an * anomaly but is not a hard error (multi-backend writers may legitimately * compute the generation from a stale local map). */ static void test_fsck_generation_regression(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; char detail[128]; CfsMapEntry e; CfsJournalEntry je; CfsJournalFileHeader jhdr; char buf[CFS_JOURNAL_HEADER_SIZE + 2 * CFS_JOURNAL_ENTRY_SIZE]; size_t off; if (!cfs_fsck_setup(&fx, "genregr", FSCK_MODE_CLEAN)) { add_result("fsck_generation_regression", "fail", "setup failed"); return; } cfs_map_entry_init(&e); e.physical_offset = CFS_CFP_BASE_OFFSET; e.compressed_size = 100; cfs_journal_header_init(&jhdr); memcpy(buf, &jhdr, sizeof(jhdr)); off = sizeof(jhdr); e.generation = 2; cfs_map_entry_crc_set(&e); cfs_journal_entry_init_update(&je, 0, &e); memcpy(buf + off, &je, sizeof(je)); off += sizeof(je); e.generation = 1; /* regression */ cfs_map_entry_crc_set(&e); cfs_journal_entry_init_update(&je, 0, &e); memcpy(buf + off, &je, sizeof(je)); off += sizeof(je); if (!cfs_test_write_file(fx.jrn_path, buf, off)) { add_result("fsck_generation_regression", "fail", "rewrite failed"); cfs_fsck_teardown(&fx); return; } cfs_fsck_result_init(&res); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); snprintf(detail, sizeof(detail), "gen_violations=%llu errors=%llu", (unsigned long long) res.generation_violations, (unsigned long long) res.errors); add_result("fsck_generation_regression", (res.generation_violations == 1 && res.errors == 0) ? "ok" : "fail", detail); cfs_fsck_teardown(&fx); } /* * Craft a .cfsjrn file holding 'nblocks' unique, valid UPDATE records * (blocknum 0..nblocks-1, generation 1). Lets the test drive the generation * tracker to its cap without a real workload. */ static bool cfs_test_write_journal(const char *path, uint32 nblocks) { CfsMapEntry e; CfsJournalEntry je; CfsJournalFileHeader jhdr; char *buf; size_t total = sizeof(jhdr) + (size_t) nblocks * CFS_JOURNAL_ENTRY_SIZE; size_t off; uint32 i; bool ok; cfs_map_entry_init(&e); e.physical_offset = CFS_CFP_BASE_OFFSET; e.compressed_size = 100; e.generation = 1; cfs_map_entry_crc_set(&e); cfs_journal_entry_init_update(&je, 0, &e); cfs_journal_header_init(&jhdr); buf = palloc(total); memcpy(buf, &jhdr, sizeof(jhdr)); off = sizeof(jhdr); for (i = 0; i < nblocks; i++) { je.blocknum = i; cfs_journal_entry_crc_set(&je); memcpy(buf + off, &je, sizeof(je)); off += sizeof(je); } ok = cfs_test_write_file(path, buf, total); pfree(buf); return ok; } /* * The per-block generation tracker is capped: a journal with more unique * blocks than CFS_FSCK_GEN_TRACK_MAX degrades the monotonicity check (no hard * errors), while a smaller journal keeps it fully active. */ static void test_fsck_generation_tracker_cap(void) { CfsFsckFixture fx; CfsFsckResult res; CfsFsckOptions opts = CFS_FSCK_OPTIONS_DEFAULT; bool ok = true; if (!cfs_fsck_setup(&fx, "gencap", FSCK_MODE_CLEAN)) { add_result("fsck_generation_tracker_cap", "fail", "setup failed"); return; } /* Below the cap: the monotonicity check stays active. */ if (!cfs_test_write_journal(fx.jrn_path, 100)) ok = false; if (ok) { cfs_fsck_result_init(&res); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); if (res.generation_check_degraded || res.errors != 0) ok = false; } /* Above the cap: monotonicity degrades, but no hard errors. */ if (ok && !cfs_test_write_journal(fx.jrn_path, (uint32) CFS_FSCK_GEN_TRACK_MAX + 1)) ok = false; if (ok) { cfs_fsck_result_init(&res); cfs_fsck_journal_file(fx.jrn_path, &opts, &res, NULL); if (!res.generation_check_degraded || res.errors != 0) ok = false; } add_result("fsck_generation_tracker_cap", ok ? "ok" : "fail", ok ? "tracker degrades above cap, clean below" : "tracker cap misbehaved"); cfs_fsck_teardown(&fx); } /* * Try to open the fixture relation; return true when cfs_open_paths() * rejects it with the "larger than the segment size" corruption error. */ static bool test_segment_open_rejected(CfsFsckFixture * fx) { CfsRelation *cfs = NULL; bool rejected = false; PG_TRY(); { RelFileLocatorBackend rl; rl.locator.spcOid = DEFAULTTABLESPACE_OID; rl.locator.dbOid = 16384; rl.locator.relNumber = 99991; rl.backend = INVALID_PROC_NUMBER; cfs = cfs_open_paths(rl, MAIN_FORKNUM, fx->cfp_path, fx->map_path, fx->jrn_path, CFS_OPEN_RDWR); } PG_CATCH(); { ErrorData *edata; MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); edata = CopyErrorData(); if (strstr(edata->message, "larger than the segment size") != NULL) rejected = true; MemoryContextSwitchTo(oldcontext); FlushErrorState(); } PG_END_TRY(); if (cfs != NULL) cfs_close(cfs); return rejected; } /* * The engine never writes a segment larger than CFS_SEGMENT_SIZE, so an * oversized one is corruption regardless of what the rest of the chain * looks like: a lone oversized ".cfp" and an oversized ".cfp" followed by * a ".cfp.1" must both be rejected at open. */ static void test_segment_oversized_rejected(void) { CfsFsckFixture fx; bool rejected_lone; bool rejected_mixed; char detail[128]; int fd; char zero[CFS_CFP_BASE_OFFSET] = {0}; if (!cfs_fsck_setup(&fx, "bigseg", FSCK_MODE_CLEAN)) { add_result("segment_oversized_rejected", "fail", "setup failed"); return; } /* * Inflate ".cfp" past CFS_SEGMENT_SIZE (sparse: lead-in plus a hole). */ fd = BasicOpenFile(fx.cfp_path, O_RDWR | PG_BINARY); if (fd < 0 || write(fd, zero, sizeof(zero)) != sizeof(zero) || ftruncate(fd, (off_t) CFS_SEGMENT_SIZE + 8192) != 0) { add_result("segment_oversized_rejected", "fail", "inflate failed"); if (fd >= 0) close(fd); cfs_fsck_teardown(&fx); return; } close(fd); /* Case 1: a lone oversized segment 0. */ rejected_lone = test_segment_open_rejected(&fx); /* Case 2: a stray ".cfp.1" on top of it — a mixed chain. */ if (!cfs_test_write_file(psprintf("%s.1", fx.cfp_path), zero, sizeof(zero))) { add_result("segment_oversized_rejected", "fail", "seg1 failed"); cfs_fsck_teardown(&fx); return; } rejected_mixed = test_segment_open_rejected(&fx); snprintf(detail, sizeof(detail), "lone=%d mixed=%d", (int) rejected_lone, (int) rejected_mixed); add_result("segment_oversized_rejected", (rejected_lone && rejected_mixed) ? "ok" : "fail", detail); unlink(psprintf("%s.1", fx.cfp_path)); cfs_fsck_teardown(&fx); } PG_FUNCTION_INFO_V1(cfs_run_tests); PG_FUNCTION_INFO_V1(test_cfs_roundtrip); PG_FUNCTION_INFO_V1(test_cfs_corrupt_crc); PG_FUNCTION_INFO_V1(test_cfs_codec_available); PG_FUNCTION_INFO_V1(cfs_run_format_tests); PG_FUNCTION_INFO_V1(cfs_run_path_tests); PG_FUNCTION_INFO_V1(cfs_run_fsck_tests); PG_FUNCTION_INFO_V1(cfs_run_storage_tests); PG_FUNCTION_INFO_V1(cfs_run_shmem_tests); PG_FUNCTION_INFO_V1(cfs_run_shmem_hook_tests); PG_FUNCTION_INFO_V1(cfs_run_segment_tests); PG_FUNCTION_INFO_V1(cfs_relation_policy); Datum test_cfs_roundtrip(PG_FUNCTION_ARGS) { CfsAlgorithm algorithm = parse_algorithm_text(PG_GETARG_TEXT_PP(0)); bytea *payload = PG_GETARG_BYTEA_PP(1); int32 level = PG_GETARG_INT32(2); unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT; CfsCompressResult cres; CfsDecompressResult dres; CfsDecompressStatus dstatus; bool ok; if (!CfsCodecAvailable(algorithm)) { PG_RETURN_BOOL(algorithm == CFS_ALGORITHM_RAW ? false : true); } fill_page_from_payload(page, payload); scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); opts.algorithm = algorithm; opts.level = level; opts.min_gain_bytes = 1; opts.explicit_algorithm = true; opts.allow_raw_fallback = true; ereport(DEBUG1, (errmsg("CFS: test round-trip for algorithm %s", CfsAlgorithmGetName(algorithm)))); CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), &dres); ok = (dstatus == CFS_DECOMPRESS_OK && dres.decompressed_size == sizeof(page) && memcmp(page, decompressed, sizeof(page)) == 0); pfree(scratch); PG_RETURN_BOOL(ok); } Datum test_cfs_corrupt_crc(PG_FUNCTION_ARGS) { CfsAlgorithm algorithm = parse_algorithm_text(PG_GETARG_TEXT_PP(0)); unsigned char page[TEST_BLCKSZ]; unsigned char decompressed[TEST_BLCKSZ]; unsigned char *scratch; size_t scratch_sz; CfsCompressOptions opts = CFS_COMPRESS_OPTIONS_INIT; CfsCompressResult cres; CfsDecompressStatus dstatus; CfsCompressedBlockHeader *hdr; if (!CfsCodecAvailable(algorithm)) { PG_RETURN_TEXT_P(cstring_to_text("skip")); } fill_constant(page, sizeof(page), 0x7F); scratch_sz = CfsCompressScratchSize(sizeof(page)); scratch = palloc(scratch_sz); opts.algorithm = algorithm; opts.level = CFS_COMPRESS_LEVEL_DEFAULT; opts.min_gain_bytes = 1; opts.explicit_algorithm = true; opts.allow_raw_fallback = true; CfsCompressPage(page, sizeof(page), &opts, scratch, scratch_sz, &cres); hdr = (CfsCompressedBlockHeader *) cres.result_data; hdr->data_crc ^= 0x00000001u; dstatus = CfsDecompressPage(cres.result_data, cres.total_size, decompressed, sizeof(decompressed), NULL); pfree(scratch); if (dstatus == CFS_DECOMPRESS_BAD_DATA || dstatus == CFS_DECOMPRESS_BAD_HDR) { PG_RETURN_TEXT_P(cstring_to_text("ok")); } PG_RETURN_TEXT_P(cstring_to_text("fail")); } Datum test_cfs_codec_available(PG_FUNCTION_ARGS) { CfsAlgorithm algorithm = parse_algorithm_text(PG_GETARG_TEXT_PP(0)); PG_RETURN_BOOL(CfsCodecAvailable(algorithm)); } /* * SQL-callable entry point: run every CFS codec test case and return one * row per case with columns (test_name, result, detail). */ Datum cfs_run_tests(PG_FUNCTION_ARGS) { ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; Tuplestorestate *tupstore; TupleDesc tupdesc; int i; Datum values[3]; bool nulls[3]; /* * Run the tests in TopMemoryContext so that any codec state cached by * CfsCodecStateCreate() (a static per-backend cache) is not allocated in * the caller's per-query context — which would be destroyed at the end * of the statement and leave dangling pointers in the cache for the next * invocation. We destroy the whole cache before returning so the next * call starts from a clean slate. */ MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC); tupdesc = rsinfo->setDesc; tupstore = rsinfo->setResult; /* Reset accumulator and run all tests. */ test_result_count = 0; test_raw_codec(); test_lz4_codec(); test_zstd_codec(); test_extended_codec(CFS_ALGORITHM_PGLZ, pglz_extended_names); test_extended_codec(CFS_ALGORITHM_ZLIB, zlib_extended_names); test_lz4_level_roundtrip(); test_codec_max_level(); test_default_write_opts_level(); test_default_level_for(); test_policy_flags_roundtrip(); test_raw_page_roundtrip(); test_compress_page_lz4(); test_incompressible_raw_fallback(); test_crc_corruption_detection(); test_decompress_original_size_rejected(); test_decompress_codec_unavailable(); test_record_padding_zeroed(); test_record_padding_checked(); test_scratch_and_alignment(); test_compress_page_size_rejected(); memset(nulls, 0, sizeof(nulls)); for (i = 0; i < test_result_count; i++) { CfsTestResult *r = &test_results[i]; values[0] = CStringGetTextDatum(r->test_name); values[1] = CStringGetTextDatum(r->result); values[2] = CStringGetTextDatum(r->detail); tuplestore_putvalues(tupstore, tupdesc, values, nulls); } /* Release any codec state cached during this run. */ CfsCodecStateDestroyAll(); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } /* * Shared result-set emitter for the format test runners. The caller is * expected to have populated the static test_results[] accumulator and to have * executed within TopMemoryContext. */ static void cfs_emit_test_results(PG_FUNCTION_ARGS) { ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; Tuplestorestate *tupstore; TupleDesc tupdesc; int i; Datum values[3]; bool nulls[3]; InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC); tupdesc = rsinfo->setDesc; tupstore = rsinfo->setResult; memset(nulls, 0, sizeof(nulls)); for (i = 0; i < test_result_count; i++) { CfsTestResult *r = &test_results[i]; values[0] = CStringGetTextDatum(r->test_name); values[1] = CStringGetTextDatum(r->result); values[2] = CStringGetTextDatum(r->detail); tuplestore_putvalues(tupstore, tupdesc, values, nulls); } } Datum cfs_run_format_tests(PG_FUNCTION_ARGS) { MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); test_result_count = 0; test_format_map_header(); test_format_map_entry(); test_format_journal_header(); test_format_journal_entry(); test_format_block_header(); cfs_emit_test_results(fcinfo); CfsCodecStateDestroyAll(); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } Datum cfs_run_path_tests(PG_FUNCTION_ARGS) { MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); test_result_count = 0; test_path_helpers(); cfs_emit_test_results(fcinfo); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } Datum cfs_run_fsck_tests(PG_FUNCTION_ARGS) { MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); test_result_count = 0; test_fsck_clean_relation(); test_fsck_corrupt_map(); test_fsck_torn_journal(); test_fsck_offset_out_of_range(); test_fsck_live_entries_missing_cfp(); test_fsck_empty_map_no_cfp(); test_fsck_journal_bad_new_entry(); test_fsck_torn_cfp_header(); test_fsck_torn_cfp_record(); test_fsck_corrupt_cfp_record(); test_fsck_cross_check(); test_fsck_resize_shrink_grow(); test_recovery_scan_strict_names(); cfs_emit_test_results(fcinfo); CfsCodecStateDestroyAll(); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } Datum cfs_run_storage_tests(PG_FUNCTION_ARGS) { MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); test_result_count = 0; test_storage_create_open(); test_storage_write_read(); test_storage_update_generation(); test_storage_fold_skips_missing_cfp(); test_cfs_journal_apply_sink(); test_storage_segment_replay_header(); test_storage_next_generation(); test_storage_journal_replay(); test_storage_checkpoint(); test_read_record_size_guard(); test_map_sparse_hole_zero_page(); test_map_corrupt_row_healed(); test_storage_crash_after_cfp(); test_storage_zero_extend_truncate(); test_storage_zero_extend_overflow(); test_storage_truncate_journal_resize_only(); test_storage_reopen_closes_fds_on_error(); test_storage_unlink_swap_artifacts(); test_storage_lookup_no_implicit_growth(); test_storage_write_page_journals_resize(); test_storage_compaction(); test_storage_journal_incarnation(); test_storage_chain_padding(); test_storage_snapshot_tail_invalidated(); test_storage_snapshot_cfp_size_from_eof(); test_storage_torn_record_visibility(); test_storage_torn_tail_truncated(); test_storage_mid_journal_preserved(); test_storage_delta_mid_journal_reload(); test_storage_tail_change_detected(); test_storage_journal_skip_missing_data(); test_storage_read_padding_garbage(); test_storage_shared_tail_protocol(); test_compress_page_nocopy_raw(); cfs_emit_test_results(fcinfo); CfsCodecStateDestroyAll(); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } Datum cfs_run_segment_tests(PG_FUNCTION_ARGS) { MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); test_result_count = 0; test_fsck_generation_zero_map(); test_fsck_generation_zero_journal(); test_fsck_generation_regression(); test_fsck_generation_tracker_cap(); test_segment_oversized_rejected(); test_segment_rollover(); cfs_emit_test_results(fcinfo); CfsCodecStateDestroyAll(); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } Datum cfs_run_shmem_tests(PG_FUNCTION_ARGS) { MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); test_result_count = 0; test_shmem_meta_pin(); test_shmem_stats(); test_shmem_chains(); test_shmem_cached_io(); test_read_cached_entry_corruption(); test_shmem_invalidate(); test_shmem_meta_overflow(); test_shmem_pin_reaper(); test_shmem_publish_postcommit_overflow(); test_shmem_truncate_meta(); test_shmem_generation_check(); test_shmem_crc_survives_invalidate(); test_shmem_crc_point_invalidate(); test_bg_pause_expiry(); test_shmem_stale_handle_hit(); test_shared_map_api(); test_shared_map_nblocks_gate(); test_shared_map_eviction(); test_shared_map_eviction_pinned(); test_shared_map_ensure(); test_shared_map_resident_store_no_evict(); test_shared_map_clock_sweep(); test_shared_map_generation_gate(); test_shared_map_short_read(); test_shared_map_segment_replay_corruption(); test_shared_map_journal_aba(); test_shared_map_truncate_resurrect(); test_shared_map_pool_exhaustion(); test_shared_map_write_no_load(); test_shared_map_fallback_read(); test_shared_map_unhealed_corruption(); test_shared_map_invalidate_index(); test_shared_map_drop_database(); cfs_emit_test_results(fcinfo); CfsCodecStateDestroyAll(); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } /* * Assert-only shared-map tests. They are split off the main shmem set so * that the regression output does not depend on whether the server was * built with assertions; the TAP test drives this function and skips when * debug_assertions is off. */ Datum cfs_run_shmem_hook_tests(PG_FUNCTION_ARGS) { MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); test_result_count = 0; test_shared_map_publish_unsynced(); test_shared_map_merge_race(); test_shared_map_orphan_reservation(); test_shared_map_usage_reset(); cfs_emit_test_results(fcinfo); CfsCodecStateDestroyAll(); MemoryContextSwitchTo(oldcontext); return (Datum) 0; } /* ------------------------------------------------------------------ * Relation policy inspection helper. * * cfs_relation_policy(regclass) returns the CFS policy of the named relation * as it is effective for the current session: whether CFS is enabled and, * if so, the algorithm plus level / min_gain_bytes resolved the same way * the write path resolves them (explicit stored value, else the session's * cfs_default_* GUCs). It exercises RelationUsesCfs() and * CfsEffectiveOptionsFromRelation() from the SQL surface so that the * reloptions / GUC / inheritance behaviour can be validated by regression * tests. * ------------------------------------------------------------------ */ Datum cfs_relation_policy(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); Relation rel; CfsEffectiveOptions opts; TupleDesc tupdesc; Datum values[4]; bool nulls[4]; HeapTuple tuple; if (!OidIsValid(reloid)) PG_RETURN_NULL(); if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) elog(ERROR, "return type must be a row type"); rel = relation_open(reloid, AccessShareLock); /* * CfsEffectiveOptionsFromRelation handles every relkind safely: an * index resolves through its own stored policy (no parent lookup), * and non-StdRdOptions relkinds (views/composite-types/sequences) are * recognized internally and return is_cfs=false without casting * rd_options. No outer gate needed. */ CfsEffectiveOptionsFromRelation(rel, &opts); /* * Resolve unset fields from the session GUCs, mirroring the write path * (cfs_smgr_write_opts): the probe reports what a write in this session * would use right now. */ if (opts.is_cfs) { if (!opts.level_set) opts.level = (opts.algorithm != CFS_ALGORITHM_RAW) ? cfs_default_level_for(opts.algorithm) : CFS_COMPRESS_LEVEL_DEFAULT; if (!opts.min_gain_bytes_set) opts.min_gain_bytes = cfs_default_min_gain_bytes; } MemSet(nulls, 0, sizeof(nulls)); values[0] = BoolGetDatum(opts.is_cfs); if (opts.is_cfs) { values[1] = CStringGetTextDatum(CfsAlgorithmGetName(opts.algorithm)); values[2] = Int32GetDatum(opts.level); values[3] = Int32GetDatum(opts.min_gain_bytes); } else { nulls[1] = true; nulls[2] = true; nulls[3] = true; } relation_close(rel, AccessShareLock); tuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(tuple)); } /* ------------------------------------------------------------------ * cfs_relation_has_sidecars(regclass) * * Returns true when at least one CFS sidecar file (.cfp / .cfsmap / .cfsjrn) * exists on disk for the relation's main fork. Used by the regression test * to verify that the storage manager creates sidecars when a relation uses * CFS and removes them on DROP. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_relation_has_sidecars); Datum cfs_relation_has_sidecars(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); Relation rel; RelFileLocatorBackend rl; bool result; if (!OidIsValid(reloid)) PG_RETURN_NULL(); rel = relation_open(reloid, AccessShareLock); rl.locator = rel->rd_locator; rl.backend = rel->rd_backend; /* * cfs_exists() returns false for unsupported (temp) locators, which is * the correct answer here. */ result = cfs_exists(rl, MAIN_FORKNUM); relation_close(rel, AccessShareLock); PG_RETURN_BOOL(result); } /* ------------------------------------------------------------------ * cfs_test_defer_publish(regclass, int) * * Resolve the relation's current effective CFS policy, set the level to the * given value, and queue it for deferred publication (as if an ALTER had * changed the tuning). Exercises cfs_publish_options_deferred() from the * SQL surface so the pre-commit / abort flush semantics can be validated by * a regression test. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_defer_publish); Datum cfs_test_defer_publish(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); int level = PG_GETARG_INT32(1); Relation rel; RelFileLocatorBackend rl; CfsEffectiveOptions opts; if (!OidIsValid(reloid)) PG_RETURN_NULL(); rel = relation_open(reloid, AccessShareLock); CfsEffectiveOptionsFromRelation(rel, &opts); if (!opts.is_cfs) { relation_close(rel, AccessShareLock); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("relation is not a CFS relation"))); } opts.level = level; opts.level_set = true; rl.locator = rel->rd_locator; rl.backend = rel->rd_backend; cfs_publish_options_deferred(rl, MAIN_FORKNUM, &opts); relation_close(rel, AccessShareLock); PG_RETURN_VOID(); } /* ------------------------------------------------------------------ * cfs_test_publish_pending(regclass) * * Report whether the relation has a deferred policy publication queued in the * current transaction (cfs_publish_is_pending). * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_publish_pending); Datum cfs_test_publish_pending(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); Relation rel; RelFileLocatorBackend rl; bool pending; if (!OidIsValid(reloid)) PG_RETURN_NULL(); rel = relation_open(reloid, AccessShareLock); rl.locator = rel->rd_locator; rl.backend = rel->rd_backend; pending = cfs_publish_is_pending(rl, MAIN_FORKNUM); relation_close(rel, AccessShareLock); PG_RETURN_BOOL(pending); } /* ------------------------------------------------------------------ * cfs_test_shared_level(regclass) * * Return the level currently stored in the shared-memory policy cache for the * relation, or NULL when no CFS policy is published there. Exercises * cfs_get_options() from the SQL surface. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_shared_level); Datum cfs_test_shared_level(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); Relation rel; RelFileLocatorBackend rl; CfsEffectiveOptions opts; if (!OidIsValid(reloid)) PG_RETURN_NULL(); rel = relation_open(reloid, AccessShareLock); rl.locator = rel->rd_locator; rl.backend = rel->rd_backend; if (!cfs_get_options(rl, MAIN_FORKNUM, &opts) || !opts.is_cfs) { relation_close(rel, AccessShareLock); PG_RETURN_NULL(); } relation_close(rel, AccessShareLock); PG_RETURN_INT32(opts.level); } /* ------------------------------------------------------------------ * cfs_test_publish_pending_at(oid) * * Report whether the given relfilenode (current database, default * tablespace, regular backend) has a deferred policy publication queued in * the current transaction. Lets a test inspect a storage node the * relation itself no longer uses (e.g. after a rewrite). * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_publish_pending_at); Datum cfs_test_publish_pending_at(PG_FUNCTION_ARGS) { Oid filenode = PG_GETARG_OID(0); RelFileLocatorBackend rl; rl.locator.spcOid = MyDatabaseTableSpace; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = filenode; rl.backend = INVALID_PROC_NUMBER; PG_RETURN_BOOL(cfs_publish_is_pending(rl, MAIN_FORKNUM)); } /* ------------------------------------------------------------------ * cfs_test_shared_level_at(oid) * * Return the level currently stored in the shared-memory policy cache for * the given relfilenode (current database, default tablespace), or NULL * when no CFS policy is published there. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_shared_level_at); Datum cfs_test_shared_level_at(PG_FUNCTION_ARGS) { Oid filenode = PG_GETARG_OID(0); RelFileLocatorBackend rl; CfsEffectiveOptions opts; rl.locator.spcOid = MyDatabaseTableSpace; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = filenode; rl.backend = INVALID_PROC_NUMBER; if (!cfs_get_options(rl, MAIN_FORKNUM, &opts) || !opts.is_cfs) PG_RETURN_NULL(); PG_RETURN_INT32(opts.level); } /* ------------------------------------------------------------------ * cfs_test_journal_header(oid) * * Dump the .cfsjrn header summary (incarnation, max_generation) of a * relation fork together with the same totals computed directly from the * .cfsmap entries, so tests can assert that every journal reset stamped * the monotone watermark and that dead-space arithmetic matches the map *. Raises ERROR when either sidecar is missing or its * header fails validation. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_journal_header); Datum cfs_test_journal_header(PG_FUNCTION_ARGS) { Oid filenode = PG_GETARG_OID(0); RelFileLocatorBackend rl; CfsJournalFileHeader jhdr; CfsMapPrologue mhdr; CfsMapEntry *entries = NULL; TupleDesc tupdesc; Datum values[3]; bool nulls[3]; HeapTuple tuple; uint64 nblocks = 0; uint32 map_max_generation = 0; uint64 i; int fd; char *path; rl.locator.spcOid = MyDatabaseTableSpace; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = filenode; rl.backend = INVALID_PROC_NUMBER; if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) elog(ERROR, "return type must be a row type"); path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_JOURNAL); fd = BasicOpenFile(path, O_RDONLY | PG_BINARY); if (fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open journal \"%s\": %m", path))); if (cfs_pread_all(fd, &jhdr, sizeof(jhdr), 0) != CFS_STORAGE_OK || cfs_journal_header_validate(&jhdr) != CFS_FORMAT_OK) { close(fd); ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("invalid journal header in \"%s\"", path))); } close(fd); pfree(path); path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_MAP); fd = BasicOpenFile(path, O_RDONLY | PG_BINARY); if (fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open page map \"%s\": %m", path))); if (cfs_pread_all(fd, &mhdr, sizeof(mhdr), 0) != CFS_STORAGE_OK || cfs_map_prologue_validate(&mhdr) != CFS_FORMAT_OK) { close(fd); ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("invalid page map header in \"%s\"", path))); } nblocks = 0; { off_t map_size = lseek(fd, 0, SEEK_END); if (map_size >= 0) nblocks = cfs_map_rows_from_size((uint64) map_size); } if (nblocks > 0) { entries = palloc(nblocks * CFS_MAP_ENTRY_SIZE); if (cfs_pread_all(fd, entries, nblocks * CFS_MAP_ENTRY_SIZE, CFS_MAP_HEADER_SIZE) != CFS_STORAGE_OK) { close(fd); ereport(ERROR, (errcode_for_file_access(), errmsg("could not read page map entries from \"%s\"", path))); } } close(fd); pfree(path); for (i = 0; i < nblocks; i++) { CfsMapEntry *e = &entries[i]; if (cfs_map_entry_validate(e, false) != CFS_FORMAT_OK) continue; if (e->generation > map_max_generation) map_max_generation = e->generation; } if (entries != NULL) pfree(entries); MemSet(nulls, 0, sizeof(nulls)); values[0] = Int32GetDatum(jhdr.incarnation); values[1] = Int32GetDatum(jhdr.max_generation); values[2] = Int64GetDatum((int64) map_max_generation); tuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(tuple)); } /* ------------------------------------------------------------------ * cfs_test_slot_present_at(oid) * * True when the shared-memory policy cache holds a slot for the given * relfilenode (current database, default tablespace), regardless of what * the slot says — unlike cfs_test_shared_level_at, which reports NULL * both for a missing slot and for one lying is_cfs=false. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_slot_present_at); Datum cfs_test_slot_present_at(PG_FUNCTION_ARGS) { Oid filenode = PG_GETARG_OID(0); RelFileLocatorBackend rl; rl.locator.spcOid = MyDatabaseTableSpace; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = filenode; rl.backend = INVALID_PROC_NUMBER; PG_RETURN_BOOL(cfs_slot_present(rl, MAIN_FORKNUM)); } /* ------------------------------------------------------------------ * cfs_test_publish_false_at(oid) * * Publish a "not a CFS relation" policy into the shared-memory policy * cache for the given relfilenode (current database, default * tablespace): a controlled imitation of a stale cache slot lying about * a node whose sidecar files still exist on disk. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_publish_false_at); Datum cfs_test_publish_false_at(PG_FUNCTION_ARGS) { Oid filenode = PG_GETARG_OID(0); RelFileLocatorBackend rl; CfsEffectiveOptions opts; rl.locator.spcOid = MyDatabaseTableSpace; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = filenode; rl.backend = INVALID_PROC_NUMBER; memset(&opts, 0, sizeof(opts)); opts.is_cfs = false; cfs_publish_options(rl, MAIN_FORKNUM, &opts); PG_RETURN_VOID(); } /* ------------------------------------------------------------------ * cfs_test_sidecars_at(oid) * * True when the given relfilenode (current database, default * tablespace) has CFS sidecar files on disk, regardless of any cached * policy. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_sidecars_at); Datum cfs_test_sidecars_at(PG_FUNCTION_ARGS) { Oid filenode = PG_GETARG_OID(0); RelFileLocatorBackend rl; rl.locator.spcOid = MyDatabaseTableSpace; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = filenode; rl.backend = INVALID_PROC_NUMBER; PG_RETURN_BOOL(cfs_exists(rl, MAIN_FORKNUM)); } /* ------------------------------------------------------------------ * cfs_relation_last_record(regclass) * * Walk the append-only record stream of the relation's .cfp file * (segment 0 only; the regression tests never produce a segmented * file) and report the LAST record's on-disk header fields plus the * total record count. * * The record header carries the algorithm but NOT the compression * level (decompression never needs it), so the probe reports sizes: * two structurally identical pages written under different effective * levels must produce records with different compressed_size. This * is how the regression tests pin the write path's runtime level * resolve to the actual bytes on disk instead of trusting the * session-visible policy. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_relation_last_record); Datum cfs_relation_last_record(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); Relation rel; RelFileLocatorBackend rl; char *relpath; char *path; FILE *f; long file_size; long off; uint64 nrecords = 0; CfsCompressedBlockHeader last; TupleDesc tupdesc; Datum values[4]; bool nulls[4]; HeapTuple tuple; if (!OidIsValid(reloid)) PG_RETURN_NULL(); rel = relation_open(reloid, AccessShareLock); rl.locator = rel->rd_locator; rl.backend = rel->rd_backend; relation_close(rel, AccessShareLock); relpath = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA); if (relpath == NULL) PG_RETURN_NULL(); path = psprintf("%s/%s", DataDir, relpath); f = AllocateFile(path, PG_BINARY_R); if (f == NULL) PG_RETURN_NULL(); /* no sidecar: nothing recorded yet */ if (fseek(f, 0, SEEK_END) != 0 || (file_size = ftell(f)) < 0) { FreeFile(f); ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("could not determine size of \"%s\"", path))); } MemSet(nulls, 0, sizeof(nulls)); memset(&last, 0, sizeof(last)); /* * Records start after the reserved lead-in and follow each other * contiguously; each header's compressed_size tells where the next record * begins (the same walk cfs_fsck_cfp_file() performs). */ off = CFS_CFP_BASE_OFFSET; while (off + (long) CFS_BLOCK_HEADER_SIZE <= file_size) { CfsCompressedBlockHeader hdr; long rec_size; if (fseek(f, off, SEEK_SET) != 0 || fread(&hdr, 1, CFS_BLOCK_HEADER_SIZE, f) != CFS_BLOCK_HEADER_SIZE) ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("could not read record header at offset %ld of \"%s\"", off, path))); if (hdr.magic != CFS_BLOCK_MAGIC || hdr.version != CFS_FORMAT_VERSION) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("invalid CFS record header at offset %ld of \"%s\"", off, path))); rec_size = (long) CFS_RECORD_SIZE(hdr.compressed_size); if (rec_size <= 0 || off + rec_size > file_size) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("truncated CFS record at offset %ld of \"%s\"", off, path))); last = hdr; nrecords++; off += rec_size; } FreeFile(f); if (nrecords == 0) PG_RETURN_NULL(); if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) elog(ERROR, "return type must be a row type"); values[0] = CStringGetTextDatum(CfsAlgorithmGetName((CfsAlgorithm) last.algorithm)); values[1] = Int64GetDatum((int64) last.original_size); values[2] = Int64GetDatum((int64) last.compressed_size); values[3] = Int64GetDatum((int64) nrecords); tuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(tuple)); } /* * Test-only: drop the shared metadata slot, read block 0 through the smgr * bridge (which opens the lazy CFS handle) and report the nblocks value the * bridge published, if any. A lazy handle only knows the .cfsmap snapshot, * so publishing its size would hide journal-only extensions. */ PG_FUNCTION_INFO_V1(cfs_test_smgr_read_meta); Datum cfs_test_smgr_read_meta(PG_FUNCTION_ARGS) { Oid relid = PG_GETARG_OID(0); Relation rel; RelFileLocatorBackend rl; SMgrRelation reln; char *buf; uint64 nblocks = 0; bool have_nblocks; rel = RelationIdGetRelation(relid); if (!RelationIsValid(rel)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relid))); rl.locator = rel->rd_locator; rl.backend = INVALID_PROC_NUMBER; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); reln = smgropen(rl.locator, INVALID_PROC_NUMBER); buf = palloc(CFS_BLCKSZ); smgrread(reln, MAIN_FORKNUM, 0, buf); pfree(buf); have_nblocks = cfs_map_cache_get_nblocks(rl, MAIN_FORKNUM, &nblocks); smgrclose(reln); RelationClose(rel); if (have_nblocks) PG_RETURN_INT64((int64) nblocks); PG_RETURN_NULL(); } /* * Test-only: measure a relation's size through the smgr bridge with a cold * metadata slot and report how many throwaway full-map handles the path * opened. The size path measures the sidecar pair (stat(.cfsmap) plus the * journal's last RESIZE) and never builds a map of its own (QDB-1516), so * the answer must be 0 for every pool size. */ PG_FUNCTION_INFO_V1(cfs_test_smgr_size_full_opens); Datum cfs_test_smgr_size_full_opens(PG_FUNCTION_ARGS) { Oid relid = PG_GETARG_OID(0); Relation rel; RelFileLocatorBackend rl; SMgrRelation reln; uint64 before; uint64 opens; rel = RelationIdGetRelation(relid); if (!RelationIsValid(rel)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relid))); rl.locator = rel->rd_locator; rl.backend = INVALID_PROC_NUMBER; cfs_map_cache_invalidate(rl, MAIN_FORKNUM); reln = smgropen(rl.locator, INVALID_PROC_NUMBER); before = cfs_smgr_full_map_open_count(); (void) smgrnblocks(reln, MAIN_FORKNUM); opens = cfs_smgr_full_map_open_count() - before; smgrclose(reln); RelationClose(rel); PG_RETURN_INT64((int64) opens); } /* -------------------------------------------------------------------- * cfs_test_checkpoint_full_opens(oid) * * Run a real immediate checkpoint (the flags the SQL CHECKPOINT command * uses) and report how many throwaway full-map handles the checkpoint * path opened for THIS relation. The count is per-relation, so a * background full-map open of some unrelated relation cannot mask or * fake the measurement (the cluster-wide counter could do both). The * checkpoint's cost must track the journal, not the table: folding a * handful of journal records must not assemble the relation's complete * in-memory page map. * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_checkpoint_full_opens); Datum cfs_test_checkpoint_full_opens(PG_FUNCTION_ARGS) { Oid relid = PG_GETARG_OID(0); Relation rel; RelFileLocatorBackend rl; uint64 before; uint64 after; rel = RelationIdGetRelation(relid); if (!RelationIsValid(rel)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relid))); rl.locator = rel->rd_locator; rl.backend = INVALID_PROC_NUMBER; before = cfs_shared_full_map_opens_rel(rl, MAIN_FORKNUM); RequestCheckpoint(CHECKPOINT_FAST | CHECKPOINT_FORCE | CHECKPOINT_WAIT); after = cfs_shared_full_map_opens_rel(rl, MAIN_FORKNUM); RelationClose(rel); /* * An evicted slot would read 0 again; the test keeps it pinned-dirty, so * a genuine drop shows up as after < before instead. */ if (after < before) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("full-map-open counter of relation %u went backwards", relid))); PG_RETURN_INT64((int64) (after - before)); } /* -------------------------------------------------------------------- * cfs_test_immedsync(oid) * * Run smgrimmedsync() on the relation's main fork: the SQL-reachable way * to open a CFS full map handle lock-free on demand (the immedsync path * the bulk writer takes). * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_immedsync); Datum cfs_test_immedsync(PG_FUNCTION_ARGS) { Oid relid = PG_GETARG_OID(0); Relation rel; rel = RelationIdGetRelation(relid); if (!RelationIsValid(rel)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relid))); smgrimmedsync(RelationGetSmgr(rel), MAIN_FORKNUM); RelationClose(rel); PG_RETURN_BOOL(true); } /* -------------------------------------------------------------------- * cfs_test_smgr_truncate(oid, int) * * Truncate the relation's main fork through smgrtruncate(), i.e. through * the backend's cached SMgrRelation and its cached CFS handle. SQL * TRUNCATE allocates a new relfilenode and VACUUM reads every page before * it truncates, so both reopen the handle on the way; this wrapper is the * only SQL-reachable way to drive cfs_smgr_truncate() with a handle that * predates a sidecar swap (an immedsync, which does not bump the shared * generation). * ------------------------------------------------------------------ */ PG_FUNCTION_INFO_V1(cfs_test_smgr_truncate); Datum cfs_test_smgr_truncate(PG_FUNCTION_ARGS) { Oid relid = PG_GETARG_OID(0); int32 target = PG_GETARG_INT32(1); Relation rel; SMgrRelation reln; ForkNumber forknum = MAIN_FORKNUM; BlockNumber old_nblocks; BlockNumber nblocks; CfsEffectiveOptions opts; rel = RelationIdGetRelation(relid); if (!RelationIsValid(rel)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation with OID %u does not exist", relid))); CfsEffectiveOptionsFromRelation(rel, &opts); if (!opts.is_cfs) { RelationClose(rel); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("relation is not a CFS relation"))); } /* * smgrtruncate() requires an exclusive lock on the relation, so other * backends process the smgr invalidation it sends. */ LockRelation(rel, AccessExclusiveLock); reln = RelationGetSmgr(rel); old_nblocks = smgrnblocks(reln, MAIN_FORKNUM); if (target < 0 || (BlockNumber) target > old_nblocks) { UnlockRelation(rel, AccessExclusiveLock); RelationClose(rel); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("truncation target %d is outside relation size %u", target, old_nblocks))); } nblocks = (BlockNumber) target; smgrtruncate(reln, &forknum, 1, &old_nblocks, &nblocks); UnlockRelation(rel, AccessExclusiveLock); RelationClose(rel); PG_RETURN_BOOL(true); } /* * Report whether the pin-owner registry was created. It must exist for * every cfs_map_memory value (0 included): metadata slots are pinned and * reaped with the pool off just the same. */ PG_FUNCTION_INFO_V1(cfs_test_map_pin_registry); Datum cfs_test_map_pin_registry(PG_FUNCTION_ARGS) { PG_RETURN_BOOL(cfs_map_cache_test_pin_registry_live()); } /* ------------------------------------------------------------------ * cfs_test_tail_write(relnumber, blocknum) -> bigint * cfs_test_tail_verify(relnumber, nblocks) -> bigint * cfs_test_tail_cleanup(relnumber) -> boolean * * The D1 two-backend exercise: write one page of a synthetic CFS * relation through the REAL locked write path (metadata slot pinned, * append lock taken, handle refreshed, cfs_write_page_cached), the same * sequence the smgr layer runs, and return the record's physical .cfp * offset. Two sessions calling this alternately must produce strictly * increasing offsets: a backend that appended at a stale per-handle tail * would return an offset its peer already used (and overwrite its * record), which cfs_test_tail_verify detects as duplicated offsets or * as corrupted read-back data. * * The page of block b is filled with the byte pattern (b & 0xFF), so * verify can check every byte of every block without carrying the * written tags around. * ------------------------------------------------------------------ */ static RelFileLocatorBackend cfs_tail_locator(int64 relnumber) { RelFileLocatorBackend rl; rl.locator.spcOid = MyDatabaseTableSpace; rl.locator.dbOid = MyDatabaseId; rl.locator.relNumber = (RelFileNumber) relnumber; rl.backend = INVALID_PROC_NUMBER; return rl; } PG_FUNCTION_INFO_V1(cfs_test_tail_write); Datum cfs_test_tail_write(PG_FUNCTION_ARGS) { int64 relnumber = PG_GETARG_INT64(0); int32 blocknum = PG_GETARG_INT32(1); RelFileLocatorBackend rl = cfs_tail_locator(relnumber); CfsRelation *cfs; CfsWriteOptions opts = cfs_test_write_opts(); unsigned char page[TEST_BLCKSZ]; CfsMapEntry *e; int64 off; cfs_map_cache_pin(rl, MAIN_FORKNUM); cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR | CFS_OPEN_CREATE); if (cfs == NULL) { cfs_map_cache_unpin(rl, MAIN_FORKNUM); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("cfs_test_tail_write: could not open sidecars"))); } cfs_test_fill_page(page, (unsigned char) (blocknum & 0xFF)); /* * Materialise the handle's local map array before the write: a full * handle of a fresh relation allocates it lazily, and the write path * only mirrors the new entry into a non-NULL local map (the journal * and the shared pool always get it). With the array in place the * offset read below comes from the local mirror of the write. */ (void) cfs_map_get_entry(cfs, blocknum); /* * The locked write path exactly as cfs_smgr runs it: pin the metadata * slot, then let cfs_write_page_cached take the append lock, refresh * the stale handle and journal the map update itself. */ if (cfs_write_page_cached(cfs, blocknum, (const char *) page, &opts) != CFS_STORAGE_OK) { cfs_close(cfs); cfs_map_cache_unpin(rl, MAIN_FORKNUM); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("cfs_test_tail_write: write failed"))); } e = cfs_map_get_entry(cfs, blocknum); off = (e != NULL) ? (int64) e->physical_offset : -1; cfs_close(cfs); cfs_map_cache_unpin(rl, MAIN_FORKNUM); PG_RETURN_INT64(off); } /* * Verification result codes of cfs_test_tail_verify: the verified block * count (>= 0) on success, -1 an invalid map entry, -2 a duplicated or * non-increasing record offset, -3 a failed open, -4 a failed read and * -5 a content mismatch. */ PG_FUNCTION_INFO_V1(cfs_test_tail_verify); Datum cfs_test_tail_verify(PG_FUNCTION_ARGS) { int64 relnumber = PG_GETARG_INT64(0); int32 nblocks = PG_GETARG_INT32(1); RelFileLocatorBackend rl = cfs_tail_locator(relnumber); CfsRelation *cfs; unsigned char back[TEST_BLCKSZ]; uint64 prev_off = 0; int32 blk; int tag; cfs = cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDWR); if (cfs == NULL) PG_RETURN_INT64(-3); /* * The exercise numbers its blocks from 1 (see the TAP test): verify * exactly the blocks the writers wrote. */ for (blk = 1; blk <= nblocks; blk++) { CfsMapEntry *e = cfs_map_get_entry(cfs, blk); if (e == NULL || e->physical_offset == CFS_ENTRY_INVALID_OFFSET) { cfs_close(cfs); PG_RETURN_INT64(-1); } /* Appends only: every record must sit strictly past its peer. */ if (e->physical_offset <= prev_off) { cfs_close(cfs); PG_RETURN_INT64(-2); } prev_off = e->physical_offset; if (cfs_read_page(cfs, blk, (char *) back) != CFS_STORAGE_OK) { cfs_close(cfs); PG_RETURN_INT64(-4); } for (tag = 0; tag < TEST_BLCKSZ; tag++) { /* cfs_test_fill_page writes the ramp (tag + i) & 0x7F. */ if (back[tag] != (unsigned char) (((blk & 0xFF) + tag) & 0x7F)) { cfs_close(cfs); PG_RETURN_INT64(-5); } } } cfs_close(cfs); PG_RETURN_INT64((int64) nblocks); } PG_FUNCTION_INFO_V1(cfs_test_tail_cleanup); Datum cfs_test_tail_cleanup(PG_FUNCTION_ARGS) { int64 relnumber = PG_GETARG_INT64(0); RelFileLocatorBackend rl = cfs_tail_locator(relnumber); cfs_map_cache_invalidate(rl, MAIN_FORKNUM); cfs_shared_map_invalidate_relation(rl, MAIN_FORKNUM); cfs_test_unlink_synthetic(rl); PG_RETURN_BOOL(true); } /* ================================================================ * QDB-1513: batched read path (cfs_map_contiguous_run / * cfs_read_pages_batch / cfs_read_records_span) * ================================================================ */ /* * Open a full (private-map) read handle for a real CFS relation. * Returns NULL when the relation has no sidecars. */ static CfsRelation * cfs_test_batch_open(Oid reloid, RelFileLocatorBackend *rl_out) { Relation rel; RelFileLocatorBackend rl; rel = relation_open(reloid, AccessShareLock); rl.locator = rel->rd_locator; rl.backend = rel->rd_backend; relation_close(rel, AccessShareLock); if (rl_out != NULL) *rl_out = rl; return cfs_open(rl, MAIN_FORKNUM, CFS_OPEN_RDONLY); } /* * SQL-callable: exercise the batched read path against a real CFS relation * through a full (private-map) handle. Reports the advisory contiguous-run * length at block 0 and the maximum over the relation, then re-reads every * page in chunks of 16 through cfs_read_pages_batch() and compares each * page byte-for-byte with the per-block cfs_read_page_cached() result. * Pre-fills the batch buffers with a poison pattern so an unfilled buffer * can never compare equal by accident. Returns (run0, run_max, * pages_checked, batch_ok). */ PG_FUNCTION_INFO_V1(cfs_test_read_batch); Datum cfs_test_read_batch(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); CfsRelation *cfs; TupleDesc tupdesc; HeapTuple tuple; Datum values[4]; bool nulls[4]; uint64 nblocks; BlockNumber blk; uint32 run0 = 0; uint32 run_max = 0; uint64 pages_checked = 0; bool batch_ok = true; char *single; void **buffers; int i; const int chunk = 16; cfs = cfs_test_batch_open(reloid, NULL); if (cfs == NULL) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("test_cfs: relation %u has no CFS sidecars", reloid))); nblocks = cfs->map_hdr.nblocks; if (nblocks > 0) { run0 = (uint32) cfs_map_contiguous_run(cfs, 0, chunk); for (blk = 0; blk < nblocks; blk++) { uint32 run = (uint32) cfs_map_contiguous_run(cfs, blk, chunk); if (run > run_max) run_max = run; } } single = (char *) palloc(CFS_BLCKSZ); buffers = (void **) palloc(chunk * sizeof(void *)); for (i = 0; i < chunk; i++) buffers[i] = palloc(CFS_BLCKSZ); for (blk = 0; blk < nblocks && batch_ok; blk += chunk) { BlockNumber n = Min((BlockNumber) chunk, (BlockNumber) (nblocks - blk)); int rc; BlockNumber b; for (b = 0; b < n; b++) MemSet(buffers[b], 0xAA, CFS_BLCKSZ); rc = cfs_read_pages_batch(cfs, blk, buffers, n, NULL, NULL); if (rc != CFS_STORAGE_OK) { batch_ok = false; break; } for (b = 0; b < n; b++) { if (cfs_read_page_cached(cfs, blk + b, single) != CFS_STORAGE_OK || memcmp(buffers[b], single, CFS_BLCKSZ) != 0) { batch_ok = false; break; } pages_checked++; } } for (i = 0; i < chunk; i++) pfree(buffers[i]); pfree(buffers); pfree(single); cfs_close(cfs); if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) elog(ERROR, "return type must be a row type"); MemSet(nulls, 0, sizeof(nulls)); values[0] = Int32GetDatum((int32) run0); values[1] = Int32GetDatum((int32) run_max); values[2] = Int64GetDatum((int64) pages_checked); values[3] = BoolGetDatum(batch_ok); tuple = heap_form_tuple(tupdesc, values, nulls); PG_RETURN_DATUM(HeapTupleGetDatum(tuple)); } /* * SQL-callable: corrupt one payload byte of 'blockno's record directly in * .cfp (the map entry stays valid), batch-read the range [first, first+n) * through cfs_read_pages_batch() and demand CFS_STORAGE_CORRUPT with * fail_block == blockno, then restore the byte and demand a clean read of * the same range. The caller picks a block whose neighbours form a * contiguous run, so the corrupted record is exercised through the span * reader, not the per-block fallback. Returns 'ok' / 'fail: '. */ PG_FUNCTION_INFO_V1(cfs_test_read_batch_corrupt); Datum cfs_test_read_batch_corrupt(PG_FUNCTION_ARGS) { Oid reloid = PG_GETARG_OID(0); BlockNumber blockno = (BlockNumber) PG_GETARG_INT32(1); RelFileLocatorBackend rl; CfsRelation *cfs; CfsMapEntry *e; const char *reason = NULL; char *base_path; char *seg_path; uint64 rec_off; off_t file_off; int fd; char b; void **buffers; int fail_code = 0; BlockNumber fail_block = 0; int rc; int i; const int nreq = 8; cfs = cfs_test_batch_open(reloid, &rl); if (cfs == NULL) PG_RETURN_TEXT_P(cstring_to_text("fail: no sidecars")); if ((uint64) blockno >= cfs->map_hdr.nblocks) { cfs_close(cfs); PG_RETURN_TEXT_P(cstring_to_text("fail: block out of range")); } e = &cfs->map[blockno]; if (!CFS_MAP_ENTRY_VALID(e)) { cfs_close(cfs); PG_RETURN_TEXT_P(cstring_to_text("fail: block has no record")); } rec_off = e->physical_offset; base_path = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA); seg_path = cfs_segment_path(base_path, CFS_CFP_SEGNO((off_t) rec_off)); file_off = CFS_CFP_SEG_OFF((off_t) rec_off) + CFS_BLOCK_HEADER_SIZE + 2; b = 0; fd = BasicOpenFile(seg_path, O_RDWR | PG_BINARY); if (fd < 0 || pg_pread(fd, &b, 1, file_off) != 1) reason = "fail: could not read the record byte"; else { char flipped = (char) (b ^ 0xFF); if (pg_pwrite(fd, &flipped, 1, file_off) != 1) reason = "fail: could not corrupt the record byte"; } if (fd >= 0) close(fd); buffers = (void **) palloc(nreq * sizeof(void *)); for (i = 0; i < nreq; i++) buffers[i] = palloc(CFS_BLCKSZ); if (reason == NULL) { rc = cfs_read_pages_batch(cfs, 0, buffers, (BlockNumber) nreq, &fail_code, &fail_block); if (rc != CFS_STORAGE_CORRUPT || fail_code != CFS_STORAGE_CORRUPT || fail_block != blockno) reason = "fail: corrupted record not reported exactly"; } if (reason == NULL) { /* Restore the byte: the range must read cleanly again. */ fd = BasicOpenFile(seg_path, O_RDWR | PG_BINARY); if (fd < 0 || pg_pwrite(fd, &b, 1, file_off) != 1) reason = "fail: could not restore the record byte"; else { rc = cfs_read_pages_batch(cfs, 0, buffers, (BlockNumber) nreq, NULL, NULL); if (rc != CFS_STORAGE_OK) reason = "fail: clean range read after restore"; } if (fd >= 0) close(fd); } for (i = 0; i < nreq; i++) pfree(buffers[i]); pfree(buffers); cfs_close(cfs); if (reason != NULL) PG_RETURN_TEXT_P(cstring_to_text(reason)); PG_RETURN_TEXT_P(cstring_to_text("ok")); } /* * Test-only independent oracle for the small, single-segment LZ4 fixture. * Validate every physical record, including obsolete records, and return * the requested full page and payload with independent reference matches. */ PG_FUNCTION_INFO_V1(cfs_test_lz4_record); Datum cfs_test_lz4_record(PG_FUNCTION_ARGS) { #ifndef USE_LZ4 elog(ERROR, "LZ4 support is required for the test oracle"); PG_RETURN_NULL(); #else Oid relid = PG_GETARG_OID(0); int32 wanted = PG_GETARG_INT32(1); Relation rel; RelFileLocatorBackend rl; char *filename; char *relpath; FILE *fp; long end; int64 offset = CFS_CFP_BASE_OFFSET; int64 count = 0; int64 selected_offset = 0; int64 selected_end = 0; bytea *selected_page = NULL; bytea *selected_payload = NULL; char page[TEST_BLCKSZ]; char payload[LZ4_COMPRESSBOUND(TEST_BLCKSZ)]; char fast[LZ4_COMPRESSBOUND(TEST_BLCKSZ)]; char hc[LZ4_COMPRESSBOUND(TEST_BLCKSZ)]; int fast_size; int hc_size; int selected_size; TupleDesc desc; Datum values[7]; bool nulls[7] = {false}; if (wanted <= 0) elog(ERROR, "record number must be positive"); rel = relation_open(relid, AccessShareLock); rl.locator = rel->rd_locator; rl.backend = rel->rd_backend; relpath = cfs_make_filename(rl, MAIN_FORKNUM, CFS_FILE_DATA); if (!relpath) elog(ERROR, "missing CFS test record path"); filename = psprintf("%s/%s", DataDir, relpath); pfree(relpath); fp = AllocateFile(filename, PG_BINARY_R); if (!fp) elog(ERROR, "cannot open CFS test record file"); if (fseek(fp, 0, SEEK_END) != 0 || (end = ftell(fp)) < offset) elog(ERROR, "invalid CFS test record file length"); while (offset < end) { CfsCompressedBlockHeader hdr; pg_crc32c crc; size_t record_size; size_t pad; size_t j; if (end - offset < sizeof(hdr) || fseek(fp, offset, SEEK_SET) != 0 || fread(&hdr, 1, sizeof(hdr), fp) != sizeof(hdr)) elog(ERROR, "incomplete CFS test record header"); INIT_CRC32C(crc); COMP_CRC32C(crc, &hdr, offsetof(CfsCompressedBlockHeader, hdr_crc)); FIN_CRC32C(crc); if (hdr.magic != CFS_BLOCK_MAGIC || hdr.version != CFS_FORMAT_VERSION || !EQ_CRC32C(crc, hdr.hdr_crc)) elog(ERROR, "invalid CFS test header CRC"); if (hdr.algorithm != CFS_ALGORITHM_LZ4) elog(ERROR, "CFS test record is not LZ4"); if (hdr.original_size != TEST_BLCKSZ || hdr.compressed_size <= 0 || hdr.compressed_size > sizeof(payload)) elog(ERROR, "invalid CFS test record size"); record_size = CFS_RECORD_SIZE(hdr.compressed_size); if (record_size > end - offset || fread(payload, 1, hdr.compressed_size, fp) != hdr.compressed_size) elog(ERROR, "incomplete CFS test payload"); INIT_CRC32C(crc); COMP_CRC32C(crc, payload, hdr.compressed_size); FIN_CRC32C(crc); if (!EQ_CRC32C(crc, hdr.data_crc) || LZ4_decompress_safe(payload, page, hdr.compressed_size, TEST_BLCKSZ) != TEST_BLCKSZ) elog(ERROR, "invalid CFS test payload"); INIT_CRC32C(crc); COMP_CRC32C(crc, page, TEST_BLCKSZ); FIN_CRC32C(crc); if (!EQ_CRC32C(crc, hdr.orig_crc)) elog(ERROR, "invalid CFS test page CRC"); pad = record_size - sizeof(hdr) - hdr.compressed_size; for (j = 0; j < pad; j++) if (fgetc(fp) != 0) elog(ERROR, "invalid CFS test record padding"); count++; if (count == wanted) { selected_offset = offset; selected_end = offset + record_size; selected_page = palloc(VARHDRSZ + TEST_BLCKSZ); SET_VARSIZE(selected_page, VARHDRSZ + TEST_BLCKSZ); memcpy(VARDATA(selected_page), page, TEST_BLCKSZ); selected_payload = palloc(VARHDRSZ + hdr.compressed_size); SET_VARSIZE(selected_payload, VARHDRSZ + hdr.compressed_size); memcpy(VARDATA(selected_payload), payload, hdr.compressed_size); } offset += record_size; } FreeFile(fp); pfree(filename); relation_close(rel, AccessShareLock); if (!selected_page) elog(ERROR, "CFS test record %d does not exist", wanted); fast_size = LZ4_compress_fast(VARDATA(selected_page), fast, TEST_BLCKSZ, sizeof(fast), 2); hc_size = LZ4_compress_HC(VARDATA(selected_page), hc, TEST_BLCKSZ, sizeof(hc), 12); if (fast_size <= 0 || hc_size <= 0 || (fast_size == hc_size && memcmp(fast, hc, fast_size) == 0)) elog(ERROR, "LZ4 reference payloads are not distinct"); selected_size = VARSIZE(selected_payload) - VARHDRSZ; if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE) elog(ERROR, "composite result required"); values[0] = Int64GetDatum(count); values[1] = Int64GetDatum(selected_offset); values[2] = Int64GetDatum(selected_end); values[3] = PointerGetDatum(selected_page); values[4] = PointerGetDatum(selected_payload); values[5] = BoolGetDatum(selected_size == fast_size && memcmp(VARDATA(selected_payload), fast, fast_size) == 0); values[6] = BoolGetDatum(selected_size == hc_size && memcmp(VARDATA(selected_payload), hc, hc_size) == 0); PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(BlessTupleDesc(desc), values, nulls))); #endif }