/*------------------------------------------------------------------------- * cfs_checkpoint.c * Compressed File Store (CFS) — the checkpoint's two-phase journal * fold. * * After the buffer manager has flushed all dirty buffers (which wrote the * compressed records into .cfp and appended the journal updates), every * dirty CFS relation goes through the two-phase checkpoint implemented * here. The state machine, its phases and the durability contract are * described above cfs_checkpoint_begin() below. * * The handle stays LAZY for the whole checkpoint: the fold reads the * journal and rewrites exactly the rows it names, straight through the * map file descriptor, so the checkpoint's cost tracks the journal - the * changes since the previous checkpoint - and never the table size. No * full map is ever materialized here. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_checkpoint.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/xlog.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_checkpoint.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_state.h" #include "storage/cfs/cfs_storage.h" #include "storage/fd.h" #include "storage/smgr.h" /* ---------------------------------------------------------------- * Checkpoint integration * * After the buffer manager has flushed all dirty buffers (which wrote the * compressed records into .cfp and appended the journal updates), every * dirty CFS relation goes through the two-phase checkpoint: * phase 1 runs lock-free and folds the journal into .cfsmap row by row * (with the .cfp and journal already fsynced), then a short phase 2 * under the exclusive append lock rewrites the surviving journal tail, * resets the journal and stamps its header. This bounds the journal * size and makes the state durable across a crash. * * The checkpoint is a small state machine: cfs_checkpoint_begin() opens * the handle and runs phase 1, cfs_checkpoint_fold_tail() runs phase 2 * up to the resize, cfs_checkpoint_reset() resets the journal and * publishes the statistics, and cfs_checkpoint_cleanup() (PG_FINALLY * only) releases the append lock and the handle whatever happened. * ---------------------------------------------------------------- */ typedef struct CfsCheckpointState { RelFileLocatorBackend rlocator; ForkNumber forknum; CfsRelation *cfs; CfsJournalFoldResult fold1; /* phase-1 fold outcome */ off_t fold_limit; /* journal end sampled before fsyncs */ CfsStateSnapshot fold_base; /* ownership-state base of that sample: phase * 2 switches on the judge's verdict against * it (cfs_state.c) */ uint64 fold_superseded; /* superseded rows of both folds */ uint64 truncate_rows; /* rows the truncating RESIZE dropped * (dead_pages input, like above) */ uint64 dead_base; /* dead_bytes the previous owner left */ uint64 dead_delta; /* live payload this checkpoint turns dead * (superseded + truncated rows) */ /* * QDB-1507 U1: the sampled dead_base predates the last crash (or * the statistics slot is missing entirely), so the base must be * recomputed from the folded map before publication. */ bool dead_base_stale; int64 folded_rows; /* rows written by both folds */ uint32 max_generation; /* watermark stamped by the reset */ bool append_held; /* the exclusive lock is ours */ bool not_ours; /* a foreign reset or swap owns the state, or * phase 1 refused the journal before any * work: skip, don't count */ bool recovery_deferred; /* mid-journal corruption during the * end-of-recovery checkpoint: skip, count * (journal kept for a retry) */ } CfsCheckpointState; /* * cfs_checkpoint_begin - open-phase work and phase 1 of the fold. * * The fsyncs and the journal fold into the map run WITHOUT the append * lock: writers append journal records and extend the relation freely; * the records they add during the fold land beyond its stop offset and * survive as the journal tail. A record whose .cfp data is not yet * durable stops the fold (see cfs_journal_fold), and the sidecar-pair * swaps of compaction or immedsync - or the generation bump of a * concurrent TRUNCATE - are detected in phase 2. * * The lazy handle may have lost a race with immedsync/compaction while it * was opening: the map descriptor can name the replaced inode while the * journal baseline already reads the new pair. Take the append lock for * the identity check (a reopen resolves an interrupted swap and is only * legal under that lock or in recovery), reopen the handle if the path * moved, and sample the fold boundary and incarnation from the same * consistent state. After the release a later swap is caught by the * phase-2 checks. * * Persist this relation's sidecars in durability order: data -> journal * -> fold the journal into the map, then reset the journal. Any failure * is fatal: * * - an fsync failure of the data or journal file escalates to PANIC via * data_sync_elevel() (like md.c): a checkpoint that reports success * without durable data lets the WAL needed to rebuild the relation be * recycled, so the data becomes irrecoverable after the next crash. * * - a fold failure raises ERROR, which unwinds the whole * cfs_for_each_cfs_relation() loop and aborts the checkpoint. This is * the same "durability failure on one file is fatal for the checkpoint" * contract as vanilla PostgreSQL; the failing relation is deliberately * NOT skipped. The journal is left intact, so the next checkpoint can * retry the fold. cfs_fsync_kind() only returns on success, so the * guarded calls below cover the remaining "file not open" defensive * cases. */ /* * The shared fsync step of both phases: one report site for the data and * journal fsyncs (the four copies the review counted became this one). * The message text is unchanged. */ static void cfs_checkpoint_fsync(CfsRelation *cfs, CfsFileKind kind, RelFileLocatorBackend rlocator) { if (cfs_fsync_kind(cfs, kind) != CFS_STORAGE_OK) ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: checkpoint could not fsync %s file for %u/%u/%u", kind == CFS_FILE_DATA ? "data" : "journal", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); } static void cfs_checkpoint_begin(CfsCheckpointState *state) { CfsRelation *cfs = state->cfs; RelFileLocatorBackend rlocator = state->rlocator; /* * Sample the fold boundary and the whole ownership-state base BEFORE the * fsyncs: every record below the boundary references .cfp data the fsync * below is about to flush, so the fold may carry it; anything appended * after the sample stays in the tail for phase 2. Phase 2 re-derives * nothing: it switches on cfs_state_check() against this snapshot (the * judge's caller mask table lives in cfs_state.c). */ cfs_append_lock_acquire(rlocator, state->forknum, LW_EXCLUSIVE); state->append_held = true; (void) cfs_reopen_if_map_swapped(cfs); cfs_state_capture(cfs, &state->fold_base); state->fold_limit = state->fold_base.jrn_size; if (state->fold_limit < (off_t) CFS_JOURNAL_HEADER_SIZE) state->fold_limit = (off_t) CFS_JOURNAL_HEADER_SIZE; cfs_append_lock_release(rlocator, state->forknum); state->append_held = false; /* * The fold boundary IS the sampled journal size. Without it nothing can * be proven about what the journal holds, and the silent clamp to the * header size above would let phase 2 reset the journal without folding * it - destroying records that were never proven durable in the map. Fail * the relation instead (a plain ERROR: the checkpointer logs it and * carries on, exactly like a fold failure); the journal and the dirty * mark stay as they are, so the next checkpoint retries. The same * contract the other consumers of the size signal already uphold * (cfs_scan_torn_is_tail, cfs_journal_tail_changed). */ if (!state->fold_base.jrn_fd_valid) 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 checkpoint retries."))); /* * Header damage already present at the capture is not a race window phase * 2 could skip over: the header is what the reset's identity check * compares, so a permanently unreadable header would turn every * checkpoint into fold-all-then-skip - the journal growing without * converging, silently. Fail the relation instead (a plain ERROR, the * journal and the dirty mark preserved, so the next checkpoint retries), * the same signal every other consumer of the header raises (replay: * ERROR, verify: ERROR). The HEADER_STALE skip of phase 2 stays reserved * for the genuine window "readable at the capture, unreadable by the * check". * * The end-of-recovery exception is shared with the mid-journal corruption * check below: that checkpoint runs before recovery is complete, and an * ERROR there would abort startup over damage an explicit checkpoint can * safely fail on - skip the relation instead (not_ours: no phase-1 work * ran, so the driver's count stays honest), and every later, explicit * checkpoint retries and fails loudly until the damage is repaired. */ if (state->fold_base.jrn_size < (off_t) CFS_JOURNAL_HEADER_SIZE) { if (RecoveryInProgress()) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: journal \"%s\" is shorter than its header", cfs->jrn_path), errdetail("The journal is preserved; the next checkpoint retries."))); state->not_ours = true; return; } /* * Structural journal damage outside WAL replay: in a normal * backend session route through cfs_report_corruption() * (QDB-1507 U8, severity by cfs_checksum_failure); everywhere * else - including this checkpointer - keep the historical * direct ERROR, so a 'panic' setting never aborts the whole * cluster from a background process (cfs_corruption_guc_applies). */ if (cfs_corruption_guc_applies()) cfs_report_corruption(state->rlocator, state->forknum, InvalidBlockNumber, psprintf("journal \"%s\" is shorter than " "its header", cfs->jrn_path), false); ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: journal \"%s\" is shorter than its header", cfs->jrn_path), errdetail("The journal is preserved; the next checkpoint retries."))); } if (!state->fold_base.jrn_header_valid) { if (RecoveryInProgress()) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: journal \"%s\" has an unreadable header", cfs->jrn_path), errdetail("The journal is preserved; the next checkpoint retries."))); state->not_ours = true; return; } /* * Same routing as the short-journal branch above (QDB-1507 U8): * normal backend -> centralised handler; otherwise the direct * ERROR below (cfs_corruption_guc_applies). */ if (cfs_corruption_guc_applies()) cfs_report_corruption(state->rlocator, state->forknum, InvalidBlockNumber, psprintf("journal \"%s\" has an " "unreadable header", cfs->jrn_path), false); ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: journal \"%s\" has an unreadable header", cfs->jrn_path), errdetail("The journal is preserved; the next checkpoint retries."))); } cfs_checkpoint_fsync(cfs, CFS_FILE_DATA, rlocator); cfs_checkpoint_fsync(cfs, CFS_FILE_JOURNAL, rlocator); /* * Fold the journal into the map in place: only the rows the journal * carries are rewritten. RESIZE is only collected here - phase 2 applies * it under the append lock, so readers never see a map shorter than the * logical size. Raises ERROR on failure, aborting the whole checkpoint; * the journal is still intact, so the next checkpoint retries. */ state->folded_rows = cfs_journal_fold(cfs, CFS_JOURNAL_HEADER_SIZE, state->fold_limit, 1, &state->fold1); state->fold_superseded = state->fold1.superseded_pages; /* * A torn record with records still following it is corruption, not a * crash artifact: the records behind it are the only durable trace of * their changes. Abort before phase 2 resets the journal, so the valid * tail survives for a retry. A plain ERROR: phase 1 holds no append * lock, and the checkpointer logs it and carries on to the next * checkpoint request. * * The end-of-recovery checkpoint is the exception: it runs before * recovery is complete and a failure there aborts startup altogether, * which would make a corrupt journal unrecoverable without manual * intervention and break the non-strict contract of starting over it. * Skip this relation for that checkpoint instead: the journal and the * dirty mark stay as they are, so every later, explicit checkpoint * retries and fails loudly until the damage is repaired. */ if (state->fold1.torn_stop && !state->fold1.torn_is_tail) { if (RecoveryInProgress()) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: checkpoint stopped at a corrupt journal record in the middle of \"%s\"", cfs->jrn_path), errdetail("The journal is preserved; the next checkpoint retries."))); state->recovery_deferred = true; return; } ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: checkpoint stopped at a corrupt journal record in the middle of \"%s\"", cfs->jrn_path), errdetail("Records following offset %lld are preserved for a retry.", (long long) state->fold1.stop_off))); } /* * The two numbers the reset stamps, both computed without ever touching * the map rows: * * The generation watermark is the journal header's monotone stamp * (surviving every reset) merged with the folds' own watermarks below and * in phase 2: the apply engine raises a fold's watermark for every UPDATE * record it visits, skipped ones included, and the two folds cover the * journal from its header to the end sampled under the append lock - so * no journal scan is needed and the journal is read exactly once. An * unreadable header falls back to the handle's cached value; the reset * below re-reads the header itself for the incarnation bump. * * The dead-space delta accumulates in the fold itself: every superseded * row's payload (the fold reads it anyway to count the supersession) * turns from live to dead. It is published in phase 2 on top of the * dead_bytes the previous owner left. */ { CfsJournalFileHeader jhdr; if (cfs_journal_read_header(cfs->jrn_fd, &jhdr)) state->max_generation = jhdr.max_generation; else state->max_generation = cfs->map_hdr.max_generation; } state->dead_delta = state->fold1.superseded_bytes; { CfsStatsSnapshot prev; /* * Sample the stale mark together with the base (QDB-1507 U1): * a restored value predates the last crash, and a missing slot * may never have been persisted at all - both need a map-based * base in cfs_checkpoint_reset. */ if (cfs_stats_snapshot(rlocator, state->forknum, &prev)) { state->dead_base = prev.dead_bytes; state->dead_base_stale = cfs_stats_slot_stale(rlocator, state->forknum); } else { /* * No slot: a crashed boot may never have persisted this * relation's counters at all. */ state->dead_base_stale = true; } } /* The fold's generation joins the watermark the reset stamps. */ if (state->fold1.max_generation > state->max_generation) state->max_generation = state->fold1.max_generation; } /* * cfs_checkpoint_fold_tail - phase 2 up to the resize, under the short * exclusive section: verify that the fold target survived phase 1, fold * the tail that appeared meanwhile, and apply the last RESIZE. Returns * false (with the lock already released) when an identity check failed * and the reset must not run; true leaves the append lock held for * cfs_checkpoint_reset(). */ static bool cfs_checkpoint_fold_tail(CfsCheckpointState *state) { CfsRelation *cfs = state->cfs; RelFileLocatorBackend rlocator = state->rlocator; bool have_resize = state->fold1.have_resize; BlockNumber resize_target = state->fold1.resize_target; int state_fl; cfs_append_lock_acquire(rlocator, state->forknum, LW_EXCLUSIVE); state->append_held = true; /* * One judge, one verdict: every staleness signal phase 2 ever checked by * hand (map inode, incarnation, shared generation) comes back as flags * from cfs_state_check(); the order of the three not_ours branches below * only picks which DEBUG report explains the skip. */ state_fl = cfs_state_check(&state->fold_base, cfs, state->fold_base.jrn_size, NULL); if (state_fl & CFS_STATE_JRN_STAT_FAILED) { /* * The journal size became unknowable between the phases: no fold * boundary can be proven, so no reset may run. The journal and the * dirty mark stay as they are; the next checkpoint retries. */ ereport(DEBUG1, (errmsg("CFS: checkpoint skipped journal reset for %u/%u/%u: journal size unverifiable", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); state->not_ours = true; goto not_ours; } if (state_fl & CFS_STATE_MAP_SWAPPED) { /* * immedsync (which does not bump the shared generation) or compaction * replaced the .cfsmap while phase 1 ran: our row pwrites went to the * replaced inode, and the journal now belongs to the new pair * (already reset by the swap). Leave both alone; the next checkpoint * folds the new journal. */ ereport(DEBUG1, (errmsg("CFS: checkpoint skipped journal reset for %u/%u/%u: page map replaced", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); state->not_ours = true; goto not_ours; } if (state_fl & CFS_STATE_JRN_RESET) { /* * A foreign journal reset (immedsync holds this exclusive lock, * snapshots and resets) interleaved with the fold: the fold_stop * offset refers to the pre-reset layout. The foreign reset already * carried everything - its snapshot ran under this lock - so the * journal and the dirty mark stay as the resetter left them. */ ereport(DEBUG1, (errmsg("CFS: checkpoint skipped journal reset for %u/%u/%u: journal incarnation moved", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); state->not_ours = true; goto not_ours; } if (state_fl & CFS_STATE_GEN_MOVED) { /* * A compaction swapped the sidecar pair while the fold was running: * our row pwrites went to the replaced inode (harmless, it is * unlinked) and the journal on disk belongs to the new pair, already * reset by the compaction itself. Leave the journal and the dirty * mark alone - the next checkpoint folds whatever the new journal * holds. */ ereport(DEBUG1, (errmsg("CFS: checkpoint skipped journal reset for %u/%u/%u: generation moved", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); state->not_ours = true; goto not_ours; } if (state_fl & CFS_STATE_JRN_HEADER_STALE) { /* * The journal header became unreadable while phase 1 ran (it was * valid at the capture): the incarnation cannot be compared, so the * fold target can no longer be proven ours. Leave the journal alone * - the next checkpoint re-captures and retries. */ ereport(DEBUG1, (errmsg("CFS: checkpoint skipped journal reset for %u/%u/%u: journal header unverifiable", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); state->not_ours = true; goto not_ours; } /* * Records appended after the phase-1 boundary (or after the fold's clean * end) were not folded. Fold them now, still under the exclusive append * lock: no writer can add more, so the journal is empty afterwards and * the reset below is final. * * A torn stop in phase 1 means the journal holds a record no replay can * interpret. Mid-file corruption already aborted in phase 1, so this is * a torn tail: the crash artifact with nothing valid behind it, dropped * with the reset instead of folded. */ if (!state->fold1.torn_stop) { off_t jrn_end = cfs_fd_size(cfs->jrn_fd); if (jrn_end < (off_t) CFS_JOURNAL_HEADER_SIZE) jrn_end = (off_t) CFS_JOURNAL_HEADER_SIZE; if (jrn_end > state->fold1.stop_off) { CfsJournalFoldResult fold2; int64 folded; /* * The tail's .cfp and journal bytes may not be durable: phase 1 * fsynced both before the boundary sample, and these records were * appended after it. Persist data and journal before any tail * row reaches the map. The journal fsync is load-bearing: * without it a crash in the map fsync could leave a torn map row * whose covering journal record never reached the disk - * "corruption with no covering record", and silent data loss for * relations created since the last checkpoint under minimal WAL. * Durability order: data -> journal -> map -> journal reset. */ cfs_checkpoint_fsync(cfs, CFS_FILE_DATA, rlocator); cfs_checkpoint_fsync(cfs, CFS_FILE_JOURNAL, rlocator); folded = cfs_journal_fold(cfs, state->fold1.stop_off, jrn_end, 2, &fold2); state->folded_rows += folded; state->fold_superseded += fold2.superseded_pages; state->dead_delta += fold2.superseded_bytes; /* * Phase 1 stopped cleanly, yet the tail holds a torn record with * records behind it: still corruption, and the records behind it * must not be dropped by the reset below. A plain ERROR is safe * here: PG_FINALLY releases the append lock on the way out, and * the journal is left intact for the next checkpoint. Escalating * to PANIC would crash-restart the cluster over a corrupt record * that aborted phase 1 would have handled without one. */ if (fold2.torn_stop && !fold2.torn_is_tail) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: checkpoint stopped at a corrupt journal record in the middle of \"%s\"", cfs->jrn_path), errdetail("The journal is preserved; the next checkpoint retries."))); if (fold2.max_generation > state->max_generation) state->max_generation = fold2.max_generation; if (fold2.have_resize) { have_resize = true; resize_target = fold2.resize_target; } } } else if (cfs_journal_tail_changed(cfs, state->fold1.stop_off)) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: checkpoint tail changed during the fold of \"%s\"", cfs->jrn_path), errdetail("The journal is preserved; the next checkpoint retries."))); /* * Apply the last RESIZE seen in either phase, now that readers are * excluded: a shorter map must never be visible while a reader still * trusts the old logical size. This is THE truncation point of the * design: the live path (cfs_truncate) only journals the RESIZE - it runs * inside RelationTruncate()'s critical section, where neither an * O(dropped rows) tail read nor an I/O failure PANIC belongs - so the map * file keeps its dead tail until this application charges the dropped * payloads (the one moment they are still readable) and truncates the * file, all under the append lock and outside any critical section. The * work is bounded by what the truncation itself removes, exactly like the * fold's own row work. (A growing RESIZE only adds hole rows, which carry * no payload.) */ if (have_resize) { uint64 old_rows = cfs_map_rows_from_size(cfs_fd_size(cfs->map_fd)); if (resize_target < old_rows) { uint64 tail_live; uint64 tail_rows; if (cfs_map_file_range_live_bytes(cfs->map_fd, resize_target, old_rows - resize_target, &tail_live, &tail_rows) != CFS_STORAGE_OK) ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: checkpoint could not read page map \"%s\"", cfs->map_path))); state->dead_delta += tail_live; state->truncate_rows = tail_rows; } cfs_map_file_resize(cfs, resize_target); } return true; not_ours: cfs_append_lock_release(rlocator, state->forknum); state->append_held = false; return false; } /* * cfs_checkpoint_reset - finish phase 2 (the append lock is still held * from cfs_checkpoint_fold_tail): reset the journal to a bare header, * clear the dirty mark, and publish the dead-space statistics. */ static void cfs_checkpoint_reset(CfsCheckpointState *state) { RelFileLocatorBackend rlocator = state->rlocator; /* * Everything the journal held is now in the map (or was dropped as * untrusted), so the reset can run bare and the dirty mark clears. This * must happen while the append lock is still held: a writer appends its * journal records under this lock but marks the slot dirty only after * releasing it (the cfs_map_cache_set_meta() call in * cfs_write_page_cached()), so clearing the flag after releasing the lock * could erase the dirty mark of a record appended too late. */ cfs_journal_reset_point(state->cfs, state->max_generation, data_sync_elevel(ERROR)); cfs_map_cache_clear_dirty(rlocator, state->forknum); /* * Publish the dead-space numbers only after the identity checks passed * and this checkpoint owns the relation's state: the counter holds this * value until the next checkpoint - what the compaction threshold (hourly * checks) needs. The value is the previous owner's dead_bytes plus this * checkpoint's delta: the superseded rows' payloads (both folds) and the * payloads of the rows the truncating RESIZE dropped (charged by the * phase-2 application above - the checkpoint is the single truncation * point, so its sum covers every shrink since the previous reset). The * dead_pages delta below covers the same two sources in rows. * * Accepted ceilings, all healed by compaction's exact recomputation: the * delta of a checkpoint that fails after folding but before resetting is * lost (the identical-row guard keeps the retry from charging it twice, * and by then it cannot charge it once); a stats slot evicted between * checkpoints (only a handful of slots per partition) restarts the * baseline from zero; segments closed between checkpoints add structural * padding the delta never sees. The counter drives the compaction * threshold - a heuristic - so an understated value delays compaction, it * never hides dead space from it. (When the reset was skipped, the * counters stay with the compaction or immedsync that interleaved - their * values are already current.) The fold's row count joins them for the * same ownership reason, and so does the truncating RESIZE's row count: * those rows left the file (they are not superseded versions of live * rows), and this is the one moment they are still countable - the * dead_pages delta below covers both, exactly like the dead_bytes one. */ /* * After a crash restart the prev snapshot is stale (the stats file * was written at the last clean shutdown), while the journal has * already been folded into the map by this point - the on-disk map * is exact, so the base is taken from it (conservatively: the chain * lead-in and inter-segment padding count as dead, which matches * what compaction can actually reclaim). The map-derived total * already contains everything dead_delta charges - the folds' * superseded payloads and the truncation tail's payloads are not * live in the folded, truncated map - and the publication below * adds dead_delta on top of the base, so the delta is subtracted * here to publish exactly the map-derived value, with every payload * counted once. On a read failure (soft fail) the base stays at * the prev value: the historical behaviour. */ if (state->dead_base_stale) { uint64 live_bytes = 0; uint64 map_rows; uint64 map_dead; int64 cfp_size; cfp_size = cfs_segmented_sidecar_size(state->rlocator, state->forknum, CFS_FILE_DATA); map_rows = cfs_map_rows_from_size(cfs_fd_size(state->cfs->map_fd)); if (cfp_size > 0 && cfs_map_file_range_live_bytes(state->cfs->map_fd, 0, map_rows, &live_bytes, NULL) == CFS_STORAGE_OK) { map_dead = ((uint64) cfp_size > live_bytes) ? (uint64) cfp_size - live_bytes : 0; state->dead_base = (map_dead > state->dead_delta) ? map_dead - state->dead_delta : 0; } } cfs_stats_count_checkpoint_rows(rlocator, state->forknum, (uint64) state->folded_rows); cfs_stats_set_dead(rlocator, state->forknum, state->dead_base + state->dead_delta, state->fold_superseded + state->truncate_rows); cfs_append_lock_release(rlocator, state->forknum); state->append_held = false; } /* * cfs_checkpoint_cleanup - release the * append lock if a phase still holds it, and drop the pinned handle. * Never called as a normal phase. */ static void cfs_checkpoint_cleanup(CfsCheckpointState *state, bool after_error) { if (state->append_held) { if (after_error) cfs_append_lock_release_after_error(state->rlocator, state->forknum); else cfs_append_lock_release(state->rlocator, state->forknum); } cfs_close_full_unpinned(state->cfs, state->rlocator, state->forknum); } static void cfs_checkpoint_one(RelFileLocatorBackend rlocator, ForkNumber forknum, void *arg) { CfsCheckpointState *state; int *count = (int *) arg; /* Only the main fork is compressed; skip everything else. */ if (forknum != MAIN_FORKNUM) return; /* * The sidecars may already be gone (the relation was dropped or rewritten * after its slot was listed as dirty): there is nothing to persist, clear * the stale dirty mark instead of failing the checkpoint. */ if (!cfs_exists(rlocator, MAIN_FORKNUM)) { cfs_map_cache_clear_dirty(rlocator, forknum); return; } state = palloc0(sizeof(*state)); state->rlocator = rlocator; state->forknum = forknum; /* * A lazy handle: descriptors and the map prologue, no private map. The * fold below works straight off the files, so the checkpoint's cost * tracks the journal, never the table. A NULL return means the open lost * a race - the sidecars vanished between the exists check and the open, * or the append lock was taken by a compaction or immediate sync in * flight - so the relation is skipped; its dirty mark is untouched and * the next checkpoint retries it. */ state->cfs = cfs_open_lazy_pinned(rlocator, MAIN_FORKNUM, false); if (state->cfs == NULL) { pfree(state); return; } PG_TRY(); { cfs_checkpoint_begin(state); if (!state->not_ours && !state->recovery_deferred && cfs_checkpoint_fold_tail(state)) cfs_checkpoint_reset(state); } PG_CATCH(); { cfs_checkpoint_cleanup(state, true); pfree(state); PG_RE_THROW(); } PG_END_TRY(); cfs_checkpoint_cleanup(state, false); /* * A relation skipped for a foreign reset or swap is not persisted: keep * the count honest for the DEBUG1 summary. (The recovery-deferred skip * did its phase-1 work; it counts.) */ if (!state->not_ours) (*count)++; pfree(state); } void CfsCheckpoint(void) { int count = 0; /* * Iterate over the CFS relations written since the last checkpoint * (dirty_checkpoint in the shared-memory metadata cache); a relation * without any write since then needs no new snapshot or fsync and is * skipped. Dirty-checkpoint slots are never evicted, so every relation * written since the last checkpoint is guaranteed to be found here. */ cfs_for_each_cfs_relation(cfs_checkpoint_one, &count); if (count > 0) ereport(DEBUG1, (errmsg("CFS: checkpoint persisted %d relation map snapshot(s)", count))); }