Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
edit | blame | history | raw

src/backend/storage/cfs/README

Compressed File Store (CFS)

CFS is a transparent page-level compression layer for heaps, indexes and
their TOAST tables. Shared buffers always hold ordinary, uncompressed
BLCKSZ pages, so the rest of the backend (WAL, index access methods,
locking, page checksums) is unaware that a relation is compressed.
Compression and decompression happen only at the storage-manager
boundary: a page is compressed when it is flushed out of the buffer
cache, and decompressed when it is read back in.

Because a compressed page cannot occupy the same offset as an ordinary
BLCKSZ page (compressed size varies, block N is not at N * BLCKSZ), a
compressed relation does not store its data in the ordinary main fork.
Instead it uses three sidecar files next to it: an append-only data file
(.cfp) holding compressed page versions, a fixed-size page map (.cfsmap)
translating logical block numbers to offsets in .cfp, and a journal
(.cfsjrn) of map updates used to recover the map after a crash without
rewriting it on every page write. The ordinary main-fork file is still
created by the generic relation-creation path and is kept as an empty,
permanently zero-size compatibility marker; it is never used for data
once a relation switches to CFS.

cfs_codec.c and cfs_compress.c implement the codec dispatch table
(RAW/LZ4/Zstd) and the page-level compress/decompress entry points,
including the three CRC-32C checks described below. cfs_format.c,
cfs_path.c and cfs_fsck.c handle on-disk struct (de)serialization and
validation, sidecar filename construction/parsing, and a streaming
structural integrity checker. cfs_storage.c and cfs_compact.c are the
storage engine proper: opening and closing a relation's three sidecar
files, appending and reading records, replaying and folding the journal
into the map (the fold serves the checkpoint and the startup recovery
scan alike), writing a full map snapshot for an immediate sync, and
compacting a relation in place.
cfs_shmem.c is the shared-memory layer built on top of it -- a
partitioned page-offset cache, per-relation metadata slots (including
the per-relation append lock discussed below), and aggregated usage
statistics. cfs_smgr.c bridges the storage engine to the generic
Storage Manager (smgr.c/md.c) and to WAL redo; this is where a
relation's CFS-ness is decided per SMgrRelation and where checkpoint/
sync-queue integration happens. cfs_bgworker.c, in
src/backend/postmaster/, is the background worker that periodically
compacts relations whose dead-byte ratio exceeds a threshold. cfs_rel.c
and cfs_guc.c are the SQL-visible policy layer -- reloption validation,
GUC defaults, and inheritance rules for TOAST tables, indexes and
partitions. cfs_sql.c holds the SQL-callable diagnostic and
administrative functions (pg_cfs_check, pg_cfs_compact, pg_stat_cfs and
friends). Headers for each of the above live under
src/include/storage/cfs/, one per source file.

Supported algorithms

RAW is always available and used verbatim as a sentinel for "not
actually compressed" (an incompressible page, or a storage fallback
during recovery -- see "WAL and recovery" below). LZ4 and Zstd are
compiled in conditionally on --with-lz4 / --with-zstd; a codec that is
not compiled in reports itself unavailable rather than erroring at
declaration time, so a relation created with an algorithm this
particular binary doesn't have simply cannot be decompressed here.

Index policy

An index is a CFS relation if and only if its own reloptions carry a
policy. The policy is written once, at CREATE INDEX time: an index
created without an explicit policy inherits the parent table's stored
algorithm and explicitly stored auxiliary keys into its own reloptions
(the "policy freeze"); WITH (algorithm = ...) spells one out directly;
ALTER INDEX ... SET adds or changes one later. Nothing is resolved from
the table at runtime: ALTER TABLE ... SET (algorithm) never affects the
indexes that already exist, and ALTER INDEX ... RESET (algorithm)
returns the index to plain storage for good (the implicit rebuild drops
its sidecar files). A partitioned index (relkind 'I') carries no
storage; its reloptions are the WITH clause each leaf index is created
with, and a leaf created on a CFS partition freezes that partition's
policy the same way.

On-disk format

A compressed record in .cfp is a CfsCompressedBlockHeader (40 bytes)
followed by the compressed page bytes and padding to CFS_BLOCK_ALIGN.
The header carries the algorithm, compressed/original sizes, the
page's LSN at compression time (diagnostic only), and three separate
CRC-32C checksums:

hdr_crc   the header fields themselves (algorithm/size confusion)
data_crc  the compressed bytes (on-disk corruption)
orig_crc  the original, decompressed page (a bad compress/
          decompress round trip)

All three are checked on every decompression, in that order, before
the page is handed back to the buffer manager -- which means
storage-level corruption is reported as a CFS CRC failure, not as an
ordinary page-checksum mismatch; PageIsVerified() never gets a chance
to see the bad page. When cfs_skip_page_checksum is on (the default),
the redundant cluster page-checksum is additionally skipped for these
pages: the CRC chain has already verified the exact bytes, so
PageIsVerified() performs only its header sanity checks there.
Setting the GUC to off restores the second hash (the double-check
behaviour); on clusters without data checksums nothing changes, since
the page-checksum branch never runs there either way.

