/*------------------------------------------------------------------------- * cfs_recovery.c * Compressed File Store (CFS) — WAL / recovery / replication * coordination. * * Implements the startup and recovery coordination functions declared in * cfs_recovery.h. The CFS crash-safety model does not use a WAL resource * manager; instead, durability is provided by the append-only .cfp data * file, the idempotent .cfsjrn journal, and the .cfsmap that checkpoints * and startup keep in sync with it by folding that journal row by row. * This module ensures that: * * 1. At startup after a crash, all CFS journals are folded into their * page maps row by row before any backend can access a CFS relation. * 2. Leftover temporary files from an interrupted compaction swap are * cleaned up before relations are opened. * 3. Corruption during reads is reported through a centralised handler * that respects the cfs_checksum_failure and cfs_recovery_strict GUCs. * * Directory layout (must match GetDatabasePath / GetRelationPath): * * Default tablespace: base//{.cfp,.cfsmap,.cfsjrn} * User tablespace: pg_tblspc////... * Global tablespace: global/... * * Copyright (c) 2026, Kirillov Vyacheslav, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_recovery.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #include #include #include "catalog/pg_tablespace_d.h" #include "common/relpath.h" #include "lib/stringinfo.h" #include "miscadmin.h" #include "access/xlog.h" #include "access/xlogutils.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_codec.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_io.h" #include "storage/cfs/cfs_journal.h" #include "storage/cfs/cfs_map_file.h" #include "storage/cfs/cfs_path.h" #include "storage/cfs/cfs_recovery.h" #include "storage/cfs/cfs_shmem.h" #include "storage/cfs/cfs_smgr.h" #include "storage/cfs/cfs_storage.h" #include "storage/cfs/cfs_swap.h" #include "storage/fd.h" #include "storage/relfilelocator.h" /* ================================================================ * Lifecycle * ================================================================ */ void CfsSubsystemInit(void) { /* Verify the codec dispatch table (PANICs on a coding error). */ CfsCodecInit(); ereport(DEBUG1, (errmsg("CFS: subsystem initialised"))); } void CfsBackendInit(void) { ereport(DEBUG1, (errmsg("CFS: backend initialised (pid %d)", MyProcPid))); } void CfsAtProcExit(int code, Datum arg) { /* * Release cached per-backend codec states (Zstd CCTX/DCTX contexts). */ CfsCodecStateDestroyAll(); } /* ================================================================ * Unified recovery scan * * A single directory walk covers every database directory across all * tablespaces. For each directory two operations are performed: * (a) remove leftover temp/candidate files from interrupted * compaction and snapshot writes (.cfscand, .tmp, .new, .cfsswap); * (b) replay .cfsjrn journals for CFS relations. * ================================================================ */ typedef struct CfsRecoveryStats { int64 total_replayed; /* journal records applied cluster-wide */ int64 rows_folded; /* map rows the recovery folds wrote */ int temp_files_removed; /* leftover compaction temp files deleted */ int journals_opened; /* relations whose journal was opened */ } CfsRecoveryStats; /* * Outcome of stat()ing one sidecar path. When PRESENT, *size (if given) * receives the file size for the caller's use. */ typedef enum CfsSidecarPresence { CFS_SIDECAR_ABSENT, /* stat() failed with ENOENT */ CFS_SIDECAR_PRESENT, /* stat() succeeded */ CFS_SIDECAR_UNKNOWN /* stat() failed with another error */ } CfsSidecarPresence; static CfsSidecarPresence cfs_sidecar_presence(const char *path, off_t *size) { struct stat st; if (stat(path, &st) == 0) { if (size) *size = st.st_size; return CFS_SIDECAR_PRESENT; } if (errno == ENOENT) return CFS_SIDECAR_ABSENT; return CFS_SIDECAR_UNKNOWN; } /* * True when 'base' (a basename with the transient ".tmp"/".new" suffix * already stripped) is a strict CFS sidecar name of a kind the engine * itself creates transient files for: .cfp (any segment) or .cfsmap. * Startup cleanups must only remove files matching the names the server * itself creates, like vanilla's RemovePgTempFiles — a foreign file that * merely shares the suffix stays in place. */ static bool cfs_temp_base_is_sidecar(const char *base) { RelFileNumber relnumber; CfsFileKind kind; unsigned segno; if (!parse_cfs_sidecar_filename(base, &relnumber, &kind, &segno)) return false; return kind == CFS_FILE_DATA || kind == CFS_FILE_MAP; } /* * Read the first bytes of a sidecar file (its header) without opening the * relation. Returns the number of bytes read (0 for an empty file), or * -1 with errno set when the file cannot be opened or read. */ static int cfs_read_sidecar_header(const char *path, void *buf, Size size) { int fd; int nread; fd = OpenTransientFile(path, O_RDONLY | PG_BINARY); if (fd < 0) return -1; do { nread = (int) pg_pread(fd, buf, size, 0); } while (nread < 0 && errno == EINTR); if (CloseTransientFile(fd) != 0) return -1; return nread; } /* * Validate the .cfsmap and .cfsjrn headers of a relation the scan skips * because its journal is empty. The full open path validates both * headers on every open; without this check a corrupt header of a clean * relation would go unnoticed at startup and only surface at the first * backend access (or never). A zero-byte file is a legal fresh state * that the open path ensures later; a partially written prologue (1..7 * bytes) is corruption, the single classification cfs_map_file.c owns. */ static void cfs_verify_sidecar_headers(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsMapPrologue map_hdr; CfsJournalFileHeader jrn_hdr; char *map_path; char *jrn_path; int nread; map_path = cfs_make_filename(rlocator, forknum, CFS_FILE_MAP); jrn_path = cfs_make_filename(rlocator, forknum, CFS_FILE_JOURNAL); /* * The caller has already confirmed the full sidecar triple, and the * temp-name locator cannot reach this function, so both paths exist. */ Assert(map_path != NULL && jrn_path != NULL); nread = cfs_read_sidecar_header(map_path, &map_hdr, sizeof(map_hdr)); if (nread < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not read sidecar header from \"%s\": %m", map_path))); if (nread == (int) sizeof(map_hdr)) { if (cfs_map_prologue_validate(&map_hdr) != CFS_FORMAT_OK) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: corrupt page map snapshot"), errdetail("Invalid .cfsmap header in \"%s\".", map_path))); } else if (nread > 0) { /* * 1..7 bytes is a torn prologue write, not the fresh state: the empty * file (checked as nread == 0 above reaching neither branch) is the * legal fresh state the open path ensures later - the single * classification cfs_map_file.c owns. */ ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: corrupt page map snapshot"), errdetail("File \"%s\" is shorter than its 8-byte header.", map_path))); } nread = cfs_read_sidecar_header(jrn_path, &jrn_hdr, sizeof(jrn_hdr)); if (nread < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not read sidecar header from \"%s\": %m", jrn_path))); if (nread == (int) sizeof(jrn_hdr) && cfs_journal_header_validate(&jrn_hdr) != CFS_FORMAT_OK) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: corrupt page map journal"), errdetail("Invalid .cfsjrn header in \"%s\".", jrn_path))); pfree(map_path); pfree(jrn_path); } /* * Fold the journal of one relation into its page map row by row, then * reset the journal, so subsequent opens see the durable state directly. * * The fold runs through the checkpoint's engine (cfs_journal_fold, stage * CFS_FOLD_STAGE_RECOVERY) on a lazy handle: no full map is loaded into * memory and no snapshot is rewritten, so the cost tracks the journal - * the changes since the last checkpoint - and never the map. */ static void cfs_replay_one_locator(RelFileLocatorBackend rlocator, ForkNumber forknum, CfsRecoveryStats *stats) { CfsJournalFileHeader jhdr; CfsJournalFoldResult fold; CfsRelation *cfs; off_t jrn_eof; int64 folded; int64 nrecords; uint32 watermark; if (forknum != MAIN_FORKNUM) return; if (RelFileLocatorBackendIsTemp(rlocator)) return; /* * Stat the sidecar triple explicitly instead of trusting cfs_exists() * (which reports true when ANY of the three files exists). A partial * triple can only be the debris of a commit-time removal that crashed * midway (.cfp -> .cfsmap -> .cfsjrn, the drop is already committed) or * manual tampering; either way the set is unusable: opening it would fail * hard in the startup process and crash-loop the cluster. Mirror * vanilla's startup cleanups (RemovePgTempFiles, the idempotent * redo-unlink tolerating ENOENT): leftovers of a legal crash are removed * with a WARNING and startup continues. The full triple falls through to * the normal open + replay path below. */ { char *cfp_path = cfs_make_filename(rlocator, forknum, CFS_FILE_DATA); char *map_path; char *jrn_path; off_t jrn_size = 0; CfsSidecarPresence p_cfp, p_map, p_jrn; if (cfp_path == NULL) return; /* unsupported locator (temp) */ map_path = cfs_make_filename(rlocator, forknum, CFS_FILE_MAP); jrn_path = cfs_make_filename(rlocator, forknum, CFS_FILE_JOURNAL); p_cfp = cfs_sidecar_presence(cfp_path, NULL); p_map = cfs_sidecar_presence(map_path, NULL); p_jrn = cfs_sidecar_presence(jrn_path, &jrn_size); pfree(cfp_path); pfree(map_path); pfree(jrn_path); /* Not a CFS relation at all: nothing to do. */ if (p_cfp == CFS_SIDECAR_ABSENT && p_map == CFS_SIDECAR_ABSENT && p_jrn == CFS_SIDECAR_ABSENT) return; /* * A path we cannot inspect is treated as present: never delete what * could not be examined, and never open a set whose state is unknown. * Skipping the relation keeps the cluster running; the WARNING names * the error for the administrator. */ if (p_cfp == CFS_SIDECAR_UNKNOWN || p_map == CFS_SIDECAR_UNKNOWN || p_jrn == CFS_SIDECAR_UNKNOWN) { ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not inspect sidecar files of %u/%u/%u: %m", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); return; } if (p_cfp != CFS_SIDECAR_PRESENT || p_map != CFS_SIDECAR_PRESENT || p_jrn != CFS_SIDECAR_PRESENT) { StringInfoData found; initStringInfo(&found); if (p_cfp == CFS_SIDECAR_PRESENT) appendStringInfoString(&found, " .cfp"); if (p_map == CFS_SIDECAR_PRESENT) appendStringInfoString(&found, " .cfsmap"); if (p_jrn == CFS_SIDECAR_PRESENT) appendStringInfoString(&found, " .cfsjrn"); ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: incomplete sidecar set for %u/%u/%u, " "removing found files", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber), errdetail("Found:%s. A crash during the commit-time " "removal of a dropped relation can leave a " "partial set; the leftovers are removed and " "startup continues.", found.data))); pfree(found.data); /* Remove every file of the triple (segments, candidates too). */ cfs_unlink(rlocator, forknum); return; } /* * Full triple with an empty journal: the checkpoint snapshot is * already the durable state, so there is nothing to replay or * persist. Skipping the open turns the scan into a genuine readdir + * stat pass for every clean relation (a full open loads the whole map * into memory); the journal is opened below only when it actually * holds records. The sidecar headers are still validated, so a * structurally corrupt .cfsmap/.cfsjrn aborts the startup scan here * exactly like it would on the full open path. */ if (jrn_size <= (off_t) CFS_JOURNAL_HEADER_SIZE) { cfs_verify_sidecar_headers(rlocator, forknum); return; } stats->journals_opened++; } /* * Lazy handle + one row-by-row fold + reset: the same engine the * checkpoint uses, so the startup cost tracks the journal, never the * map. required=false mirrors the old soft skip: a sidecar set that * vanished between the stat above and this open (or a busy conditional * append lock when called from a test backend) is a WARNING, not a * crash-loop. */ cfs = cfs_open_lazy_pinned(rlocator, forknum, false); if (cfs == NULL) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: recovery could not open sidecars for %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); return; } /* * The strictness the old full open passed through CFS_OPEN_STRICT: * cfs_open_lazy_pinned() takes no flag argument, so mirror it here - * the fold's skipped-UPDATE reports reach the cfs_recovery_strict * severity only through a strict handle (cfs_journal_update_data_usable). */ if (cfs_recovery_strict) cfs->strict = true; /* * The append lock is cfs_journal_reset_point()'s contract and the fold * boundary's seal: the journal size is sampled INSIDE it, so no record * can escape the fold and still be cut away by the reset (the * checkpoint samples its boundary under the same lock). On startup no * competitor can exist; a test-backend call (CfsReplayAllJournals) * serialises the fold+reset window with live writers and swappers. * Everything from here on runs inside PG_TRY so an ERROR unwinds * without leaking the lock, the pin or the descriptors. */ cfs_append_lock_acquire(rlocator, forknum, LW_EXCLUSIVE); PG_TRY(); { /* * The open released the append lock before returning, so a * compaction may have swapped the sidecar pair in that window: * the descriptors would then name unlinked inodes while the * paths - which cfs_journal_finish_reset() truncates by - name * the new files. Reopen under the lock when the pair moved, the * checkpoint's own identity discipline (cfs_checkpoint_begin): * every step below then works on the current pair, and a foreign * journal reset of a not-swapped pair is caught by the fresh * size sample right after (a bare header skips the fold). */ (void) cfs_reopen_if_map_swapped(cfs); /* * Make the payload durable before any map row referencing it is * written - the checkpoint's data -> journal -> map -> reset * order. At startup the disk already holds the durable state * and these fsyncs are near-free; a test-backend caller may race * with writers whose .cfp data is still only in the OS page * cache, where skipping them would let the reset erase journal * records whose data never became durable. */ if (cfs_fsync_kind(cfs, CFS_FILE_DATA) != CFS_STORAGE_OK) ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: recovery could not fsync data file " "for %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); if (cfs_fsync_kind(cfs, CFS_FILE_JOURNAL) != CFS_STORAGE_OK) ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: recovery could not fsync journal " "file for %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); /* * Fresh journal size under the lock. An unknowable size is an * I/O error, not a cosmetic failure: no fold boundary could be * proven, so nothing may be folded or reset - fail the relation * exactly like the old replay path failed its reads. */ jrn_eof = cfs_fd_size(cfs->jrn_fd); if (jrn_eof < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not determine the journal " "size of \"%s\"", cfs->jrn_path), errdetail("The journal is preserved; the next restart " "retries."))); if (jrn_eof <= (off_t) CFS_JOURNAL_HEADER_SIZE) { /* * Nothing to fold. The stat above saw records, so the journal * became bare in between: the open's interrupted-swap recovery * is the one legal writer here, and it resets the journal of * the new pair (the open validated both sidecar headers). * Skipping the reset too - a bare header is already the folded * state. No early return inside PG_TRY: the FINALLY arm must * run, and a plain return would bypass it. */ } else { /* * Structural validation, fatal in every mode exactly like the * replay path (cfs_journal_replay): without a valid header no * record can be interpreted, so no fold decision can be made * safely. */ if (!cfs_journal_read_header(cfs->jrn_fd, &jhdr)) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: corrupt page map journal"), errdetail("Invalid .cfsjrn header in \"%s\".", cfs->jrn_path))); folded = cfs_journal_fold(cfs, (off_t) CFS_JOURNAL_HEADER_SIZE, jrn_eof, CFS_FOLD_STAGE_RECOVERY, &fold); /* * A torn record with valid records behind it is corruption, not * a crash artifact: the records behind it are the only durable * trace of their changes, so the resize and the reset must not * run. The scan engine already reported it once with the * "recovery" role (cfs_scan_torn_is_tail): through the strict * handle and policy.during_recovery that report is fatal under * cfs_recovery_strict, otherwise it stays a WARNING and this * branch leaves both files untouched - the next restart repeats * the fold. The FINALLY arm releases the lock and the handle * either way. */ if (!(fold.torn_stop && !fold.torn_is_tail)) { /* * Apply the last RESIZE the fold reported, before the reset * drops the journal record that carries it: the map must * never stay longer than the logical size. The * dead-payload read the checkpoint charges over a * shrinking tail is skipped here: startup publishes no * statistics (that stays with the checkpoint). */ if (fold.have_resize) cfs_map_file_resize(cfs, fold.resize_target); /* * Watermark composition, the checkpoint's * (cfs_checkpoint.c): the journal header's monotone stamp * merged with the fold's own (raised for every UPDATE the * engine visited, skipped ones included). */ watermark = jhdr.max_generation; if (fold.max_generation > watermark) watermark = fold.max_generation; /* * WARNING (not data_sync_elevel): every step here is * idempotent - the next restart repeats the fold and the * reset - so failing the startup over a truncate/fsync * hiccup would crash-loop the cluster over a cosmetic * failure (the truncate-failure contract of t/502). */ cfs_journal_reset_point(cfs, watermark, WARNING); nrecords = (fold.stop_off - (off_t) CFS_JOURNAL_HEADER_SIZE) / CFS_JOURNAL_ENTRY_SIZE; ereport(DEBUG1, (errmsg("CFS: replayed %lld journal record(s) for " "%u/%u/%u, %lld row(s) folded into the " "page map", (long long) nrecords, rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber, (long long) folded))); stats->total_replayed += nrecords; stats->rows_folded += folded; } } } PG_CATCH(); { cfs_append_lock_release_after_error(rlocator, forknum); cfs_close_full_unpinned(cfs, rlocator, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rlocator, forknum); cfs_close_full_unpinned(cfs, rlocator, forknum); } /* * Complete a crash-safe compaction swap whose commit marker ('.cfp.cfsswap') * was left on disk by an interrupted activation. 'dirpath' is the directory * holding the sidecars; 'marker_name' is the marker file name within it. * The work itself is delegated to cfs_recover_compaction() — the same * routine the open path uses — so the segmented (.cfp.N) activation * renames, the trailing-segment cleanup and the journal reset exist in * exactly one place. */ static void cfs_complete_swap_marker(const char *dirpath, const char *marker_name) { char cfp_path[MAXPGPATH]; char cfsmap_path[MAXPGPATH]; char cfsjrn_path[MAXPGPATH]; size_t mlen = strlen(marker_name); const char *cfp_suffix = ".cfp.cfsswap"; size_t slen = strlen(cfp_suffix); /* * Derive the sidecar paths by stripping the marker suffix: * ".cfp.cfsswap" -> ".cfp" / ".cfsmap" / ".cfsjrn". */ if (mlen <= slen || strcmp(marker_name + mlen - slen, cfp_suffix) != 0) { /* Not a swap marker we recognise; leave it to the open path. */ return; } snprintf(cfp_path, sizeof(cfp_path), "%s/%.*s", dirpath, (int) (mlen - strlen(".cfsswap")), marker_name); snprintf(cfsmap_path, sizeof(cfsmap_path), "%s/%.*s.cfsmap", dirpath, (int) (mlen - slen), marker_name); snprintf(cfsjrn_path, sizeof(cfsjrn_path), "%s/%.*s.cfsjrn", dirpath, (int) (mlen - slen), marker_name); cfs_recover_compaction(cfp_path, cfsmap_path, cfsjrn_path); ereport(LOG, (errmsg("CFS: completed interrupted compaction swap for \"%s\"", cfp_path))); } /* * process_db_dir — scan one database directory for CFS sidecar files. * * 'spcOid' is the tablespace OID of the directory (may be * DEFAULTTABLESPACE_OID, GLOBALTABLESPACE_OID or a user tablespace OID). * 'dbOid' is 0 for the global tablespace. */ static void process_db_dir(const char *path, Oid spcOid, Oid dbOid, CfsRecoveryStats *stats) { DIR *dir; struct dirent *de; dir = AllocateDir(path); if (dir == NULL) { ereport(DEBUG1, (errmsg("CFS: recovery could not open directory \"%s\": %m", path))); return; } while ((de = ReadDir(dir, path)) != NULL) { const char *name = de->d_name; size_t len = strlen(name); if (name[0] == '.') continue; /* * Clean up leftover temps from interrupted compaction and snapshot * writes: ".cfscand" (compaction map candidate) and ".tmp" (cfp * segment temps and snapshot writer temps). ENOENT is expected: * the open-path recovery (cfs_recover_compaction) may already have * removed the file while replaying this relation's journal earlier * in the same scan. */ if (len > strlen(CFS_MAP_CANDIDATE_TMP_SUFFIX) && strcmp(name + len - strlen(CFS_MAP_CANDIDATE_TMP_SUFFIX), CFS_MAP_CANDIDATE_TMP_SUFFIX) == 0) { char fullpath[MAXPGPATH]; char base[MAXPGPATH]; snprintf(fullpath, sizeof(fullpath), "%s/%s", path, name); /* * Remove only temps whose base is a strict CFS sidecar name — * the engine creates "<...>.cfsmap.cfscand" for its compaction * candidates and nothing else with this suffix; a foreign file * sharing it stays in place. */ strlcpy(base, name, sizeof(base)); base[len - strlen(CFS_MAP_CANDIDATE_TMP_SUFFIX)] = '\0'; if (!cfs_temp_base_is_sidecar(base)) { ereport(DEBUG1, (errmsg("CFS: \"%s\" is not a CFS sidecar name, left in place", fullpath))); continue; } if (unlink(fullpath) == 0) { ereport(LOG, (errmsg("CFS: removed leftover compaction temp file \"%s\"", fullpath))); stats->temp_files_removed++; } else if (errno != ENOENT) { ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not remove leftover temp file \"%s\": %m", fullpath))); } continue; } if (len > 4 && strcmp(name + len - 4, ".tmp") == 0) { char fullpath[MAXPGPATH]; char base[MAXPGPATH]; snprintf(fullpath, sizeof(fullpath), "%s/%s", path, name); /* * Remove only temps whose base is a strict CFS sidecar name — * the engine creates "<...>.cfp[.N].tmp" (compaction segment * temps) and "<...>.cfsmap.tmp" (snapshot writer temps) and * nothing else; a foreign "*.tmp" stays in place. */ strlcpy(base, name, sizeof(base)); base[len - strlen(".tmp")] = '\0'; if (!cfs_temp_base_is_sidecar(base)) { ereport(DEBUG1, (errmsg("CFS: \"%s\" is not a CFS sidecar name, left in place", fullpath))); continue; } if (unlink(fullpath) == 0) { ereport(LOG, (errmsg("CFS: removed leftover compaction temp file \"%s\"", fullpath))); stats->temp_files_removed++; } else if (errno != ENOENT) { ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not remove leftover temp file \"%s\": %m", fullpath))); } continue; } /* * Crash-safe compaction swap (single commit marker). A leftover * ".cfp.cfsswap" marker means activation was interrupted after the * candidate pair became durable: finish the renames now so the * relation opens from a consistent pair without waiting for the * open-path recovery. */ if (len > strlen(".cfp.cfsswap") && strcmp(name + len - strlen(".cfp.cfsswap"), ".cfp.cfsswap") == 0) { cfs_complete_swap_marker(path, name); continue; } /* * Orphan candidate files (".new"): a compaction that crashed before * reaching the commit marker leaves these behind with no matching * marker. Remove them so the old pair is used. When a commit marker * DOES exist, the candidate is part of an interrupted-but-committed * swap, so we leave it for cfs_complete_swap_marker() / the open * path. We check the marker on disk (not the iteration order) so the * decision is correct regardless of directory ordering. */ if (len > 4 && strcmp(name + len - 4, ".new") == 0) { char fullpath[MAXPGPATH]; char marker_path[MAXPGPATH]; struct stat MST; snprintf(fullpath, sizeof(fullpath), "%s/%s", path, name); /* * Derive the commit marker for this relation. All candidate * kinds (.cfp.new / .cfp.N.new / .cfsmap.new) share the marker * keyed off the .cfp base. For a numbered .cfp segment candidate * (".cfp.N.new") the trailing ".N" is stripped first. The * strict template check runs BEFORE the strip: it rejects a * segment ".0" (the engine numbers segments from 1), which * cfs_strip_trailing_segment() would otherwise silently remove * and turn a foreign ".cfp.0.new" into a plausible ".cfp" * candidate. Same contract as the ".tmp" branch above. */ { char base[MAXPGPATH]; size_t blen; strlcpy(base, name, sizeof(base)); base[len - strlen(".new")] = '\0'; if (!cfs_temp_base_is_sidecar(base)) { ereport(DEBUG1, (errmsg("CFS: \"%s\" is not a CFS sidecar name, left in place", fullpath))); continue; } /* Strip a trailing segment number (".cfp.N" -> ".cfp"). */ cfs_strip_trailing_segment(base); blen = strlen(base); if (blen > strlen(".cfp") && strcmp(base + blen - strlen(".cfp"), ".cfp") == 0) snprintf(marker_path, sizeof(marker_path), "%s/%s.cfsswap", path, base); else snprintf(marker_path, sizeof(marker_path), "%s/%.*s.cfp.cfsswap", path, (int) (blen - strlen(".cfsmap")), base); } if (stat(marker_path, &MST) == 0) { /* Marker present: committed swap, leave for activation. */ continue; } if (unlink(fullpath) == 0) ereport(LOG, (errmsg("CFS: removed orphan compaction candidate \"%s\"", fullpath))); else if (errno != ENOENT) ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not remove orphan candidate \"%s\": %m", fullpath))); continue; } /* * Replay CFS journal files (.cfsjrn). Only journals are scanned * here; the .cfp and .cfsmap are loaded by cfs_open() during replay. * * The strict sidecar parser is used instead of a hand-rolled * strchr/strtoul scan, so names the engine never creates (leading * zeroes and other divergent forms) are skipped. A journal never * carries a segment number, so segno is always 0 here; the transient * compaction names (.tmp/.new/.cfsswap) were already handled by the * branches above and are rejected by the parser by design. */ { RelFileNumber relnumber; CfsFileKind kind; unsigned segno; if (parse_cfs_sidecar_filename(name, &relnumber, &kind, &segno) && kind == CFS_FILE_JOURNAL) { RelFileLocatorBackend rlb; rlb.locator.spcOid = spcOid; rlb.locator.dbOid = dbOid; rlb.locator.relNumber = relnumber; rlb.backend = INVALID_PROC_NUMBER; cfs_replay_one_locator(rlb, MAIN_FORKNUM, stats); } } } FreeDir(dir); } /* * cfs_scan_all_db_dirs — walk every database directory in every tablespace * and process CFS sidecar files (cleanup + journal replay). */ static void cfs_scan_all_db_dirs(CfsRecoveryStats *stats) { DIR *dir; struct dirent *de; /* * Default tablespace: base//. */ dir = AllocateDir("base"); if (dir != NULL) { while ((de = ReadDir(dir, "base")) != NULL) { char dbpath[MAXPGPATH]; Oid dbOid; if (de->d_name[0] == '.') continue; dbOid = strtoul(de->d_name, NULL, 10); if (dbOid == 0 || dbOid > OID_MAX) continue; snprintf(dbpath, sizeof(dbpath), "base/%s", de->d_name); process_db_dir(dbpath, DEFAULTTABLESPACE_OID, dbOid, stats); } FreeDir(dir); } /* * Global tablespace: global/ (shared relations, dbOid = 0). */ process_db_dir("global", GLOBALTABLESPACE_OID, 0, stats); /* * User tablespaces: pg_tblspc////. * * PostgreSQL does NOT create a "base/" subdirectory inside user * tablespaces; relation files live directly under //. */ dir = AllocateDir("pg_tblspc"); if (dir != NULL) { while ((de = ReadDir(dir, "pg_tblspc")) != NULL) { char ts_path[MAXPGPATH]; Oid spcOid; DIR *ts_dir; struct dirent *ts_de; if (de->d_name[0] == '.') continue; spcOid = strtoul(de->d_name, NULL, 10); if (spcOid == 0 || spcOid > OID_MAX) continue; snprintf(ts_path, sizeof(ts_path), "%s/%s/%s", PG_TBLSPC_DIR, de->d_name, TABLESPACE_VERSION_DIRECTORY); ts_dir = AllocateDir(ts_path); if (ts_dir == NULL) continue; while ((ts_de = ReadDir(ts_dir, ts_path)) != NULL) { char dbpath[MAXPGPATH]; Oid dbOid; if (ts_de->d_name[0] == '.') continue; dbOid = strtoul(ts_de->d_name, NULL, 10); if (dbOid == 0 || dbOid > OID_MAX) continue; snprintf(dbpath, sizeof(dbpath), "%s/%s", ts_path, ts_de->d_name); process_db_dir(dbpath, spcOid, dbOid, stats); } FreeDir(ts_dir); } FreeDir(dir); } } /* ================================================================ * Public recovery API * ---------------------------------------------------------------- * The public surface is exactly the set of symbols with external * consumers: CfsRecoveryInit (StartupXLOG), the lifecycle hooks, the * corruption reporter (smgr paths) and CfsReplayAllJournals (the * test_cfs module drives it directly). Everything else stays static so * the compiler's -Wunused-function catches dead code as it appears. * ================================================================ */ int64 CfsReplayAllJournals(void) { CfsRecoveryStats stats; memset(&stats, 0, sizeof(stats)); ereport(DEBUG1, (errmsg("CFS: starting journal replay scan"))); cfs_scan_all_db_dirs(&stats); if (stats.total_replayed > 0) ereport(LOG, (errmsg("CFS: recovery replayed %lld journal record(s)", (long long) stats.total_replayed))); else ereport(DEBUG1, (errmsg("CFS: recovery found no journals needing replay"))); return stats.total_replayed; } void CfsRecoveryInit(void) { CfsRecoveryStats stats; memset(&stats, 0, sizeof(stats)); ereport(DEBUG1, (errmsg("CFS: recovery init starting"))); /* * Single pass: clean up leftover compaction temp files AND fold all CFS * journals. The walk itself (readdir + stat per relation) runs on every * startup; the heavy part - folding a relation's journal into its page * map, row by row - is gated on a non-empty journal, and its cost tracks * the journal (the changes since the last checkpoint), never the map, * so a clean restart (journals truncated at the last checkpoint) does * no map work at all. */ cfs_scan_all_db_dirs(&stats); ereport(LOG, (errmsg("CFS: recovery init complete " "(replayed %lld journal record(s), removed %d temp file(s), " "journals opened %d, folded %lld row(s))", (long long) stats.total_replayed, stats.temp_files_removed, stats.journals_opened, (long long) stats.rows_folded))); } /* ================================================================ * Centralised corruption handling * ================================================================ */ /* * cfs_corruption_guc_applies - true when a structural corruption report * may take the cfs_checksum_failure-driven severity: only a normal * backend session of a primary that is not replaying WAL. Recovery * (the startup scan, WAL redo), standby query execution (the cluster * keeps replaying, InRecovery is false in its backends but * RecoveryInProgress() is true) and auxiliary processes (the * checkpointer, the compaction bgworker, autovacuum) keep the * historical hard ERROR, so a 'panic' setting can neither put a standby * into a crash loop nor take the whole cluster down from a background * process (QDB-1507 U8, operator decisions Q9/Q10). */ bool cfs_corruption_guc_applies(void) { return MyBackendType == B_BACKEND && !InRecovery && !RecoveryInProgress(); } void cfs_report_corruption(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum, const char *detail, bool during_recovery) { int elevel; if (during_recovery) { /* * During recovery, the cfs_recovery_strict GUC controls severity. * When true, corrupt records are fatal; when false (default), a * WARNING is logged and recovery continues. In the startup process * an ERROR already means "the server does not come up", so PANIC * would only add a forced shutdown of a process that is failing to * start anyway. */ elevel = cfs_recovery_strict ? ERROR : WARNING; } else { /* * During normal backend reads, the cfs_checksum_failure GUC * determines severity. Both ERROR and PANIC longjmp out of the * caller; we never return a fabricated page. */ switch ((CfsChecksumFailureAction) cfs_checksum_failure) { case CFS_CHECKSUM_PANIC: elevel = PANIC; break; case CFS_CHECKSUM_ERROR: default: elevel = ERROR; break; } } /* * Journal-wide damage has no single block to name: callers pass * InvalidBlockNumber and the message omits the block part, so a * corruption report never claims a block it does not have. */ if (blocknum == InvalidBlockNumber) ereport(elevel, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: checksum or format corruption in relation " "%u/%u/%u, fork %u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber, forknum), errdetail("%s.", detail))); else ereport(elevel, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: checksum or format corruption in relation " "%u/%u/%u, fork %u, block %u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber, forknum, blocknum), errdetail("%s.", detail))); }