/*-------------------------------------------------------------------------
|
* cfs_journal.h
|
* Compressed File Store (CFS) — the .cfsjrn journal, one module.
|
*
|
* The journal-side primitives every consumer shares: the chunked record
|
* reader, the header reads (strict and lenient), the reset (the single
|
* home of the durability sequence header -> truncate -> fsync) and the
|
* torn-record tail classification. The append path and the replay/fold
|
* engines stay in cfs_storage.c: they are write-path state machines, not
|
* journal-file primitives.
|
*
|
* Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
|
*
|
* IDENTIFICATION
|
* src/include/storage/cfs/cfs_journal.h
|
*
|
*-------------------------------------------------------------------------
|
*/
|
#ifndef CFS_JOURNAL_H
|
#define CFS_JOURNAL_H
|
|
#include "postgres.h"
|
|
#include "storage/cfs/cfs.h"
|
#include "storage/block.h"
|
#include "storage/cfs/cfs_format.h"
|
#include "storage/cfs/cfs_io.h"
|
#include "storage/relfilelocator.h"
|
|
/* The handle type: a forward declaration keeps this header free of
|
* cfs_storage.h (the include cycle journal -> storage -> journal).
|
* Pass struct CfsRelation * or struct struct CfsRelation * interchangeably. */
|
struct CfsRelation;
|
|
/*
|
* Chunked journal reader (the P2 tail): the journal is
|
* consumed by whole-file scans (full-map open, segment sync, generation
|
* seeding), and one pread per 48-byte record turned a cold load of N
|
* segments into millions of syscalls. The reader keeps the transport
|
* semantics of the per-record cfs_pread_all() loop exactly:
|
*
|
* - a record is only returned when all CFS_JOURNAL_ENTRY_SIZE bytes of
|
* it are on disk; a trailing partial record reads as end-of-records
|
* (NOENT), never as garbage;
|
* - a full record with a bad CRC/magic is returned as-is — the caller's
|
* validate step decides, so the torn-tail vs mid-journal corruption
|
* policy is unchanged;
|
* - 'off' always names the next unconsumed record, so stop offsets
|
* keep their meaning.
|
*
|
* One CFS_JOURNAL_READ_CHUNK-byte read covers ~5.4k records.
|
*/
|
#define CFS_JOURNAL_READ_CHUNK (256 * 1024)
|
|
typedef struct CfsJournalReader
|
{
|
int fd;
|
off_t off; /* absolute offset of the next record */
|
off_t rec_off; /* offset of the record returned last; a
|
* torn/invalid record must keep its place as
|
* the replay stop position, so callers break
|
* on it read rec_off, not off */
|
char *buf;
|
size_t buflen; /* bytes in buf */
|
size_t bufpos; /* next unconsumed byte of buf */
|
int rc; /* OK while a next record may exist; NOENT
|
* after clean end, ERROR on I/O */
|
bool fail_next_read; /* injection: fail the next block read once */
|
} CfsJournalReader;
|
|
extern void cfs_journal_reader_init(CfsJournalReader *r, int fd,
|
off_t start_off);
|
extern void cfs_journal_reader_free(CfsJournalReader *r);
|
extern bool cfs_journal_reader_next(CfsJournalReader *r, CfsJournalEntry *je);
|
|
/*
|
* Read and validate the journal header. Returns false when the header is
|
* missing, unreadable or fails validation; the caller then falls back to
|
* the legacy file-size-only staleness heuristics.
|
*/
|
extern bool cfs_journal_read_header(int fd, CfsJournalFileHeader *out);
|
|
/*
|
* Read the journal header checking only the fixed-format fields (magic and
|
* version), without requiring a valid CRC. Used by the reset paths so
|
* that a torn header from a crash window still yields its previous
|
* incarnation value: bumping from a CRC-broken header is strictly better
|
* than restarting the sequence at 0, which could alias with a backend's
|
* saved baseline and hide the reset entirely.
|
*/
|
extern bool cfs_journal_read_header_fields(int fd, CfsJournalFileHeader *out);
|
|
/*
|
* Initialise a fresh journal header for a reset, bumping the incarnation
|
* of the header currently stored in 'fd' (if any) and stamping the
|
* generation watermark the caller computed for the state the reset leaves
|
* behind. Kept in one place so the init -> read -> bump -> set_crc
|
* sequence cannot drift between the reset points.
|
*/
|
extern void cfs_journal_header_init_bumped(int fd, CfsJournalFileHeader *jhdr,
|
uint32 max_generation);
|
|
/*
|
* Shared tail of every journal reset: write the freshly stamped header
|
* (incarnation bumped, generation watermark of the state the caller
|
* leaves behind), truncate the file to the new logical end and make the
|
* reset durable. The journal is append-only: this header rewrite plus
|
* truncate is the only way its prefix is ever replaced. The fd-based
|
* callers (checkpoint, recovery scan, immedsync) and the path-based
|
* compaction swap reset all end here, so the durability sequence cannot
|
* drift.
|
*/
|
extern void cfs_journal_finish_reset(int fd, const char *jrn_path,
|
CfsJournalFileHeader *jhdr,
|
off_t end_off, int elevel);
|
|
/*
|
* cfs_journal_reset_file — reset the .cfsjrn at 'jrn_path' to a bare
|
* header and fsync it (the compaction swap reset; the file is opened by
|
* path because the swapping caller holds no descriptor for it).
|
*/
|
extern void cfs_journal_reset_file(const char *jrn_path,
|
uint32 max_generation);
|
|
/*
|
* cfs_journal_reset_point - THE reset entry point for every handle-based
|
* path (checkpoint, immedsync, recovery). Fixes the durability contract
|
* in one place: the caller's payload (.cfsmap rows / snapshot / .cfp
|
* data) is already durable and the append lock is held; this helper
|
* flushes the journal and resets it to a bare header, stamping the
|
* watermark as the max over the passed value and the previous header
|
* (never regresses). The only other way a journal is ever reset is
|
* cfs_journal_reset_file() - the compaction swap exception (reset by
|
* path on the already-renamed pair; the single documented exception, see
|
* the CFS review rules (README.md, "Review rules")).
|
*/
|
extern void cfs_journal_reset_point(struct CfsRelation *cfs, uint32 watermark,
|
int elevel);
|
|
/*
|
* Classify a torn/invalid journal record hit at 'rec_off' during a
|
* replay: a torn TAIL (the record's slot is the file's last) is the
|
* normal crash artifact, an invalid record with records still following
|
* it is corruption. Returns true when the record is the tail; raises
|
* ERROR if the journal size cannot be determined, because no safe
|
* verdict exists then. Shared by the full replay and the segment replay
|
* so the two policies cannot drift.
|
*/
|
/*
|
* cfs_journal_torn_is_tail was absorbed into the scan engine: the
|
* classification is CFS_SCAN_STOP_TORN_TAIL / _TORN_MIDFILE.
|
*/
|
|
/*
|
* cfs_journal_tail_changed - the phase-2 re-check after phase 1 classified
|
* the journal as ending in a torn tail. Phase 1 runs without the append
|
* lock, so a writer may have completed that record or appended past it while
|
* the fold was reading. Returns true when the journal no longer ends at
|
* rec_off with an invalid (still torn) record; the reset must not run then.
|
*/
|
extern bool cfs_journal_tail_changed(struct CfsRelation *cfs, off_t rec_off);
|
|
/*
|
* The journal's on-disk identity: which inode the descriptor names, and
|
* the header watermark of what it currently holds. Two equal samples
|
* mean no reset swapped or rewrote the journal in between; any difference
|
* (a fresh inode after immedsync, an incarnation bump from a reset, a
|
* regrown tail) means the caller must re-read. cfs_map_load() samples it
|
* around its snapshot and journal reads and retries on a change.
|
*
|
* The checkpoint phase 2 does NOT use it: the journal legitimately grows
|
* between its phases, so a size difference is not evidence of a reset.
|
* Phase 2 compares the incarnation and the map generation instead.
|
*/
|
typedef struct CfsJournalIdentity
|
{
|
dev_t dev; /* inode the descriptor names */
|
ino_t ino;
|
uint16 incarnation; /* header watermark at sample time */
|
off_t size; /* file size at sample time */
|
uint32 max_generation;
|
} CfsJournalIdentity;
|
|
extern bool cfs_journal_identity(int fd, CfsJournalIdentity * out);
|
extern bool cfs_journal_identity_equal(const CfsJournalIdentity * a,
|
const CfsJournalIdentity * b);
|
|
/*
|
* The one apply engine: every consumer of journal records (the full
|
* replay, the delta replay, the checkpoint fold and the segment replay)
|
* feeds a validated record through cfs_journal_apply_record() and states
|
* its own sink - where an applied row goes and what a RESIZE means for
|
* it. The UPDATE/DELETE/RESIZE policy lives here and nowhere else.
|
*
|
* The engine counts what it sees: max_generation is raised by every
|
* UPDATE (even one the sink skips - a generation is occupied once its
|
* journal record exists), superseded is left for the fold's sink to bump
|
* (it owns the old-row read), and resize_target/have_resize mirror the
|
* last RESIZE record applied.
|
*
|
* A sink may install its own update_usable hook (the unit-test contract);
|
* every production sink leaves it NULL and lets the engine apply the
|
* shared durability policy (cfs_journal_update_data_usable), whose report
|
* channel is selected by recovery_severity. filter_range restricts
|
* UPDATE/DELETE rows to [first_block, last_block) before the durability
|
* check - the segment replay must not even look at records outside its
|
* range.
|
*/
|
typedef struct CfsJournalSink
|
{
|
void (*write_row) (void *arg, BlockNumber block,
|
const CfsMapEntry *row);
|
void (*resize) (void *arg, BlockNumber target);
|
bool (*update_usable) (void *arg, const CfsJournalEntry *je);
|
void *arg;
|
BlockNumber first_block; /* range filter, see filter_range */
|
BlockNumber last_block;
|
uint64 superseded; /* fold's sink bumps: dead page versions */
|
uint32 max_generation; /* highest seen UPDATE generation */
|
BlockNumber resize_target; /* last RESIZE target */
|
bool have_resize; /* a RESIZE record was seen */
|
bool filter_range;
|
|
/*
|
* Corrupt-data report channel for the shared durability policy, not a "we
|
* are in WAL redo" fact: true selects the recovery severity
|
* (cfs_recovery_strict: ERROR, else WARNING and continue), false the
|
* backend's checksum-failure severity (cfs_checksum_failure: ERROR or
|
* PANIC). cfs->strict decides whether the report happens at all.
|
*/
|
bool recovery_severity;
|
|
/*
|
* Stream observers for the census/aggregate consumers that must NOT apply
|
* records (they run without a CfsRelation, see cfs_journal_scan_fd): one
|
* call per structurally present record - valid ones through see_record,
|
* invalid ones (only reported while the policy asks continue_on_invalid)
|
* through invalid_record. The applying consumers (replay, fold) leave
|
* both NULL.
|
*/
|
void (*see_record) (void *arg, const CfsJournalEntry *je);
|
void (*invalid_record) (void *arg, off_t rec_off,
|
CfsFormatStatus st);
|
} CfsJournalSink;
|
|
extern void cfs_journal_apply_record(struct CfsRelation *cfs,
|
const CfsJournalEntry *je,
|
CfsJournalSink *sink);
|
|
/*
|
* The one journal scan loop (review I3): every consumer that walks the
|
* journal - the full replay, the delta replay, the checkpoint fold and
|
* the segment replay - runs cfs_journal_scan() with its own policy and
|
* sink. The torn-tail vs mid-file-corruption classification lives
|
* INSIDE the engine and is reported once, with the caller's role in the
|
* message; the stop reason comes back classified. Writing a new journal
|
* loop by hand is rejected by the CFS review rules (README.md).
|
*/
|
typedef enum CfsScanStopReason
|
{
|
CFS_SCAN_STOP_EOF, /* clean end of records */
|
CFS_SCAN_STOP_TORN_TAIL, /* crash artifact: truncatable tail */
|
CFS_SCAN_STOP_TORN_MIDFILE, /* corruption: valid records follow */
|
CFS_SCAN_STOP_BOUNDARY, /* fold limit reached (policy.limit) */
|
CFS_SCAN_STOP_IO_ERROR /* reader I/O failure */
|
} CfsScanStopReason;
|
|
typedef struct CfsJournalScanPolicy
|
{
|
/*
|
* Stop BEFORE the first record that starts at/after this offset (the fold
|
* boundary); 0 disables. The boundary report fires only when a limit is
|
* set.
|
*/
|
off_t limit;
|
|
/* The role in the torn-record reports: "replay", "fold", ... */
|
const char *role;
|
|
/* Route the mid-file report through the recovery channel? */
|
bool during_recovery;
|
|
/*
|
* Test seams: fail the next block read (the fold's injection points), or
|
* pause after the first applied map row (the parked-fold test). The
|
* pause counts UPDATE/DELETE rows only: RESIZE names a size, not a map
|
* row, and a journal leading with RESIZE must not park before the first
|
* row it exists to hold.
|
*/
|
bool fail_next_read;
|
const char *pause_after_first_row;
|
|
/*
|
* Keep scanning past a structurally present but invalid record (bad CRC /
|
* fields) instead of stopping with the torn-tail / mid-file
|
* classification: the census consumers (fsck) count every invalid record
|
* and carry on to report all damage. A partial trailing record still
|
* ends the scan - the transport folds it into the clean end. Incompatible
|
* with the classification report (there is no single stop to classify)
|
* and with applying: consumers that apply records must stop at the first
|
* invalid one.
|
*/
|
bool continue_on_invalid;
|
|
/*
|
* Stop at the first invalid record without classifying it: no size stat,
|
* no ereport, no WARNING - whatever the sink raised so far stands. The
|
* soft contract of the aggregate consumers (the max-generation seed):
|
* their result is advisory, and the next checkpoint recomputes it, so
|
* degrading quietly beats failing the caller. Incompatible with
|
* continue_on_invalid (one stop, no census) and with applying.
|
*/
|
bool soft_invalid_stop;
|
} CfsJournalScanPolicy;
|
|
typedef struct CfsJournalScanResult
|
{
|
CfsScanStopReason reason; /* why the scan stopped */
|
off_t stop_off; /* the record it stopped at (EOF: the next
|
* unconsumed offset) */
|
int64 applied; /* validated records delivered to the sink */
|
} CfsJournalScanResult;
|
|
/*
|
* Scan the journal from 'start_off' (clamped to the header size) through
|
* the policy, applying every valid record through 'sink'. Returns
|
* result->applied; for a torn record the classification reports at
|
* WARNING/DEBUG1 and may raise for a journal-size stat failure
|
* (soft_invalid_stop skips the classification entirely, so neither
|
* happens there); may also raise through the sink.
|
*/
|
extern int64 cfs_journal_scan(struct CfsRelation *cfs, off_t start_off,
|
const CfsJournalScanPolicy * policy,
|
CfsJournalSink *sink,
|
CfsJournalScanResult * result);
|
|
/*
|
* The descriptor-based form of the same engine, for consumers that hold
|
* an open journal fd but no CfsRelation handle (the swap recovery and
|
* the generation seeding): records are NOT applied - valid ones are
|
* offered to sink->see_record, invalid ones (under
|
* policy->continue_on_invalid) to sink->invalid_record - and a torn stop
|
* is classified from the file size alone. 'jrn_path' names the file in
|
* the torn-stop reports.
|
*/
|
extern int64 cfs_journal_scan_fd(int jrn_fd, const char *jrn_path,
|
off_t start_off,
|
const CfsJournalScanPolicy * policy,
|
CfsJournalSink *sink,
|
CfsJournalScanResult * result);
|
|
/*
|
* Raise *max_gen to the highest generation carried by any valid UPDATE
|
* record of the journal behind 'jrn_fd', stopping at the first torn
|
* record. Shared by the generation seeding and the swap recovery's
|
* journal-reset stamp.
|
*/
|
extern int cfs_journal_fd_scan_max_generation(int jrn_fd,
|
const char *jrn_path,
|
uint32 *max_gen);
|
|
/*
|
* The outcome of cfs_journal_measure_nblocks().
|
*/
|
typedef enum CfsJournalMeasureStatus
|
{
|
CFS_JOURNAL_MEASURE_OK, /* clean end of records: trusted size */
|
CFS_JOURNAL_MEASURE_TORN_TAIL, /* crash artifact tolerated: records
|
* before it stand, trusted size */
|
CFS_JOURNAL_MEASURE_MIDFILE /* torn record with valid records behind
|
* it: no size can be trusted */
|
} CfsJournalMeasureStatus;
|
|
/*
|
* cfs_journal_measure_nblocks - the O(journal) logical-size measurement
|
* for the smgrnblocks() cache-miss path: the row count of the on-disk
|
* .cfsmap (stat, no map read) plus the journal's last valid RESIZE
|
* record, without opening a handle or building a private full map.
|
* The caller must hold the relation's append lock (SHARED is enough);
|
* see the implementation for the consistency argument and the damage
|
* policy. OK and TORN_TAIL fill '*nblocks' (the torn tail is the
|
* tolerated crash artifact: the RESIZEs before it stand). MIDFILE
|
* trusts no size - '*nblocks' is untouched, '*torn_off' receives the
|
* record the scan stopped at, and the CALLER escalates by its context
|
* (a backend through cfs_report_corruption(); the startup process
|
* through the recovery severity, with a full-map fallback when
|
* non-strict). Every other failure raises.
|
*/
|
extern CfsJournalMeasureStatus
|
cfs_journal_measure_nblocks(RelFileLocatorBackend rl,
|
ForkNumber forknum,
|
BlockNumber *nblocks,
|
off_t *torn_off);
|
|
#endif /* CFS_JOURNAL_H */
|