Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*-------------------------------------------------------------------------
 * 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 */