/*------------------------------------------------------------------------- * cfs_compact.c * Compressed File Store (CFS) — compaction primitives. * * Rebuilds the .cfp and .cfsmap sidecars of a relation fork so that they * contain only the live (most recent) compressed records, reclaiming the * space occupied by dead records left behind by append-only updates. * * Strategy (see cfs_compact.h): * 0. quiesce writers: hold the per-relation append lock for the whole * copy + swap window (every sidecar write — buffer flush, checkpoint, * immedsync — funnels through it) * 1. open the source relation read/write * 2. create .cfp.tmp + .cfsmap.cfscand * 3. copy every live record verbatim (no recompression) into .cfp.tmp * 4. write a fresh .cfsmap.cfscand snapshot * 5. fsync + atomic rename over the originals (durable commit marker) * 6. reset the journal durably, then drop the commit marker * 7. bump the shared-cache map generation (still under the append lock) * so writers that were waiting for the lock reopen the new pair * * Online mode (cfs_compact_online, QDB-1514) reshapes the same steps into * three phases without changing the swap protocol: * A. (exclusive append lock, short) mark the compaction owner in the * metadata slot, open the relation and pin its map+journal snapshot; * release the lock. The caller holds ShareUpdateExclusiveLock, so * readers and writers keep running. * B. (no locks) copy the snapshot's live records into the .cfp.tmp chain * and write + fsync the full .cfsmap.cfscand. Concurrent appends land in * the old chain beyond the snapshot's EOF. * C. (exclusive append lock, short) refresh the map to the authoritative * current state, transfer the records appended meanwhile (entries * whose generation moved or appeared), apply the changed rows to * .cfsmap.cfscand positionally, then run the swap protocol unchanged and * clear the ownership mark. The exclusive window is proportional to * the append stream during the copy, not to the relation size. * Offline mode (cfs_compact_online = off) keeps the historical single * window of step 0. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_compact.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #include #include "access/xlog.h" #include "miscadmin.h" #include "postmaster/bgworker.h" #include "postmaster/interrupt.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_compact.h" #include "storage/cfs/cfs_format.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_journal.h" #include "storage/cfs/cfs_map_file.h" #include "storage/cfs/cfs_path.h" #include "storage/cfs/cfs_shmem.h" #include "storage/cfs/cfs_stats.h" #include "storage/cfs/cfs_storage.h" #include "storage/cfs/cfs_swap.h" #include "storage/fd.h" #include "utils/backend_progress.h" #include "utils/injection_point.h" #include "utils/palloc.h" #include "utils/timestamp.h" #include "utils/wait_event.h" /* * Progress-reporting parameter indices for PROGRESS_COMMAND_CFS_COMPACT. * Kept in sync with the pg_stat_progress_cfs_compact view. The indices * are zero-based, like every PROGRESS_* param in vanilla: SQL param1 of * pg_stat_get_progress_info() is C index 0. * - param1: phase (1=initializing, 2=copying live blocks, 3=transferring * concurrent appends, 4=durable swap; the transfer phase exists only in * the online mode) * - param2: blocks_total (live + dead logical blocks; re-read at the * catch-up phase, where concurrent appends may have grown the map) * - param3: blocks_done (live blocks copied so far; set to blocks_total * once the copy phase completes, so the counter always reaches 100%) */ #define PROGRESS_CFS_PHASE_INIT 1 #define PROGRESS_CFS_PHASE_COPY 2 #define PROGRESS_CFS_PHASE_CATCHUP 3 #define PROGRESS_CFS_PHASE_SWAP 4 #define PROGRESS_CFS_PARAM_PHASE 0 #define PROGRESS_CFS_PARAM_BLOCKS_TOTAL 1 #define PROGRESS_CFS_PARAM_BLOCKS_DONE 2 #define PROGRESS_CFS_PARAM_STARTED_AT 3 /* The marker helpers moved to cfs_swap.c. */ /* * Open the temporary file of segment 'segno' of the destination chain * rooted at 'dst_cfp_path': ".tmp" for segment 0, ".N.tmp" for * segment N. Segment 0 additionally receives the reserved lead-in. * * The descriptor is opened with OpenTransientFile() so that it is closed * automatically by the resource owner if the compaction errors out while * the segment is still open; the success path closes it explicitly with * CloseTransientFile(). */ static int cfs_compact_open_dst_segment(const char *dst_cfp_path, uint32 segno) { char *path; int fd; path = cfs_segment_suffixed(dst_cfp_path, segno, ".tmp"); fd = OpenTransientFile(path, O_CREAT | O_RDWR | O_TRUNC | PG_BINARY); if (fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not create \"%s\": %m", path))); if (segno == 0) { CfsDataFileLeadIn leadin; /* * The compacted file is a new append-only lifespan: stamp it with a * fresh epoch so that incremental backups never confuse it with the * pre-compaction file of the same name. */ leadin.epoch = (uint64) GetCurrentTimestamp(); if (cfs_pwrite_all(fd, &leadin, sizeof(leadin), 0) != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not write .cfp.tmp lead-in"))); } ereport(DEBUG1, (errmsg("CFS: compaction: opened destination segment \"%s\"", path))); pfree(path); return fd; } /* * Open an existing destination segment for the catch-up phase: unlike * cfs_compact_open_dst_segment() this never truncates and never writes the * lead-in — the copy phase already created the chain. O_CREAT is still * needed: the records transferred meanwhile may cross the segment boundary * the copy ended inside, and the segment beyond it does not exist yet (the * plain append path creates segments on demand the same way). A fresh * non-zero segment needs no lead-in, and segment 0 was always created by * the copy phase itself. */ static int cfs_compact_open_dst_segment_existing(const char *dst_cfp_path, uint32 segno) { char *path; int fd; path = cfs_segment_suffixed(dst_cfp_path, segno, ".tmp"); fd = OpenTransientFile(path, O_CREAT | O_RDWR | PG_BINARY); if (fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not open \"%s\": %m", path))); pfree(path); return fd; } /* * Positionally rewrite one row of the candidate .cfsmap.cfscand. Rows have a * fixed length, so the row of block N lives at CFS_MAP_HEADER_SIZE + * N * CFS_MAP_ENTRY_SIZE — the same addressing the checkpoint fold uses. */ static void cfs_compact_write_map_row(int fd, const char *path, uint64 blocknum, const CfsMapEntry *entry) { off_t off = CFS_MAP_HEADER_SIZE + (off_t) blocknum * CFS_MAP_ENTRY_SIZE; if (cfs_pwrite_all(fd, entry, CFS_MAP_ENTRY_SIZE, off) != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not update row %llu of \"%s\"", (unsigned long long) blocknum, path))); } /* * qsort_arg comparator: order block indices by the physical offset of * their map entries. */ static int cfs_compact_offset_cmp(const void *a, const void *b, void *arg) { const CfsMapEntry *map = (const CfsMapEntry *) arg; uint64 ia = *(const uint64 *) a; uint64 ib = *(const uint64 *) b; if (map[ia].physical_offset < map[ib].physical_offset) return -1; if (map[ia].physical_offset > map[ib].physical_offset) return 1; return 0; } int64 cfs_compact_copy_live_records(const CfsRelation *cfs, const char *dst_cfp_path, CfsMapEntry *dst_map, bool do_fsync, uint64 *out_eof) { uint64 i; uint64 k; off_t dst_off = CFS_CFP_BASE_OFFSET; int dst_fd = -1; uint32 dst_seg = 0; int64 copied = 0; uint64 *live_blocks = NULL; uint64 nlive = 0; Assert(cfs != NULL && dst_cfp_path != NULL && dst_map != NULL && out_eof != NULL); Assert(cfs->cfp_path != NULL); /* * Copy live records in ascending source-offset order (updates leave block * order and offset order unrelated): reads and the one-entry read-fd * cache then run sequentially across the segment chain instead of * bouncing between segment descriptors on every record. */ if (cfs->map_hdr.nblocks > 0) { live_blocks = palloc(cfs->map_hdr.nblocks * sizeof(uint64)); for (i = 0; i < cfs->map_hdr.nblocks; i++) { if (CFS_MAP_ENTRY_VALID(&cfs->map[i])) live_blocks[nlive++] = i; } if (nlive > 1) qsort_arg(live_blocks, nlive, sizeof(uint64), cfs_compact_offset_cmp, (void *) cfs->map); } /* Never-written or dead blocks keep an invalid slot. */ for (i = 0; i < cfs->map_hdr.nblocks; i++) cfs_map_entry_init(&dst_map[i]); for (k = 0; k < nlive; k++) { const CfsMapEntry *e; size_t rec_size; char *buf; CfsMapEntry ne; i = live_blocks[k]; e = &cfs->map[i]; rec_size = CFS_RECORD_SIZE(e->compressed_size); buf = palloc(rec_size); /* * Verbatim copy: read the raw record through the storage layer so the * segmented address translation lives in one place. */ if (cfs_read_raw_record((CfsRelation *) cfs, (off_t) e->physical_offset, e->compressed_size, buf) != CFS_STORAGE_OK) { pfree(buf); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not read record for block %llu", (unsigned long long) i))); } /* * A record never crosses a segment boundary: the rollover rule is * shared with the append path (cfs_cfp_roll_offset). */ dst_off = (off_t) cfs_cfp_roll_offset((uint64) dst_off, rec_size); if (dst_fd < 0 || CFS_CFP_SEGNO(dst_off) != dst_seg) { if (dst_fd >= 0) { if (do_fsync && pg_fsync(dst_fd) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not fsync segment %u of \"%s\"", dst_seg, dst_cfp_path))); CloseTransientFile(dst_fd); } dst_seg = CFS_CFP_SEGNO(dst_off); dst_fd = cfs_compact_open_dst_segment(dst_cfp_path, dst_seg); } if (cfs_pwrite_all(dst_fd, buf, rec_size, CFS_CFP_SEG_OFF(dst_off)) != CFS_STORAGE_OK) { pfree(buf); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not write record for block %llu", (unsigned long long) i))); } pfree(buf); /* New entry: same payload, new offset, generation preserved. */ ne = *e; ne.physical_offset = (uint64) dst_off; cfs_map_entry_crc_set(&ne); dst_map[i] = ne; dst_off += rec_size; copied++; /* * Debug fault injection: stretch the compaction so a concurrent * writer to an unrelated relation can be tested for lock isolation. * No-op in production (default 0). */ if (cfs_debug_compact_delay_ms > 0) pg_usleep(cfs_debug_compact_delay_ms * 1000L); /* Bump progress per block. */ pgstat_progress_update_param(PROGRESS_CFS_PARAM_BLOCKS_DONE, (int64) (k + 1)); /* * The offline mode holds the append lock for the whole copy, and * holding an LWLock defers CHECK_FOR_INTERRUPTS() by core design (an * interrupt unwinding out of a locked shared-memory section could * corrupt it); the online mode runs this loop without the lock, but * keeps the same explicit poll so the response window is identical. * Poll the pending interrupt flags directly and abort explicitly * instead: the autovacuum shutdown-latency discipline (see the * do_autovacuum comments about not ignoring shutdown commands for too * long), translated to a section that cannot use the macro. An ERROR * abort releases the append lock and the pin through * LWLockReleaseAll() during transaction abort and the PG_CATCH in * cfs_compact_relation(). A FATAL, however, unwinds past every * PG_CATCH (they only catch ERROR): the append lock is still dropped * by LWLockReleaseAll(), but nothing would drop the pin -- a plain * shared counter with no resource-owner tie-in -- so release it here, * before the exit. The online-mode ownership mark needs no explicit * release: this process is dying, and the mark's liveness check reads * a dead owner as "no compaction running". */ if (unlikely(QueryCancelPending)) ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED), errmsg("canceling statement due to user request"))); if (unlikely(ProcDiePending || ShutdownRequestPending)) { cfs_map_cache_unpin(cfs->rlocator, cfs->forknum); if (AmBackgroundWorkerProcess()) ereport(FATAL, (errcode(ERRCODE_ADMIN_SHUTDOWN), errmsg("terminating background worker \"%s\" " "due to administrator command", MyBgworkerEntry->bgw_type))); else ereport(FATAL, (errcode(ERRCODE_ADMIN_SHUTDOWN), errmsg("terminating connection due to administrator command"))); } } /* An empty relation still gets segment 0 with just the lead-in. */ if (dst_fd < 0) dst_fd = cfs_compact_open_dst_segment(dst_cfp_path, 0); if (do_fsync && pg_fsync(dst_fd) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not fsync segment %u of \"%s\"", dst_seg, dst_cfp_path))); CloseTransientFile(dst_fd); if (live_blocks != NULL) pfree(live_blocks); if (out_eof != NULL) *out_eof = (uint64) dst_off; return copied; } /* * cfs_compact_transfer_appends — the catch-up pass of the online mode's * phase C (QDB-1514). The caller holds the append lock exclusively and has * just refreshed 'cfs' to the authoritative current map; this function * carries every record that changed since the copy-phase snapshot over to * the destination chain and rewrites the affected rows of the candidate * .cfsmap.cfscand positionally: * * - a fresh entry that is valid while the copied one is not, or carries a * newer generation, is copied from the old chain into the destination * chain (the chain is append-only, so the source record still lives in * the old .cfp this handle still points at); * - a fresh entry that is invalid while the copied one is valid (a DELETE * or a truncating RESIZE applied meanwhile) invalidates the copied row — * the already copied bytes stay behind as dead weight of the new chain * until the next compaction; * - a map that grew or shrank (RESIZE) extends or truncates the row * array; an extension leaves zero rows behind the last written one, * which load as INVALID entries exactly like a sparse fold gap. * * '*dst_map' (with '*dst_nslots' rows) is repalloc'd when the authoritative * map grew. '*dst_off' advances past every transferred record, and '*live' * is kept exact across the transfer: a record for a block the copy phase * never saw counts as live, a block deleted meanwhile stops counting, and a * replaced block (new generation over a copied one) keeps its single live * count — its copied bytes become dead weight of the new chain. The * candidate .cfsmap.cfscand descriptor 'map_tmp_fd' is rewritten, truncated or * extended to the exact row count, fsync'd (the copy phase already flushed * the bulk, so this fsync only carries the delta) and closed before * returning. Returns the number of records transferred. */ static int64 cfs_compact_transfer_appends(CfsRelation *cfs, const char *dst_cfp_path, const char *map_tmp_path, int map_tmp_fd, CfsMapEntry **dst_map, uint64 *dst_nslots, uint64 *dst_off, int64 *live, bool do_fsync, Oid progress_relid) { uint64 fresh_nblocks = cfs->map_hdr.nblocks; uint64 i; int dst_fd = -1; uint32 dst_seg = 0; int64 transferred = 0; /* Grow the row array when concurrent appends extended the relation. */ if (fresh_nblocks > *dst_nslots) { CfsMapEntry *grown; Size want = (Size) fresh_nblocks * CFS_MAP_ENTRY_SIZE; grown = (*dst_map == NULL) ? (CfsMapEntry *) palloc0(want) : (CfsMapEntry *) repalloc(*dst_map, want); for (i = *dst_nslots; i < fresh_nblocks; i++) cfs_map_entry_init(&grown[i]); *dst_map = grown; *dst_nslots = fresh_nblocks; } if (OidIsValid(progress_relid)) { pgstat_progress_update_param(PROGRESS_CFS_PARAM_BLOCKS_TOTAL, (int64) fresh_nblocks); pgstat_progress_update_param(PROGRESS_CFS_PARAM_BLOCKS_DONE, (int64) fresh_nblocks); } for (i = 0; i < fresh_nblocks; i++) { const CfsMapEntry *fresh = &cfs->map[i]; CfsMapEntry *cur = &(*dst_map)[i]; char *buf; size_t rec_size; CfsMapEntry ne; /* Same interrupt discipline as the copy loop (see above). */ if (unlikely(QueryCancelPending)) ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED), errmsg("canceling statement due to user request"))); if (unlikely(ProcDiePending || ShutdownRequestPending)) { cfs_map_cache_unpin(cfs->rlocator, cfs->forknum); if (AmBackgroundWorkerProcess()) ereport(FATAL, (errcode(ERRCODE_ADMIN_SHUTDOWN), errmsg("terminating background worker \"%s\" " "due to administrator command", MyBgworkerEntry->bgw_type))); else ereport(FATAL, (errcode(ERRCODE_ADMIN_SHUTDOWN), errmsg("terminating connection due to administrator command"))); } if (!CFS_MAP_ENTRY_VALID(fresh)) { if (CFS_MAP_ENTRY_VALID(cur)) { /* Deleted or truncated meanwhile: stop counting it. */ cfs_map_entry_init(cur); cfs_compact_write_map_row(map_tmp_fd, map_tmp_path, i, cur); (*live)--; } continue; } if (CFS_MAP_ENTRY_VALID(cur) && fresh->generation == cur->generation) continue; /* * A block the copy phase never saw becomes live here; a replaced * block keeps its single live count (the copied old version turns * into dead weight of the new chain). */ if (!CFS_MAP_ENTRY_VALID(cur)) (*live)++; rec_size = CFS_RECORD_SIZE(fresh->compressed_size); buf = palloc(rec_size); /* * Verbatim copy from the old chain, through the storage layer so * the segmented address translation lives in one place. */ if (cfs_read_raw_record(cfs, (off_t) fresh->physical_offset, fresh->compressed_size, buf) != CFS_STORAGE_OK) { pfree(buf); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not read record for block %llu", (unsigned long long) i))); } /* A record never crosses a segment boundary (the rollover rule). */ *dst_off = cfs_cfp_roll_offset(*dst_off, rec_size); if (dst_fd < 0 || CFS_CFP_SEGNO(*dst_off) != dst_seg) { if (dst_fd >= 0) { if (do_fsync && pg_fsync(dst_fd) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not fsync segment %u of \"%s\"", dst_seg, dst_cfp_path))); CloseTransientFile(dst_fd); } dst_seg = CFS_CFP_SEGNO(*dst_off); dst_fd = cfs_compact_open_dst_segment_existing(dst_cfp_path, dst_seg); } if (cfs_pwrite_all(dst_fd, buf, rec_size, CFS_CFP_SEG_OFF(*dst_off)) != CFS_STORAGE_OK) { pfree(buf); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not write record for block %llu", (unsigned long long) i))); } pfree(buf); /* New row: same payload and generation, new offset. */ ne = *fresh; ne.physical_offset = *dst_off; cfs_map_entry_crc_set(&ne); *cur = ne; cfs_compact_write_map_row(map_tmp_fd, map_tmp_path, i, cur); *dst_off += rec_size; transferred++; if (cfs_debug_compact_delay_ms > 0) pg_usleep(cfs_debug_compact_delay_ms * 1000L); } if (dst_fd >= 0) { if (do_fsync && pg_fsync(dst_fd) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not fsync segment %u of \"%s\"", dst_seg, dst_cfp_path))); CloseTransientFile(dst_fd); } /* * Fix the row count exactly: growth extends the file with zero rows * (they load as INVALID entries), a shrink drops the truncated tail — * the loader derives nblocks from the file size. */ { off_t want = CFS_MAP_HEADER_SIZE + (off_t) fresh_nblocks * CFS_MAP_ENTRY_SIZE; if (ftruncate(map_tmp_fd, want) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not resize \"%s\": %m", map_tmp_path))); } if (do_fsync && pg_fsync(map_tmp_fd) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not fsync \"%s\"", map_tmp_path))); CloseTransientFile(map_tmp_fd); return transferred; } int cfs_compact_relation(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsCompactOptions *opts, CfsCompactResult *result, Oid progress_relid) { /* volatile: modified inside PG_TRY(), read in PG_CATCH() */ CfsRelation *volatile cfs = NULL; volatile bool marked = false; char *cfp_path; char *map_path; char *jrn_path; char *map_tmp; int map_tmp_fd = -1; CfsMapEntry *new_map = NULL; uint64 new_map_slots = 0; CfsMapState new_state; int64 live; int64 transferred = 0; uint64 old_cfp_size; uint64 new_cfp_eof = CFS_CFP_BASE_OFFSET; bool online; if (opts == NULL) { static const CfsCompactOptions default_opts = CFS_COMPACT_OPTIONS_DEFAULT; opts = &default_opts; } if (result != NULL) MemSet(result, 0, sizeof(CfsCompactResult)); /* * Pin the metadata slot so the per-relation append lock embedded in it * remains valid for the entire compaction. cfs_map_cache_pin() raises * ERROR (with HINT) when the slot pool is exhausted, which is the right * outcome: the relation cannot be compacted without its lock. */ cfs_map_cache_pin(rlocator, forknum); /* * The mode is picked once per compaction; a SIGHUP change applies to * the next one. */ online = cfs_compact_online; /* * Quiesce writers around the snapshot. Every write to this relation's * sidecars (buffer flush, checkpoint, immedsync) funnels through the * per-relation append lock, so taking it exclusively for the open below * guarantees a coherent snapshot: no writer is mid-append and no * journal header rewrite (checkpoint reset, immedsync snapshot) races * the load. * * The offline mode (cfs_compact_online = off) simply never releases the * lock again: it is held for the whole copy + swap window, and the * caller's ShareUpdateExclusiveLock lets readers continue; foreground * writers stall on the append lock held here for the whole window. * * The online mode (QDB-1514) releases it right after the open, marks * itself the compaction owner in the metadata slot first — so the * interrupted-swap recovery of a concurrent open never touches this * compaction's candidate files — and re-acquires it for the short * catch-up + swap phase below. The caller holds ShareUpdateExclusive * Lock, so readers and writers keep running during the copy. */ PG_TRY(); { cfs_append_lock_acquire(rlocator, forknum, LW_EXCLUSIVE); if (online) { cfs_compact_mark_active(rlocator, forknum); marked = true; } /* * The append lock is held (above), so no writer can be mid-append: a torn * journal tail, if any crash damage survived the recovery scan, can be * repaired safely here. */ cfs = cfs_open(rlocator, forknum, CFS_OPEN_RDWR | CFS_OPEN_REPAIR_TAIL); } PG_CATCH(); { if (marked) cfs_compact_mark_inactive(rlocator, forknum); cfs_append_lock_release_after_error(rlocator, forknum); cfs_map_cache_unpin(rlocator, forknum); PG_RE_THROW(); } PG_END_TRY(); if (cfs == NULL) { if (online) cfs_compact_mark_inactive(rlocator, forknum); cfs_append_lock_release(rlocator, forknum); cfs_map_cache_unpin(rlocator, forknum); return CFS_STORAGE_ERROR; } /* * Phase A is over for the online mode: the snapshot (map + journal * replay, torn tail repaired) is pinned in the handle and the ownership * mark is published, so the append lock can go. Concurrent appends land * in the old chain beyond the snapshot's EOF — append-only, never a * rewrite — and the catch-up phase below carries them over. Readers * and writers of the relation run freely while the copy phase works; * the interrupted-swap recovery of a concurrent open is kept away from * the .tmp candidates by the mark. */ if (online) cfs_append_lock_release(rlocator, forknum); /* * The handle's descriptors are raw (not tracked by the VFD layer or the * resource owner) and its scratch/map memory lives in TopMemoryContext, * so a transaction abort reclaims neither: any ERROR between here and the * close at the end of the copy phase must close the handle explicitly. * Otherwise a caller that catches the error and retries (the background * compaction worker) leaks the descriptors and the memory for the rest of * the process lifetime. */ PG_TRY(); { /* Report compaction as a wait event. */ pgstat_report_wait_start(WAIT_EVENT_CFS_COMPACT); cfp_path = pstrdup(cfs->cfp_path); map_path = pstrdup(cfs->map_path); jrn_path = pstrdup(cfs->jrn_path); old_cfp_size = (uint64) cfs->cfp_write_off; if (result != NULL) result->old_cfp_size = old_cfp_size; ereport(DEBUG1, (errmsg("CFS: compacting relation: %llu logical blocks, cfp_size %llu", (unsigned long long) cfs->map_hdr.nblocks, (unsigned long long) old_cfp_size))); /* Start progress reporting. */ if (OidIsValid(progress_relid)) { pgstat_progress_start_command(PROGRESS_COMMAND_CFS_COMPACT, progress_relid); pgstat_progress_update_param(PROGRESS_CFS_PARAM_PHASE, PROGRESS_CFS_PHASE_INIT); pgstat_progress_update_param(PROGRESS_CFS_PARAM_BLOCKS_TOTAL, (int64) cfs->map_hdr.nblocks); pgstat_progress_update_param(PROGRESS_CFS_PARAM_BLOCKS_DONE, 0); /* * Record the start time as the internal TimestampTz value * (microseconds since 2000-01-01); the view reconstructs the * timestamptz from it. */ pgstat_progress_update_param(PROGRESS_CFS_PARAM_STARTED_AT, (int64) GetCurrentTimestamp()); } /* Allocate the new map. */ if (cfs->map_hdr.nblocks > 0) { new_map = palloc0(cfs->map_hdr.nblocks * CFS_MAP_ENTRY_SIZE); new_map_slots = cfs->map_hdr.nblocks; } /* * Copy live records into a fresh chain of temporary .cfp segments * (".tmp" / ".N.tmp"), segmented exactly like the live * chain. */ if (OidIsValid(progress_relid)) pgstat_progress_update_param(PROGRESS_CFS_PARAM_PHASE, PROGRESS_CFS_PHASE_COPY); live = cfs_compact_copy_live_records(cfs, cfp_path, new_map, opts->fsync, &new_cfp_eof); /* * The copy loop bumps BLOCKS_DONE per live record, so with dead * blocks it would stop below BLOCKS_TOTAL; report the copy phase as * complete. */ if (OidIsValid(progress_relid)) pgstat_progress_update_param(PROGRESS_CFS_PARAM_BLOCKS_DONE, (int64) cfs->map_hdr.nblocks); if (result != NULL) { result->live_blocks = (uint64) live; result->dead_blocks = (cfs->map_hdr.nblocks > (uint64) live) ? cfs->map_hdr.nblocks - (uint64) live : 0; } /* Build and write the candidate .cfsmap: prologue + entries, exact * size. The temp name carries the compaction-specific suffix so it * can never collide with a snapshot writer's ".tmp" (see * CFS_MAP_CANDIDATE_TMP_SUFFIX). */ new_state = cfs->map_hdr; new_state.cfp_size = new_cfp_eof; /* * A transient descriptor is closed automatically by the resource * owner if an ERROR escapes before the explicit close below. */ map_tmp = psprintf("%s%s", map_path, CFS_MAP_CANDIDATE_TMP_SUFFIX); map_tmp_fd = OpenTransientFile(map_tmp, O_CREAT | O_RDWR | O_TRUNC | PG_BINARY); if (map_tmp_fd < 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not create \"%s\": %m", map_tmp))); } /* Prologue + entries through the shared snapshot writer. */ (void) cfs_map_file_write_snapshot_fd(map_tmp_fd, map_tmp, new_map, new_state.nblocks); if (opts->fsync && pg_fsync(map_tmp_fd) != 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not fsync \"%s\"", map_tmp))); } /* Close the temp map fd before rename (required on some platforms). */ CloseTransientFile(map_tmp_fd); map_tmp_fd = -1; /* * The online mode keeps the source handle open: the catch-up phase * below reads the records appended during the copy through it. The * offline mode closes it here, as before — its fds must not pin the * files the swap renames. */ if (!online) { cfs_close(cfs); cfs = NULL; } } PG_CATCH(); { /* * The error escaped before the close at the end of the try block * (that close is its last statement), so the handle is still open. * Drop the ownership mark and release the append lock before the * metadata-slot pin, including in the offline mode. */ cfs_close(cfs); if (online) cfs_compact_mark_inactive(rlocator, forknum); cfs_append_lock_release_after_error(rlocator, forknum); cfs_map_cache_unpin(rlocator, forknum); PG_RE_THROW(); } PG_END_TRY(); /* * Crash-safe swap of the (.cfp[.N], .cfsmap) pair. * * Two independent durable_rename() calls are not atomic: a crash between * them would leave the new .cfp (with shifted physical offsets) paired * with the old .cfsmap, after which every read returns garbage. We use a * single durable commit marker so the pair switches atomically: * * 1. rename .cfp[.N].tmp -> .cfp[.N].new (per segment) and * .cfsmap.cfscand -> .cfsmap.new 2. create ".cfsswap" + fsync parent * dir <-- COMMIT POINT * 3. rename .cfp[.N].new -> .cfp[.N] (activate data, per segment) 4. * rename .cfsmap.new -> .cfsmap (activate map) 5. unlink stale .cfp * segments of the old chain beyond the new EOF 6. reset .cfsjrn + fsync * 7. unlink ".cfsswap" + fsync parent dir * * Recovery (cfs_recover_compaction, run on open) finishes the activation * renames, repeats the trailing-segment cleanup and the journal reset * when the marker is present, or discards the candidates when it is * absent, so the on-disk pair is always self-consistent. */ /* * Phase C (online mode): re-acquire the append lock, converge the * handle's map to the authoritative current state and carry the records * appended during the copy over to the candidate chain. The offline * mode never released the lock and skips the catch-up entirely — no * writer can have appended anything. * * The swap phase (rename / fsync / marker) and this catch-up can raise * ERROR at many points. Wrap both in PG_TRY() so the ownership mark, * the metadata-slot pin and the append lock are released cleanly on the * error path too — LWLockReleaseAll() during abort drops the append * LWLock, but the pin refcount is a plain shared-memory counter with no * transaction tie-in and would leak without this handler, and the mark * must not outlive the backend's own error. */ PG_TRY(); { char *map_new = psprintf("%s.new", map_path); char *swap_marker = psprintf("%s.cfsswap", cfp_path); uint32 segno; uint32 last_seg; int mfd; if (online) { cfs_append_lock_acquire(rlocator, forknum, LW_EXCLUSIVE); /* Test seam: the catch-up window, before the map converges. */ INJECTION_POINT("cfs-compaction-catchup", NULL); if (OidIsValid(progress_relid)) pgstat_progress_update_param(PROGRESS_CFS_PARAM_PHASE, PROGRESS_CFS_PHASE_CATCHUP); /* * Converge the private map to the current on-disk state: the * journal delta since the snapshot, or a full reload when a * checkpoint reset (or an immedsync snapshot) replaced the map * meanwhile. The repair flag is allowed — this backend holds * the append lock, so no writer is mid-append. A full reload * is the one part of the window that scales with the map size, * not with the append stream: it only happens when a checkpoint * completed during the copy. */ if (cfs_refresh_map(cfs, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: compaction: could not refresh map for relation %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); /* * The old chain size is reported below, after the transfer, * from the chain itself: the refresh's delta path does not * advance cfp_write_off, so the handle's field would describe * the snapshot, not the pair being replaced. */ map_tmp_fd = OpenTransientFile(map_tmp, O_RDWR | PG_BINARY); if (map_tmp_fd < 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not open \"%s\": %m", map_tmp))); } transferred = cfs_compact_transfer_appends(cfs, cfp_path, map_tmp, map_tmp_fd, &new_map, &new_map_slots, &new_cfp_eof, &live, opts->fsync, progress_relid); map_tmp_fd = -1; /* closed by the transfer */ if (result != NULL) { result->live_blocks = (uint64) live; /* * Dead blocks of the converged pair: every authoritative * block that is not live. The snapshot-time count taken * above no longer describes the relation the copy raced * with. */ result->dead_blocks = (cfs->map_hdr.nblocks > (uint64) live) ? cfs->map_hdr.nblocks - (uint64) live : 0; /* * The old chain at its real size: the delta-replay path of * the refresh above does not advance cfp_write_off, so the * snapshot's EOF would understate the reclaimed volume. * Stat the chain directly (we hold the append lock, the * old pair cannot grow anymore). */ { int64 old_size = cfs_segmented_sidecar_size(rlocator, forknum, CFS_FILE_DATA); if (old_size > 0) result->old_cfp_size = (uint64) old_size; } } /* The candidate summary now describes the converged pair. */ new_state.nblocks = cfs->map_hdr.nblocks; new_state.cfp_size = new_cfp_eof; if (cfs->map_hdr.max_generation > new_state.max_generation) new_state.max_generation = cfs->map_hdr.max_generation; ereport(DEBUG1, (errmsg("CFS: compaction catch-up: %lld records transferred", (long long) transferred))); } /* * Close the source relation so its fds don't pin the files we * rename (the online mode kept it open for the catch-up reads). */ if (cfs != NULL) { cfs_close(cfs); cfs = NULL; } if (OidIsValid(progress_relid)) pgstat_progress_update_param(PROGRESS_CFS_PARAM_PHASE, PROGRESS_CFS_PHASE_SWAP); /* Stage every candidate segment of the new chain. */ for (segno = 0;; segno++) { char *seg_tmp = cfs_segment_suffixed(cfp_path, segno, ".tmp"); char *seg_new = cfs_segment_suffixed(cfp_path, segno, ".new"); if (!cfs_swap_path_exists(seg_tmp)) { pfree(seg_tmp); pfree(seg_new); /* * Segment 0 must always exist (the copy creates it even for * an empty relation): its absence means external interference * or a stat failure, and proceeding would activate the new * map over the old data chain. */ if (segno == 0) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: compaction: candidate file \"%s.tmp\" is missing", cfp_path))); break; } if (durable_rename(seg_tmp, seg_new, ERROR) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not rename \"%s\" to \"%s\"", seg_tmp, seg_new))); pfree(seg_tmp); pfree(seg_new); } if (durable_rename(map_tmp, map_new, ERROR) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not rename \"%s\" to \"%s\"", map_tmp, map_new))); /* * Test seam: park the compaction with the candidate pair staged but * the commit marker not yet written - the exact window the * checkpoint's handle open must not race into (the lock-free opener * issue cfs_swap.c warns about; see cfs_open_lazy_pinned). */ INJECTION_POINT("cfs-compaction-staged", NULL); /* * A backup started while the candidate pair was being built would * copy a mismatched (.cfp, .cfsmap) trio if the swap commits * underneath it: refuse to commit while a non-exclusive backup is in * progress. The WAL insertion locks are held from the check to the * durable marker, so a backup can only start before the check (and be * seen) or after the marker is durable — never in between. The * orphaned .tmp/.new candidates of an aborted attempt are discarded * by the next compaction or by the startup recovery cleanup. WAL * insertion stalls for the two fsyncs below, which is acceptable for * a rare maintenance operation. */ BackupInProgressLock(); if (BackupInProgress()) { BackupInProgressUnlock(); ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("cannot compact CFS relation while a base backup is in progress"), errhint("Retry the compaction after the backup has finished."))); } /* * Commit point: a durable marker means the candidate pair is ready. A * transient descriptor is closed automatically by the resource owner * if an ERROR escapes before the explicit close below. */ mfd = OpenTransientFile(swap_marker, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY); if (mfd < 0) { BackupInProgressUnlock(); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not create commit marker \"%s\": %m", swap_marker))); } if (pg_fsync(mfd) != 0) { BackupInProgressUnlock(); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not fsync commit marker \"%s\"", swap_marker))); } CloseTransientFile(mfd); cfs_fsync_parent_dir(swap_marker, ERROR); BackupInProgressUnlock(); /* Activate the candidate pair, segment by segment. */ for (segno = 0;; segno++) { char *seg_new = cfs_segment_suffixed(cfp_path, segno, ".new"); char *seg_path = cfs_segment_path(cfp_path, segno); if (!cfs_swap_path_exists(seg_new)) { pfree(seg_new); pfree(seg_path); break; } if (durable_rename(seg_new, seg_path, ERROR) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not rename \"%s\" to \"%s\"", seg_new, seg_path))); pfree(seg_new); pfree(seg_path); } if (durable_rename(map_new, map_path, ERROR) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: compaction: could not rename \"%s\" to \"%s\"", map_new, map_path))); /* * Remove stale segments of the old chain beyond the new EOF *before* * dropping the commit marker: the append EOF discovery walks to the * last existing segment, so a leftover segment would resurrect dead * space as the append target. Recovery repeats this step when the * marker survives a crash, so the window is closed. The cleanup rule * is shared with recovery via cfs_unlink_trailing_segments(). */ last_seg = (new_cfp_eof <= CFS_CFP_BASE_OFFSET) ? 0 : CFS_CFP_SEGNO(new_cfp_eof - 1); cfs_unlink_trailing_segments(cfp_path, last_seg); cfs_fsync_parent_dir(cfp_path, ERROR); /* * Reset the journal *before* dropping the commit marker, and make the * reset durable. The freshly swapped-in .cfsmap snapshot is now the * authoritative map, so there is nothing left to replay — and the * old journal records reference offsets of the replaced .cfp, so a * crash that undoes the reset would replay them on top of the new map * and corrupt it. When the marker survives a crash, recovery repeats * this reset (idempotently). The map summary stamped into the fresh * header describes exactly what compaction built: every copied byte * is live, and the watermark comes from the snapshot just installed. */ if (opts->reset_journal) cfs_journal_reset_file(jrn_path, new_state.max_generation); /* Drop the commit marker; the new pair is now authoritative. */ cfs_swap_unlink_marker(swap_marker); cfs_fsync_parent_dir(cfp_path, ERROR); pfree(map_new); pfree(swap_marker); } { uint64 new_cfp_size = new_cfp_eof; if (result != NULL) { result->new_cfp_size = new_cfp_size; result->reclaimed_bytes = (result->old_cfp_size > result->new_cfp_size) ? result->old_cfp_size - result->new_cfp_size : 0; } /* * Publish the swap while still holding the append lock: drop the * stale per-block cache entries and bump the map generation, so a * writer that was waiting on the lock observes the new generation and * reopens the new sidecar pair instead of writing into the replaced * inode. The metadata slot is kept alive and marked dirty-checkpoint * so the next CfsCheckpoint() snapshots the fresh map and clears the * journal. * * The shared block-map segments of the relation carry physical * offsets of the OLD .cfp: drop them, the next lookup re-loads them * from the new .cfsmap. */ cfs_map_cache_compact_reset(rlocator, forknum); cfs_shared_map_invalidate_relation(rlocator, forknum); /* * Reset the dead-space counters here, inside the same append-lock * section as the swap publication itself: a checkpoint that starts * right after the release takes its dead_base from the already reset * value, so the compaction's reset and the checkpoint's delta can * never clobber each other (the counter ownership flips with the * generation bump, atomically). */ cfs_stats_note_compaction(rlocator, forknum, (int64) GetCurrentTimestamp()); /* * The compaction is complete: clear the ownership mark while still * under the append lock. The candidates are gone by now, so even a * recovery pass that runs right after the clear finds nothing of * this compaction to clean. */ if (online) cfs_compact_mark_inactive(rlocator, forknum); } PG_CATCH(); { /* * Catch-up or swap-phase ERROR: close the handle, clear the mark, * release any owned append lock before dropping the pin, then re-throw so the caller (background worker / * pg_cfs_compact) sees the original error. */ if (cfs != NULL) cfs_close(cfs); if (online) cfs_compact_mark_inactive(rlocator, forknum); cfs_append_lock_release_after_error(rlocator, forknum); cfs_map_cache_unpin(rlocator, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rlocator, forknum); cfs_map_cache_unpin(rlocator, forknum); ereport(DEBUG1, (errmsg("CFS: compaction complete: %lld live records, cfp %llu -> %llu bytes", (long long) live, (unsigned long long) old_cfp_size, result ? (unsigned long long) result->new_cfp_size : 0ULL))); if (new_map) pfree(new_map); pfree(cfp_path); pfree(map_path); pfree(jrn_path); pfree(map_tmp); pgstat_report_wait_end(); /* Finish progress reporting. */ if (OidIsValid(progress_relid)) pgstat_progress_end_command(); return CFS_STORAGE_OK; }