.cfsmap starts with a static 8-byte prologue (magic, version) followed
by one fixed 24-byte CfsMapEntry per logical block number -- a plain
array, not an index, so locating an entry is a direct computation from
the block number. The number of rows derives from the file size (a
partial trailing row is a torn write and is ignored); there is no
server-side header, and every row is self-verifying via its entry_crc:
an all-zero row is a sparse hole (a never-written block, reads as
INVALID), a row with a bad CRC that is not all-zero is corruption
handled by the journal-repair contract (loaded as INVALID, healed by a
covering journal record, reported otherwise). Each entry carries a per-block
generation counter, bumped on every update to that block, used during
journal replay to tell competing updates of the same block apart; it
is unrelated to the per-relation generation counter used by the shared
map cache and by stale-handle detection after a compaction swap (see
below) -- the two counters share a name and nothing else.

.cfsjrn holds 48-byte entries, each a full copy of the corresponding
map entry rather than a delta, so replay is a straight overwrite with
no reconstruction logic. Its 16-byte header carries an incarnation
counter, bumped every time the journal is reset (checkpoint, recovery
scan, immediate sync or compaction), plus the monotone generation
watermark of the state the reset left behind; file size alone cannot
tell a reader whether the journal was truncated and regrown to roughly
the same size between two of its looks, but incarnation always can.

Format history (pre-release): CFS has never shipped, so there is no
upgrade or compatibility path to carry. The current layout - the
8-byte .cfsmap prologue (magic, version) with positional self-verifying
rows, and the 16-byte .cfsjrn header carrying max_generation - replaced
an earlier development layout (a 32-byte .cfsmap header and a 12-byte
.cfsjrn header without the watermark); the catalog version was bumped
with the change, and files written by those earlier development builds
are deliberately unreadable. A format change in a released version
would instead require an explicit, documented versioning decision.

Like ordinary relation files, .cfp is split into RELSEG_SIZE * BLCKSZ
(1 GiB) segments: .cfp, then .cfp.1, .cfp.2, and so on.
CfsMapEntry.physical_offset is a global byte offset across the whole
chain, so the map/journal format did not need to change for
segmentation, and files written before segmentation was introduced
still read correctly (all their offsets address segment 0). A record
never straddles a segment boundary -- the append cursor is rounded up
to the next boundary instead, leaving unused padding at the tail of a
segment. fsync, unlink and compaction all walk every segment; a
segment larger than CFS_SEGMENT_SIZE is treated as corruption and
rejected at open, since the engine itself never produces one. The map
and journal are never segmented.

Storage engine

cfs_storage.c owns a per-open in-memory CfsRelation handle and knows
nothing about the buffer manager, smgr or shared memory; integration
with those happens one layer up, through the CfsStorageOps indirection
table.

A single page write is, in order:

  1. compress the page, building its CfsCompressedBlockHeader;
  2. append the record to .cfp;
  3. append an UPDATE record to .cfsjrn;
  4. update the in-memory map (new offset + generation);
  5. .cfsmap itself is rewritten only at checkpoint, not per page.

The order of steps 2 and 3 is load-bearing: data is always durable
before the journal record that points at it, so a crash between them
can only produce a journal record with no matching data (detected and
skipped, see "WAL and recovery"), never the reverse.

The append offset of step 2 comes from the relation's metadata slot in
shared memory (the D1 protocol): under the append lock, a slot whose
append state is IDLE carries the authoritative end of the .cfp chain,
published by the previous writer right after its successful pwrite, and
the appender starts exactly there -- no per-append fstat walk. Every
non-IDLE state is untrusted and falls back to cfs_cfp_discover_eof()
(the only rule for segment chaining): a freshly created slot starts
DIRTY, a failed pwrite marks the slot DIRTY, a compaction that replaced
the .cfp chain marks it DIRTY, and a writer marks IN_PROGRESS right
before its pwrite, so a crash between the pwrite and the publication
sends the next writer back to the discover walk instead of a stale
tail. Callers without a metadata slot (the unlocked single-threaded
API, pre-shmem contexts) keep the historical walk on every append.

