Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
/*-------------------------------------------------------------------------
 * 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)));
}