A RAW record of step 1 is not copied: CfsCompressPageNoCopy() builds
only the 28-byte header in the scratch buffer and describes the payload
as [caller's page + zero padding]; step 2 then writes it as one
pg_pwritev_with_retry() vector ([header][page][pad], cfs_pwritev_all),
byte-identical to the old copy-then-pwrite record. Compressed records
keep the contiguous scratch form of CfsCompressPage().

Opening a relation loads the last .cfsmap snapshot and replays
.cfsjrn on top of it; replay is idempotent on (blocknum, generation)
and stops at the first torn record.

A checkpoint (invoked once per relation after all of its dirty buffers
have already been flushed) fsyncs .cfp, then .cfsjrn, and then folds
the journal into the map in place -- no lock is held for this phase:
each UPDATE record rewrites exactly one positional row in .cfsmap (a
sparse gap reads as INVALID), a DELETE writes a CRC-valid INVALID row,
and a RESIZE record only names the new size - the short locked phase
below applies it, so readers never observe a map shorter than the
logical size. Records a concurrent writer appends during the fold
simply land beyond the fold's stop offset. A short exclusive phase then
folds that tail too (fsync'ing .cfp and the journal first) and resets
the journal to a bare header: the header is stamped with a bumped
incarnation and the generation watermark, and the relation's dirty mark
is cleared. The journal records are append-only; the reset is the one
place the file's prefix changes - the header is rewritten in place and
the records behind it are truncated away in the same durable step - so
a crash during the reset leaves one of three states, all safe: the old
journal (the header rewrite never reached the disk), the new bare
header, or - a crash between the header write and the truncate - the
new header still followed by the old records, which the next replay
(idempotent on block and generation) simply re-applies. A crash mid-fold
leaves torn rows that the
intact journal heals on the next load. The fold boundary is sampled
before the .cfp fsync, so a record a concurrent writer appends during
the fold never reaches the map before its data is durable - it stays in
the tail (a pread cannot tell page cache from disk, so the boundary,
not a read check, carries the guarantee). Every fsync on this path uses
the same convention as md.c: a failed fsync is PANIC by default,
because a checkpoint that claims success without actually persisting a
relation's data would let PostgreSQL recycle WAL that relation still
needs in order to recover. A failure during the lock-free fold
(e.g. ENOSPC) aborts the whole checkpoint with an ordinary ERROR
instead, without resetting the journal, so the next checkpoint can
simply retry -- matching vanilla PostgreSQL checkpoint semantics: one
relation's durability failure is fatal to the whole checkpoint, not
skip-and-continue. The locked phase holds the append lock, so its
write and fsync failures escalate through the same PANIC convention
(an ERROR there would unwind past the lock release); the one
deliberate exception is the mid-journal corruption check, which fails
with a plain ERROR while leaving the journal intact for the retry.

One deliberate simplification (measured, deferred): the fold does not
deduplicate journal records, so a block rewritten many times within one
checkpoint interval rewrites its row just as many times (one pread +
pwrite pair per record). The checkpoint itself opens a lazy handle -
under a conditionally acquired append lock, so an in-flight compaction
or immediate sync skips the relation for one round instead of being
raced into its half-staged candidate pair - and never materializes the
map: the DATA volume it moves, reads and scans tracks the journal - the
rows the journal names, the generation watermark carried in the journal
header and merged with the folds' own watermarks, and the dead-space
delta accumulated while folding. The lock is held across the whole
open, so the relation's writers wait out the open's own costs too (the
EOF walk below, and an interrupted-swap recovery when the marker is
set) - milliseconds per dirty relation per checkpoint, the price of
never racing the swap. Three fixed per-table costs remain outside that
promise and are accepted as stated: the phase-1 data fsync walks (and
fsyncs) every existing .cfp segment of the chain; the handle open
discovers the chain's EOF segment by segment - both are O(number of
segments), not O(journal); and the truncating RESIZE application reads
the map tail it drops, which is O(dropped rows) - a checkpoint's
volume is therefore proportional to max(journal, truncation), not to
the journal alone.

Dead-space accounting is a heuristic with compaction as its
exact-recomputation point. The counter's baseline is the value the
previous owner published; the checkpoint adds the payloads of the rows
its folds superseded, plus - in the same exclusive phase - the payloads
of the rows the truncating RESIZE drops, charged at the one moment they
are still readable: the physical map truncation lives in the
checkpoint's RESIZE application (the in-place truncate path only
journals the record - it runs inside RelationTruncate()'s critical
section, where neither an O(dropped rows) tail read nor an I/O failure
PANIC belongs), so until that application the rows beyond the new
logical size sit on disk as dead weight every reader resolves against
the logical size. Accepted ceilings, all healed by compaction: a
checkpoint that fails after folding but before resetting loses its
delta (the retry would charge the same rows twice, so it charges them
not at all); an evicted statistics slot restarts the baseline from
zero; segments closed between checkpoints add structural padding the
delta never sees. An understated value delays compaction; it never
hides dead space from it.

Sidecar file descriptors are raw (BasicOpenFile), deliberately
bypassing the virtual-file-descriptor layer (fd.c). The crash-safe
compaction swap protocol and stale-handle detection both rely on a
descriptor staying pinned to one inode for the lifetime of the handle
(comparing the descriptor's fstat() inode against a fresh stat() of
the path); the VFD layer can transparently close and reopen a
descriptor by path under fd pressure, which would silently swap it
onto a post-compaction inode and defeat that comparison. This is safe
because BasicOpenFile falls back to evicting ordinary relations' VFD
descriptors under fd pressure rather than competing with them, and
because every code path that opens a handle is wrapped so that an
ERROR between open and close still closes it -- a background worker
that keeps failing to compact the same relation does not leak
descriptors.

Locking discipline

Each relation that has been assigned a metadata slot (see "Shared
memory cache" below) owns a private LWLock, append_lock, embedded in
that slot -- not drawn from a shared pool, so no two relations ever
contend on the same append_lock regardless of how their keys hash. It
serializes three things against each other for one relation: a page
write (compress, append to .cfp, append to .cfsjrn, update the map), a
checkpoint (fsync both sidecar files, fold the journal into the map,
reset the journal), and a compaction swap (copy live records, atomic
rename, reset the journal). Whichever of the three loses the race simply
waits; it never observes a partially-updated map or journal.
Compression itself happens before the lock is acquired, so it can run
in parallel across relations and across concurrent writers of the same
relation -- only the actual append/journal/map-update sequence is
serialized.

A cache-miss read also takes append_lock, but LW_SHARED and only for
as long as it takes to replay the tail of the journal into the
reader's local map; decompression happens after the lock is released.
This coordination matters because both the shared map cache and a
backend's local map are filled from the journal, and the journal can,
in principle, be read mid-append: without the lock, a reader could
observe a torn journal record and silently keep serving a stale
cached offset instead of the one a concurrent writer just committed.

Inside cfs_shmem.c, ordinary map-cache-partition locks nest the other
way: never hold a partition lock across compression, decompression,
disk I/O or fsync, and always acquire the map-cache lock before the
statistics lock when both are needed, never the reverse -- which is
what keeps that pair deadlock-free.

Read path and batching

A single logical block resolves through the map (shared segment pool for
lazy handles, the backend's private map for full handles) to a
CfsMapEntry, which names the record's offset in .cfp and its compressed
size; cfs_read_record() preads the record, validates its three CRCs and
decompresses it into the caller's buffer. Since QDB-1513 a multi-block
smgr read (cfs_smgr_readv/cfs_smgr_startreadv, driven by bufmgr and
read_stream with io_combine_limit) batches runs of blocks whose records
are physically contiguous inside one .cfp segment
(next.offset == prev.offset + CFS_RECORD_SIZE(prev.size)):
cfs_read_records_span() fetches the whole run with a single pread and
decompresses each record from its slice of the scratch buffer -- the
produced pages are bit-identical to the per-block path, because
positions still come from the map and integrity from each record's own
header CRCs.

Everything that cannot join a run -- a pool miss, a stale generation
tag, an extension hole (INVALID offset), an offset gap left by rewrites,
a segment boundary, a read beyond the logical size -- degrades to the
ordinary per-block path, which remains the only place segments are made
resident and the authoritative fallback is taken. cfs_smgr_maxcombine()
publishes the contiguous-run length to the buffer manager; the value is
advisory (cheap lookups of resident state only, no I/O): the grouping is
re-derived at read time, so a compaction between planning and reading
merely shrinks the batches.

Advisory smgr hints follow the same resident-state discipline.
cfs_smgr_prefetch (pg_prewarm('prefetch'), PrefetchBuffer) resolves the
requested block range through the map and issues one
posix_fadvise(WILLNEED) per contiguous .cfp record run, warming the page
cache the synchronous decompressing reads consume. cfs_smgr_writeback
(the bgwriter/checkpoint/backend *_flush_after knobs) starts kernel
writeback of the dirty .cfp ranges with sync_file_range(WRITE) (Linux
only, a no-op elsewhere) -- a scheduling hint without fsync semantics;
durability stays with the checkpoint. Both open the sidecar pair
read-only through a quiet catch (a hint must never raise from the
bgwriter/checkpointer, which run it under HOLD_INTERRUPTS, and must
never create files of a possibly dropped relation) and skip silently on
any miss.

Failure semantics match the per-block path: a corrupted record inside a
run fails the whole read with CFS_STORAGE_CORRUPT naming the exact
block; a failing span pread names the run's first block; corruption is
escalated centrally through cfs_report_corruption (the
cfs_checksum_failure GUC decides ERROR vs PANIC).

In the AIO entry point the failure is encoded into the inline IO result
(codes < 4, see cfs_smgr.c) and the report names the FIRST block of the
multi-block IO -- there is no room for a block number in the result's
bit layout; the synchronous entry point reports the exact failing
block. The debug injection GUC cfs_debug_fail_read is spent on the
span pread.

Observability of the read path (QDB-1513 evidence cycle):

  • Wait events: WAIT_EVENT_CFS_READ covers only the pread of a record or a
    record span (plus the span scratch allocation); the validation and
    decompression of the records is reported separately as
    WAIT_EVENT_CFS_DECOMPRESS, in both the per-block path (cfs_read_record)
    and the batched path (cfs_read_records_span). Wait-event sampling can
    therefore attribute the IO phase and the decompression CPU phase
    independently.
  • pg_stat_cfs counters: read_batch_count (span preads served),
    read_batched_pages (pages served from spans) and read_fallback_pages
    (pages degraded to the per-block path by the batch wrapper). The
    invariant read_count == read_batched_pages + read_fallback_pages holds
    for smgr-driven reads in both map modes: with the shared pool (the
    default) every page is accounted; on a private map (cfs_map_memory=0)
    the per-block path historically never reaches read_count, and the
    fallback counter skips it symmetrically, while span reads are accounted
    on both sides. A span whose k-th record fails decompression counts its
    successfully served prefix as a partial batch, so the invariant also
    survives error paths. read_batched_pages / read_batch_count is the
    average span length. The persisted pg_cfs_stats layout change is
    versioned by CFS_STATS_FILE_FORMATID: an older file is discarded at
    startup (the same degradation as after a crash).

Shared memory cache

Two things live in shared memory: a page-offset cache (one entry per
recently-touched block, independent of any relation's private map) and
one metadata slot per open relation (logical size, generation, the
dirty-for-checkpoint flag, and the append_lock described above).

The page-offset cache is partitioned into 64 hash partitions of 64
slots each, purely to avoid serializing unrelated relations (or
unrelated hot blocks of the same relation) on one lock; eviction is
LRU within a partition, except that an entry belonging to a relation
someone still has open is never evicted wholesale. Each cached entry
is stamped with the relation's generation counter at insertion time
and is only trusted on lookup if that stamp still matches the
relation's current generation; a mismatch (compaction, truncate) just
falls back to the authoritative map instead of trusting stale data. A
CRC failure on a cache hit invalidates only that one block's entry,
not the whole relation, so one bad block does not cascade into misses
across the relation, and re-reading it still goes through the
authoritative map and rediscovers the real corruption.

The metadata-slot table is much smaller: cfs_map_cache_rels_per_partition
slots per partition (PGC_POSTMASTER, default 16, range 1-64), i.e. up
to 64 times that many relations cluster-wide. A slot is not an
optional cache here -- without one, a relation has nowhere to keep its
dirty-for-checkpoint flag or its append_lock, so it cannot be written
or checkpointed at all. If every slot in a partition is pinned or
checkpoint-dirty when a new relation needs one, the operation fails
with a hard ERROR (ERRCODE_CONFIGURATION_LIMIT_EXCEEDED) naming the
GUC to raise, rather than silently dropping the relation from
checkpoint accounting.

Since QDB-1516 each partition keeps its slots in hash chains: a bucket
head array indexed by the upper bits of the relation hash, and every
occupied slot carries the index of the next slot of its chain. A
lookup walks only its own chain (one or two slots typically) instead
of scanning the whole partition, so a hot partition no longer holds
its lock for O(slots) on every miss; the full-partition scan survives
only on the rare eviction path, when a victim must be chosen among all
unpinned slots. Chain mutations happen exclusively under the
partition's exclusive lock, and a victim or invalidated slot is
unlinked from its chain before it is zeroed.

The per-partition access clocks (one array for the metadata domain,
one for the statistics domain) are plain per-partition counters
incremented under the partition lock that is already held at the touch
point -- there is no cluster-wide atomic clock line bouncing between
cores on every cache touch anymore. Monotonicity only ever matters
inside one partition (LRU victim selection, and the policy
generation's anti-ABA property), so per-partition domains preserve
both contracts.

The relation-statistics table mirrors the metadata design: 64
partitions of cfs_stats_slots_per_partition slots each (PGC_POSTMASTER,
default 16, range 4-128; 1024 relations cluster-wide by default).
Counters are pg_atomic_uint64 fields, so the per-event accounting of a
read or write increments them under the partition's shared lock;
monopolizing the lock is reserved for slot creation, LRU eviction and
pg_cfs_reset_stats(). When more relations than the capacity are
active, statistics rows evict each other (the least recently used row
is reset to zero) -- raise the GUC to cover the working set. A
snapshot for pg_stat_cfs reads the atomics under the shared lock as
well; per-counter values are exact, cross-counter consistency is that
of pgstats (each counter read at its own instant).

The counters are persisted to PGDATA/pg_cfs_stats at a regular
shutdown and restored at startup (the PG15 pgstat pattern), so the
compaction worker keeps its dead-space baselines across maintenance
restarts. After a crash restart the restored dead_bytes may predate
the crash (the file was written at the last clean shutdown, while the
map the recovery folded afterwards is the truth): every restored entry
is marked stale, a slot first touched after the boot is stale the same
way (its zeroed counters know nothing of the pre-crash dead space),
and the first measurement resyncs dead_bytes from the relation's map
-- the background worker's first full cycle over the cluster's
databases (including relations that have no entry in the file at all;
an incomplete or paused cycle leaves the resync pending for the next
one) and the relation's first checkpoint, which recomputes its base
from the map it has just folded (a relation without a restored entry
gets that map-based base on any boot). dead_pages cannot be recovered
from the map (the map does not count superseded page versions; the
generation watermark is what compaction preserves), so the restored
value is kept. A clean restart keeps the persisted values as they
are: there was no crash, the file is current, and no resync runs -
unless the previous clean shutdown overtook the still-pending sweep,
which an internal empty marker file (pg_cfs_stats_resync, removed
only when the recomputation completes, never at boot) records: the
sweep then runs on that clean restart as well, and even a start
killed before the sweep keeps the obligation on disk.

Since QDB-1516 the logical size of a relation whose metadata slot was
evicted is measured without materializing any map: the base is the
row count of the .cfsmap snapshot on disk (its size; the file only
changes at fold points, which hold the exclusive append lock), and the
delta is the last RESIZE record of the journal (absolute target, last
one wins), scanned with the block-buffered journal reader under the
shared append lock. The cost of a size miss is therefore O(journal),
not O(map), and the full_map_opens counter stays at zero on this
path. A torn journal tail is tolerated by the scanner's own
classification; a torn record in the middle of the journal means the
true size may be behind the damage, so the size is not trusted: a
normal backend escalates through the corruption channel
(cfs_checksum_failure decides ERROR vs PANIC), while the startup
process mirrors the recovery contract -- cfs_recovery_strict aborts,
otherwise the size falls back to the pre-QDB-1516 full-map measurement
with a WARNING, and the server still comes up.

A sidecar set damaged from outside is never answered with a silent
zero: when the .cfsmap is missing but the journal still exists, or when
both are gone while the .cfp data file (or any of its segments) still
survives -- only a drop removes the whole triple -- the measurement
raises the corruption ERROR; a stat failure with an errno other than
ENOENT is equally loud. Zero is answered only when all three files are
gone, the drop/rewrite race with the caller's cfs_exists() check.

Compaction

Compaction rebuilds a relation's sidecar pair in place, keeping only
live records, without touching its relfilenumber and without writing
WAL. It builds a full candidate pair (.cfp[.N].new /
.cfsmap.new) next to the live one, fsyncs it, and only then
commits by creating a single marker file (.cfp.cfsswap) followed
by a durable rename of both files. If the server crashes before the
marker exists, the .new files are simply orphaned garbage, cleaned up
lazily; the old pair is still authoritative. If it crashes after the
marker exists but before, or during, the rename, startup finds the
marker and completes the rename itself -- the two files never disagree
about which generation is current.

Around the copy-and-swap, compaction flushes the relation's dirty
buffers first (the ordinary smgr write path, the same thing a CLUSTER/
VACUUM FULL relfilenode swap does). The online mode (QDB-1514, the
default; with GUC cfs_compact_online=off, append_lock is simply held
for the whole operation) runs in three phases instead of holding it
for the whole window:

A. a brief exclusive append_lock section: mark the compaction owner in
the metadata slot, open the source pair (tail repair), snapshot it
and release the lock;
B. a lock-free copy of the snapshot's live records into the candidate
chain (.cfp[.N].tmp) and a full candidate map
(.cfsmap.cfscand -- a compaction-specific suffix, so the
snapshot writer's .cfsmap.tmp namespace can never collide with
it), fsynced without any locks; ordinary readers and writers keep
running;
C. a second brief exclusive section: converge the source handle to the
current on-disk state (a delta replay, or a full reload when a
checkpoint folded the map meanwhile), positionally transfer the
records appended during the copy, then run the unchanged swap
protocol and the durable journal reset, and clear the owner mark.

The final window therefore scales with the append stream that happened
during the copy, not with the relation size. A writer blocked on
append_lock during that window notices, once released, that its open
handle's cached generation is stale and reopens the sidecar files by
path before writing -- otherwise its write would silently land in the
renamed-away old inode. The same generation protocol covers a lock-free
open that straddles the swap: the open guard pins the metadata slot and
holds append_lock shared around the descriptor resolution and the
generation tag only (the map load runs outside the lock), and a read
through a cache miss re-checks the generation and raises a transient,
retryable error on mismatch.

The caller (background worker or the synchronous pg_cfs_compact() SQL
function) holds ShareUpdateExclusiveLock on the relation for the whole
operation in both modes: plain SQL reads and writes proceed, while DDL
that needs a stronger lock waits. The modes differ only in the append
lock: online releases it after each brief phase, offline (GUC
cfs_compact_online=off) keeps it for the whole operation, so the
physical sidecar appends behind plain SQL writes (buffer flushes,
checkpoints) are serialized until compaction finishes. The compaction
owner mark in the metadata slot keeps open-path recovery from discarding
a live compaction's candidates; a dead owner's orphans are cleaned up on
open or by the startup scan.

Because compaction shifts every physical offset in .cfp, a backup or
pg_rewind snapshot taken mid-swap would see an inconsistent pair that
WAL replay cannot repair; committing a swap is therefore refused while
any non-exclusive base backup is in progress, checked both when
compaction starts and again, under the WAL insertion lock, immediately
before the commit marker is written, so a backup cannot start in the
gap between the two checks.

The background worker scans periodically, compacts relations whose
dead-byte ratio exceeds a threshold (the dead share of the LIVE volume:
dead / (cfp_size - dead_bytes), so a relation whose live tail is gone
is not masked by the space compaction is about to reclaim), processes
at most a bounded number of relations per pass, and will not revisit
the same relation within a configured minimum interval -- all four
knobs are ordinary GUCs (cfs_bg_period_ms, cfs_bg_threshold,
cfs_bg_max_relations, cfs_bg_min_interval_s). If it cannot acquire
ShareUpdateExclusiveLock on a candidate within its configured timeout,
it skips that relation until the next pass instead of erroring. A failure compacting one relation
is caught and logged, that relation is marked as recently attempted so
it is skipped for a while, and the worker moves on to the next
candidate -- one broken relation does not stop automatic compaction of
the rest of the cluster. A manual pg_cfs_compact() call, by contrast,
still raises the error to its SQL caller.

WAL and recovery

CFS does not register its own WAL resource manager. WAL always
carries ordinary, uncompressed full-page images; every backend that
flushes a CFS page asserts it is handing smgr a full BLCKSZ buffer.
The only CFS-specific WAL record is XLOG_SMGR_CFS_POLICY (RM_SMGR_ID),
which announces "this relfilenumber is a CFS relation compressed with
this algorithm." It has to travel over WAL because a standby built
purely by replaying WAL from empty never executes CREATE TABLE or
reads reloptions -- without an explicit record it has no way to know
that a given relation's data lives in sidecar files rather than the
main fork. The record is emitted next to every WAL-visible operation
that assigns new physical storage to a relation: table/index creation,
TOAST-table creation, WAL_LOG-strategy CREATE DATABASE, and in-place
rewrites (TRUNCATE, REINDEX, VACUUM FULL/CLUSTER index rebuilds,
ALTER TABLE ... SET/RESET (algorithm)) via
RelationSetNewRelfilenumber(), the one choke point all of those go
through.

On the ALTER TABLE ... SET/RESET (algorithm) rewrite path
specifically, there is a second, purely in-memory problem alongside
the WAL one: pg_class.reloptions for the old heap (and its TOAST table
and indexes) is updated before the rewrite has copied a single row, so
for the rest of that transaction the catalog says one thing while the
physical files on disk still say another. cfs_smgr_resolve_physical()
closes that window by overriding an already-open SMgrRelation's
CFS-ness to match what is physically on disk (sidecar files present or
not) rather than trusting reloptions, so reads of the old heap during
rewrite keep using the correct I/O path.

At startup, CfsRecoveryInit() runs from StartupXLOG() before WAL redo
begins and before the server accepts connections. It first removes any
orphaned .cfp.tmp/.cfsmap.tmp files left by an interrupted compaction
(always safe -- a completed compaction has already renamed them over
the originals) and completes any compaction whose commit marker exists
but whose rename did not finish. It then folds every relation's
.cfsjrn into its .cfsmap row by row, through the same fold engine the
checkpoint uses, and resets the journal. The name walk (readdir +
stat) runs on every startup; a relation's sidecars are opened -- lazily,
descriptors only -- only when its journal actually holds records, so a
clean restart (journals truncated at the last checkpoint) loads no maps
and only validates the sidecar headers. The scan itself never loads a
map into memory and rewrites no snapshot: the fold rewrites exactly the
rows the journal names, so the scan's cost is proportional to the
journal (the changes since the last checkpoint), never to the map. The
.cfsmap and
.cfsjrn headers are still read and validated for every relation, so a
full-sized header that fails validation aborts the startup scan the same
way whether the journal is empty or not. A consequence of the fold
model: a .cfsmap row corrupted without a covering journal record is no
longer touched at startup -- the fold never rewrites uncovered rows --
and the damage surfaces at the first access of the block, through the
backend checksum policy.

Journal replay treats two kinds of bad records differently. A torn
final record (bad CRC/magic, the tail of an interrupted append) simply
stops the fold there, as if it had never been written; it is the normal
crash artifact and is dropped with the journal reset. A torn record
with data still following it cannot be produced by a legal append and
is treated as corruption: a WARNING in the default mode (the journal is
preserved untouched; the next restart repeats the fold), a hard stop
with cfs_recovery_strict=on. A structurally valid UPDATE record that
points at data which is not actually present at its claimed offset in
.cfp -- possible because the kernel can flush .cfsjrn pages to disk
before the .cfp pages they reference -- is instead skipped, and the
fold continues with the next record: the map keeps the row's last
known-good version, and the ordinary WAL redo that already knows about
the same page change reapplies it independently on top of the old
version. The skip is logged as a WARNING (it is a symptom, not a
non-event) and turns into a hard stop with cfs_recovery_strict=on.

The file headers are handled separately from the records. A corrupt
.cfsmap or .cfsjrn header is always a hard error in every mode: the map
header is a synchronisation point whose data WAL does not cover, and a
journal header that fails validation means the file cannot even be
trusted to describe itself. The failed startup leaves both files
untouched, so the corruption stays diagnosable on disk.
cfs_checksum_failure (superuser-settable, error/panic) controls what a
CRC mismatch or structural damage (a .cfsmap prologue or a .cfsjrn
header that fails validation) caught during a normal backend read does
-- error aborts the statement, panic aborts the server; there is
deliberately no "warning" level that would return the corrupted page
anyway, since a primary and a standby recovering differently from the
same corruption is exactly the kind of silent divergence CFS exists to
avoid. Startup-time detection of a corrupt header stays a hard error
in every mode: the startup fold must not come up on a map or journal it
cannot even size (see cfs_map_file.c).

The set of compiled-in codecs is a property of a specific binary and
can legitimately differ between primary and standby. A standby that
builds its own sidecar files purely from streaming replication only
ever writes pages with a codec it itself has, so this never bites it;
one whose sidecar files were copied physically (base backup,
pg_rewind) must have every codec actually used in those files, or
reading the affected blocks fails outright. During recovery, an
explicit algorithm that isn't compiled in downgrades silently to RAW
for every process that writes through the redo path (startup,
checkpointer/bgwriter, hot-standby backends), rather than raising an
ERROR that would be fatal to redo. That downgrade only applies while
the node is still a standby: once it is promoted, the ordinary
DDL-time guarantee applies again, and a write against an
explicit-but-unavailable algorithm is a hard ERROR, exactly as it
would be on a primary that was never a standby.

Interaction with standard utilities

pg_basebackup, pg_verifybackup, pg_checksums and contrib modules
(pageinspect, amcheck, pgstattuple) require no CFS-specific code:
sidecar files sit next to the ordinary relation files and are treated
like any other file by tools that don't try to interpret their
contents, and everything that reads pages through the buffer manager
gets a decompressed page regardless of storage format. pg_checksums
recognizes and skips sidecar files by filename suffix, purely
lexically, independent of whether that particular binary was built
with CFS. pg_upgrade transfers sidecar files alongside the rest of a
relation's files, but first walks the old cluster for any .cfsmap file
and, if it finds one, confirms the target binary was built with CFS
support before copying anything -- otherwise the upgraded cluster
would contain sidecar files no server there can read. pg_rewind
treats sidecar files as ordinary non-relation files and is taught to
recognize (and ignore) XLOG_SMGR_CFS_POLICY while parsing WAL; without
that it would abort with "record type is not recognized" on any WAL
stream that created a CFS relation. An incremental pg_basebackup
avoids re-copying the whole .cfp file for an unchanged relation by
comparing an epoch stamped in the file's lead-in, bumped on creation
and on every compaction swap; a matching epoch means only the byte
range appended since the previous backup needs to be sent.

Review rules (auto-reject)

These rules exist to end the review-cycle class where the reviewer has to
re-model every race and invariant from scratch. Each invariant has exactly
ONE home; a change that re-derives it anywhere else is rejected without
further discussion.

  1. Ownership/race checks only in cfs_state.c. Any derivation of
    "the journal was reset / the .cfsmap was swapped / the shared
    generation moved under this handle" outside the judge
    (cfs_state_capture / cfs_state_check / cfs_state_journal_moved)
    is rejected. Callers switch on the returned flags (see the mask table
    at the top of cfs_state.c). One exception:
    cfs_journal_tail_changed() re-reads a single record -- record
    content, not pair identity.
  2. A journal reset goes only through cfs_journal_reset_point()
    (the durability contract), or through cfs_journal_reset_file(),
    which exists solely for the compaction swap (reset by path on the
    already-renamed pair). A third reset path is rejected.
  3. Journal reading goes only through cfs_journal_scan(). A new
    hand-written reader loop is rejected; add a policy/sink pair instead.
  4. The torn-tail vs mid-file classification comes only from the scan
    engine's stop reason
    (CFS_SCAN_STOP_TORN_TAIL /
    CFS_SCAN_STOP_TORN_MIDFILE); the report wording comes from the
    engine (the role parameter), reported once.
  5. Pool staleness is judged only through cfs_seg_matches() /
    cfs_seg_tag_matches()
    (cfs_shmem.c). A new by-hand comparison of
    a segment's generation against a handle is rejected.
  6. cfs_storage.c must not call the shmem/smgr layers. The
    sanctioned neighbours are the leaf modules: cfs_io.c (raw I/O),
    cfs_sync.c (sync queue), cfs_stats.c (counters), cfs_swap.c
    (swap protocol); the shared generation is read through
    cfs_state_relation_generation() (the provider hook installed by
    CfsShmemInit).