Исходный код СУБД 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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
/*-------------------------------------------------------------------------
 * cfs_journal.c
 *    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/backend/storage/cfs/cfs_journal.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
 
#include "access/xlogutils.h"
#include "utils/injection_point.h"
 
#include <sys/stat.h>
#include <unistd.h>
 
#include "storage/cfs/cfs_cfp.h"
#include "storage/cfs/cfs_format.h"
#include "storage/cfs/cfs_guc.h"
#include "storage/cfs/cfs_journal.h"
#include "storage/cfs/cfs_path.h"
#include "storage/cfs/cfs_recovery.h"
#include "storage/cfs/cfs_storage.h"
#include "storage/fd.h"
#include "utils/palloc.h"
#include "utils/wait_event.h"
 
void
cfs_journal_reader_init(CfsJournalReader *r, int fd, off_t start_off)
{
    r->fd = fd;
    r->off = start_off;
    r->buf = palloc(CFS_JOURNAL_READ_CHUNK);
    r->buflen = 0;
    r->bufpos = 0;
    r->rc = CFS_STORAGE_OK;
    r->fail_next_read = false;
}
 
void
cfs_journal_reader_free(CfsJournalReader *r)
{
    pfree(r->buf);
}
 
/*
 * Fetch the next full journal record into *je.  Returns false at the
 * clean end of records (rc == NOENT) or after an I/O error (rc ==
 * ERROR); the caller checks r->rc to tell them apart.
 */
bool
cfs_journal_reader_next(CfsJournalReader *r, CfsJournalEntry *je)
{
    if (r->bufpos + CFS_JOURNAL_ENTRY_SIZE <= r->buflen)
    {
        memcpy(je, r->buf + r->bufpos, CFS_JOURNAL_ENTRY_SIZE);
        r->bufpos += CFS_JOURNAL_ENTRY_SIZE;
        r->rec_off = r->off;
        r->off += CFS_JOURNAL_ENTRY_SIZE;
        return true;
    }
 
    if (r->rc != CFS_STORAGE_OK)
        return false;
 
    {
        size_t      done = 0;
 
        while (done < CFS_JOURNAL_READ_CHUNK)
        {
            ssize_t     n;
            size_t      len = CFS_JOURNAL_READ_CHUNK - done;
 
            if (r->fail_next_read)
            {
                r->fail_next_read = false;
                errno = EIO;
                n = -1;
            }
            else
                n = pg_pread(r->fd, r->buf + done, len, r->off + done);
            if (n < 0)
            {
                if (errno == EINTR)
                    continue;
                ereport(WARNING,
                        (errcode_for_file_access(),
                         errmsg("CFS: pread failed: %m")));
                r->rc = CFS_STORAGE_ERROR;
                return false;
            }
            if (n == 0)
                break;
            done += n;
        }
 
        r->buflen = done;
        r->bufpos = 0;
 
        /* A partial trailing record is the clean end (see above). */
        if (done < CFS_JOURNAL_ENTRY_SIZE)
        {
            r->rc = CFS_STORAGE_NOENT;
            return false;
        }
    }
 
    return cfs_journal_reader_next(r, je);
}
 
bool
cfs_journal_read_header(int fd, CfsJournalFileHeader *out)
{
    if (cfs_pread_all(fd, out, sizeof(*out), 0) != CFS_STORAGE_OK)
        return false;
    return cfs_journal_header_validate(out) == CFS_FORMAT_OK;
}
 
bool
cfs_journal_read_header_fields(int fd, CfsJournalFileHeader *out)
{
    if (cfs_pread_all(fd, out, sizeof(*out), 0) != CFS_STORAGE_OK)
        return false;
    return out->magic == CFS_JRN_MAGIC && out->version == CFS_JRN_VERSION;
}
 
void
cfs_journal_header_init_bumped(int fd, CfsJournalFileHeader *jhdr,
                               uint32 max_generation)
{
    CfsJournalFileHeader old_jhdr;
 
    cfs_journal_header_init(jhdr);
    if (cfs_journal_read_header_fields(fd, &old_jhdr))
    {
        jhdr->incarnation = old_jhdr.incarnation + 1;
        if (old_jhdr.max_generation > max_generation)
            max_generation = old_jhdr.max_generation;
    }
    jhdr->max_generation = max_generation;
    cfs_journal_header_set_crc(jhdr);
}
 
void
cfs_journal_finish_reset(int fd, const char *jrn_path,
                         CfsJournalFileHeader *jhdr,
                         off_t end_off, int elevel)
{
    /*
     * Every step of the reset tail respects 'elevel': the whole sequence is
     * idempotent (a crash mid-way repeats it on the next pass), so a soft
     * elevel (recovery's WARNING) applies uniformly - not just to the
     * truncate, which used to be the only step that honoured it.
     */
    if (cfs_pwrite_all(fd, jhdr, sizeof(*jhdr), 0) != CFS_STORAGE_OK)
        ereport(elevel,
                (errcode_for_file_access(),
                 errmsg("CFS: could not rewrite journal header of \"%s\"",
                        jrn_path)));
 
    {
        bool        truncate_failed;
 
        if (cfs_debug_fail_truncate > 0)
        {
            cfs_debug_fail_truncate--;
            errno = EIO;
            truncate_failed = true;
        }
        else
            truncate_failed = (pg_truncate(jrn_path, end_off) != 0);
 
        if (truncate_failed)
            ereport(elevel,
                    (errcode_for_file_access(),
                     errmsg("CFS: could not truncate journal \"%s\": %m",
                            jrn_path)));
    }
 
    pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC);
    if (pg_fsync(fd) != 0)
    {
        pgstat_report_wait_end();
        ereport(elevel,
                (errcode_for_file_access(),
                 errmsg("CFS: could not fsync journal \"%s\": %m",
                        jrn_path)));
    }
    pgstat_report_wait_end();
}
 
void
cfs_journal_reset_file(const char *jrn_path, uint32 max_generation)
{
    CfsJournalFileHeader jhdr;
    int         fd;
 
    fd = BasicOpenFile(jrn_path, O_CREAT | O_RDWR | PG_BINARY);
    if (fd < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not open journal \"%s\" for reset: %m",
                        jrn_path)));
 
    /*
     * Bump the incarnation so backends notice the reset even when the journal
     * later grows back past their saved replay offset (ABA).  An unreadable
     * previous header starts the incarnation sequence over.
     */
    cfs_journal_header_init_bumped(fd, &jhdr, max_generation);
 
    /*
     * Finish through the shared reset tail - the durability sequence (header,
     * truncate, fsync) is the same one every reset point runs.
     */
    cfs_journal_finish_reset(fd, jrn_path, &jhdr,
                             (off_t) CFS_JOURNAL_HEADER_SIZE, ERROR);
    close(fd);
 
    ereport(DEBUG1,
            (errmsg("CFS: journal \"%s\" reset to bare header", jrn_path)));
}
 
/* The private handle-based reset tail (see cfs_journal_reset_point). */
static void cfs_journal_reset(struct CfsRelation *cfs, uint32 max_generation,
                              int elevel);
 
void
cfs_journal_reset_point(CfsRelation *cfs, uint32 watermark, int elevel)
{
    /*
     * The one reset entry point for every handle-based path (checkpoint,
     * immedsync, recovery).  The contract, fixed HERE:
     *
     * 1. the caller has already made the payload durable - the .cfsmap rows
     * the fold wrote / the saved snapshot / the swapped-in pair - and fsynced
     * the .cfp data the surviving journal records reference; 2. this helper
     * then flushes the journal itself, so the boundary it stamps is durable
     * before any reset can erase the records; 3. the watermark never
     * regresses: header_init_bumped() takes the max over the passed value and
     * the previous header, so every caller's source (fold maxima, map
     * summary) meets the same single maximum.
     *
     * The caller must hold the relation's append lock.  The one path that
     * resets by path on files it no longer owns - compaction, after its swap
     * - uses cfs_journal_reset_file() instead (the documented exception, see
     * the CFS review rules (README.md, "Review rules")).
     */
    pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC);
    if (pg_fsync(cfs->jrn_fd) != 0)
    {
        pgstat_report_wait_end();
        ereport(data_sync_elevel(ERROR),
                (errcode_for_file_access(),
                 errmsg("CFS: could not fsync journal \"%s\": %m",
                        cfs->jrn_path)));
    }
    pgstat_report_wait_end();
 
    cfs_journal_reset(cfs, watermark, elevel);
}
 
/*
 * The handle-based reset itself: private to this module so that
 * cfs_journal_reset_point() (the durability contract) and
 * cfs_journal_reset_file() (the compaction exception) are the only two
 * ways a journal ever gets reset.
 */
static void
cfs_journal_reset(struct CfsRelation *cfs, uint32 max_generation, int elevel)
{
    CfsJournalFileHeader jhdr;
 
    Assert(cfs != NULL && !cfs->read_only);
 
    if (cfs->jrn_fd < 0)
        return;
 
    cfs_journal_header_init_bumped(cfs->jrn_fd, &jhdr, max_generation);
    cfs_journal_finish_reset(cfs->jrn_fd, cfs->jrn_path, &jhdr,
                             (off_t) CFS_JOURNAL_HEADER_SIZE, elevel);
 
    cfs->jrn_write_off = (off_t) CFS_JOURNAL_HEADER_SIZE;
    cfs->jrn_incarnation = jhdr.incarnation;
 
    ereport(DEBUG1,
            (errmsg("CFS: journal reset (incarnation %u)",
                    (unsigned) jhdr.incarnation)));
}
 
/*
 * The torn-record classification of the scan engine: a torn record with
 * nothing (but a partial of itself) behind it is the crash artifact - the
 * tail; a torn record with whole records following it is corruption,
 * because those records are the only durable trace of their changes.
 * Reports ONCE, with the caller's role in the message.
 */
static bool
cfs_scan_torn_is_tail(CfsRelation *cfs, off_t rec_off, const char *role,
                      bool during_recovery)
{
    off_t       jrn_size = cfs_fd_size(cfs->jrn_fd);
    bool        is_tail;
 
    /*
     * Without the file size the tail question cannot be answered, and
     * guessing "tail" would let a caller drop valid records behind the torn
     * one.  An I/O failure here is fatal, not a torn-tail verdict.
     */
    if (jrn_size < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not determine the journal size of \"%s\"",
                        cfs->jrn_path)));
 
    is_tail = (jrn_size - rec_off <= (off_t) sizeof(CfsJournalEntry));
    if (!is_tail)
    {
        if (cfs->strict)
            cfs_report_corruption(cfs->rlocator, cfs->forknum,
                                  InvalidBlockNumber,
                                  psprintf("torn journal record at offset "
                                           "%lld with %lld byte(s) of "
                                           "records following it",
                                           (long long) rec_off,
                                           (long long) (jrn_size - rec_off)),
                                  during_recovery);
        ereport(WARNING,
                (errcode(ERRCODE_DATA_CORRUPTED),
                 errmsg("CFS: stopping journal %s at offset %lld (torn record)",
                        role, (long long) rec_off)));
    }
    else
    {
        ereport(DEBUG1,
                (errmsg("CFS: stopping journal %s at offset %lld (torn record)",
                        role, (long long) rec_off)));
    }
 
    return is_tail;
}
 
/*
 * The size-only form of the classification, shared with the descriptor
 * consumers that hold no handle (cfs_journal_scan_fd): the verdict is the
 * same, but there is no strict-mode corruption report channel (and no
 * applying consumer that would need one) - the message is the whole
 * report.
 */
static bool
cfs_scan_torn_is_tail_fd(int jrn_fd, const char *jrn_path, off_t rec_off,
                         const char *role)
{
    off_t       jrn_size = cfs_fd_size(jrn_fd);
    bool        is_tail;
 
    if (jrn_size < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not determine the journal size of \"%s\"",
                        jrn_path)));
 
    is_tail = (jrn_size - rec_off <= (off_t) sizeof(CfsJournalEntry));
    ereport(is_tail ? DEBUG1 : WARNING,
            (errcode(ERRCODE_DATA_CORRUPTED),
             errmsg("CFS: stopping journal %s at offset %lld (torn record)",
                    role, (long long) rec_off)));
    return is_tail;
}
 
/*
 * The one journal scan loop (review I3), both entry points included:
 * every consumer that walks the journal runs this core with its own
 * policy and sink.  'cfs' non-NULL selects the applying form
 * (cfs_journal_scan); NULL selects the descriptor form
 * (cfs_journal_scan_fd), which only observes records through
 * sink->see_record / sink->invalid_record and never applies them.
 */
static int64
cfs_journal_scan_core(int jrn_fd, const char *jrn_path, CfsRelation *cfs,
                      off_t start_off, const CfsJournalScanPolicy * policy,
                      CfsJournalSink *sink, CfsJournalScanResult * result)
{
    CfsJournalReader jr;
    CfsJournalEntry je;
    int64       applied = 0;
    int64       map_rows = 0;
 
    memset(result, 0, sizeof(*result));
    result->reason = CFS_SCAN_STOP_EOF;
    result->stop_off = start_off;
 
    if (start_off < (off_t) CFS_JOURNAL_HEADER_SIZE)
        start_off = (off_t) CFS_JOURNAL_HEADER_SIZE;
 
    pgstat_report_wait_start(WAIT_EVENT_CFS_JOURNAL_REPLAY);
    cfs_journal_reader_init(&jr, jrn_fd, start_off);
    if (policy->fail_next_read)
        jr.fail_next_read = true;
 
    while (cfs_journal_reader_next(&jr, &je))
    {
        CfsFormatStatus vst = cfs_journal_entry_validate(&je);
 
        if (policy->limit > 0 &&
            jr.rec_off + (off_t) sizeof(CfsJournalEntry) > policy->limit)
        {
            /*
             * The fold boundary: the caller sampled the limit BEFORE its .cfp
             * fsync, so every record below it references data that fsync
             * flushed; a record at/after it stays in the tail.
             */
            ereport(DEBUG1,
                    (errmsg("CFS: journal fold stopped at fold boundary %lld (record offset %lld)",
                            (long long) policy->limit,
                            (long long) jr.rec_off)));
            result->reason = CFS_SCAN_STOP_BOUNDARY;
            result->stop_off = Min(jr.rec_off, policy->limit);
            break;
        }
 
        if (vst != CFS_FORMAT_OK)
        {
            if (policy->continue_on_invalid)
            {
                if (sink != NULL && sink->invalid_record != NULL)
                    sink->invalid_record(sink->arg, jr.rec_off, vst);
                continue;
            }
 
            /*
             * The soft stop: no classification, no size stat, no report - the
             * aggregate consumer keeps whatever its sink raised so far and
             * the next checkpoint recomputes the stamp.  TORN_TAIL is the
             * closest reason (the record is dead weight to this consumer),
             * and an aggregate reads nothing but the IO_ERROR bit anyway.
             */
            if (policy->soft_invalid_stop)
            {
                result->reason = CFS_SCAN_STOP_TORN_TAIL;
                result->stop_off = jr.rec_off;
                break;
            }
 
            result->reason =
                cfs != NULL
                ? (cfs_scan_torn_is_tail(cfs, jr.rec_off, policy->role,
                                         policy->during_recovery)
                   ? CFS_SCAN_STOP_TORN_TAIL
                   : CFS_SCAN_STOP_TORN_MIDFILE)
                : (cfs_scan_torn_is_tail_fd(jrn_fd, jrn_path, jr.rec_off,
                                            policy->role)
                   ? CFS_SCAN_STOP_TORN_TAIL
                   : CFS_SCAN_STOP_TORN_MIDFILE);
            result->stop_off = jr.rec_off;
            break;
        }
 
        if (sink != NULL && sink->see_record != NULL)
            sink->see_record(sink->arg, &je);
        if (cfs != NULL)
            cfs_journal_apply_record(cfs, &je, sink);
        applied++;
 
        if (je.op != CFS_JRN_OP_RESIZE)
            map_rows++;
        if (policy->pause_after_first_row != NULL && map_rows == 1)
            INJECTION_POINT(policy->pause_after_first_row, NULL);
    }
 
    if (jr.rc == CFS_STORAGE_ERROR)
        result->reason = CFS_SCAN_STOP_IO_ERROR;
    else if (result->reason == CFS_SCAN_STOP_EOF)
        result->stop_off = jr.off;
 
    cfs_journal_reader_free(&jr);
    pgstat_report_wait_end();
 
    result->applied = applied;
    return applied;
}
 
int64
cfs_journal_scan(CfsRelation *cfs, off_t start_off,
                 const CfsJournalScanPolicy * policy,
                 CfsJournalSink *sink, CfsJournalScanResult * result)
{
    return cfs_journal_scan_core(cfs->jrn_fd, cfs->jrn_path, cfs,
                                 start_off, policy, sink, result);
}
 
int64
cfs_journal_scan_fd(int jrn_fd, const char *jrn_path, off_t start_off,
                    const CfsJournalScanPolicy * policy,
                    CfsJournalSink *sink, CfsJournalScanResult * result)
{
    return cfs_journal_scan_core(jrn_fd, jrn_path, NULL,
                                 start_off, policy, sink, result);
}
 
/* The max-generation aggregate: one observer, no application. */
static void
cfs_journal_max_generation_sink(void *arg, const CfsJournalEntry *je)
{
    uint32     *max_gen = (uint32 *) arg;
 
    if (je->op == CFS_JRN_OP_UPDATE &&
        je->new_entry.generation > *max_gen)
        *max_gen = je->new_entry.generation;
}
 
int
cfs_journal_fd_scan_max_generation(int jrn_fd, const char *jrn_path,
                                   uint32 *max_gen)
{
    CfsJournalScanPolicy policy;
    CfsJournalSink sink;
    CfsJournalScanResult result;
 
    memset(&policy, 0, sizeof(policy));
    policy.role = "seed";
    policy.soft_invalid_stop = true;
    memset(&sink, 0, sizeof(sink));
    sink.see_record = cfs_journal_max_generation_sink;
    sink.arg = max_gen;
 
    (void) cfs_journal_scan_fd(jrn_fd, jrn_path,
                               (off_t) CFS_JOURNAL_HEADER_SIZE,
                               &policy, &sink, &result);
    if (result.reason == CFS_SCAN_STOP_IO_ERROR)
        return CFS_STORAGE_ERROR;
    return CFS_STORAGE_OK;
}
 
/*
 * The size observer of cfs_journal_measure_nblocks: remember only the
 * last RESIZE target.  Records arrive in journal order and a RESIZE
 * record carries the absolute target nblocks (not a delta), so the last
 * one seen is the last one on disk and simply overwrites whatever an
 * earlier RESIZE set; UPDATE/DELETE records never change the size.
 */
typedef struct CfsJournalMeasureCtx
{
    BlockNumber resize_target;  /* last RESIZE target seen                */
    bool        have_resize;    /* a valid RESIZE record was seen         */
}           CfsJournalMeasureCtx;
 
static void
cfs_journal_measure_record(void *arg, const CfsJournalEntry *je)
{
    CfsJournalMeasureCtx *ctx = (CfsJournalMeasureCtx *) arg;
 
    if (je->op == CFS_JRN_OP_RESIZE)
    {
        ctx->resize_target = je->blocknum;
        ctx->have_resize = true;
    }
}
 
/*
 * cfs_journal_measure_nblocks - measure the logical size of a CFS
 * relation from the sidecar pair alone: the row count derived from the
 * .cfsmap file size (the base every fold leaves behind) plus, when the
 * journal holds any, the last valid RESIZE record's absolute target.
 * Built for the smgrnblocks() cache-miss path (QDB-1516), which must
 * stay O(journal) and never build a private full map here.
 *
 * Correctness: the .cfsmap file is resized only at fold points (the
 * checkpoint and recovery folds, the compaction and immedsync swaps),
 * all under the EXCLUSIVE append lock, and every size-changing writer
 * journals a RESIZE under that same lock.  The caller therefore holds
 * the append lock (SHARED is enough): the stat and the scan observe one
 * consistent map/journal pair, and no RESIZE can land between them.
 *
 * Damage policy, mirroring the non-recovery load (cfs_map_load /
 * cfs_journal_replay): a missing journal or one shorter than its header
 * is the legal fresh state (the base rows stand); a full-size header
 * that fails validation is structural damage - during recovery a hard
 * ERROR, outside recovery routed through cfs_report_corruption() so the
 * cfs_checksum_failure GUC decides the severity (QDB-1507 U8, parity
 * with the replay paths); a torn TAIL is the normal crash artifact (the
 * scanner classifies it, and the RESIZEs before it stand); a torn record
 * with valid records behind it is corruption - the RESIZEs past it are
 * unreachable, so no size can be trusted.  That outcome is REPORTED,
 * not raised: the call answers CFS_JOURNAL_MEASURE_MIDFILE with the
 * torn offset, and the caller escalates by its own context (a backend
 * through cfs_report_corruption; the startup process with the recovery
 * severity contract, which WARNINGs and falls back to the full-map
 * measurement when non-strict).
 */
CfsJournalMeasureStatus
cfs_journal_measure_nblocks(RelFileLocatorBackend rl, ForkNumber forknum,
                            BlockNumber *nblocks, off_t *torn_off)
{
    char       *map_path;
    char       *jrn_path;
    struct stat st;
    uint64      base_rows;
    int         fd;
    CfsJournalMeasureStatus status;
 
    map_path = cfs_make_filename(rl, forknum, CFS_FILE_MAP);
    jrn_path = cfs_make_filename(rl, forknum, CFS_FILE_JOURNAL);
    Assert(map_path != NULL && jrn_path != NULL);
 
    /*
     * The base size: rows derived from the file size (a partial trailing
     * row is a torn write every loader ignores).  A missing map with the
     * journal still present is a damaged sidecar set, not a vanished
     * relation: the triple is materialized atomically and only a drop
     * removes it, and the drop takes the whole triple - answering zero
     * here (with WAL replay possibly overwriting live blocks from block
     * 0, see the nblocks contract) would launder the damage, so raise
     * exactly like the full-open path this measurement replaced.  When
     * the journal is gone too, the .cfp decides: a surviving data file
     * with neither map nor journal is external damage (the drop removes
     * the whole triple) and fails just as loudly; only all three gone
     * is the drop or rewrite race that raced the caller's cfs_exists()
     * check, and zero is the genuine answer.
     */
    if (stat(map_path, &st) != 0)
    {
        if (errno == ENOENT)
        {
            struct stat jst;
            char       *cfp_path;
            uint32      segno;
 
            if (stat(jrn_path, &jst) == 0)
                ereport(ERROR,
                        (errcode(ERRCODE_DATA_CORRUPTED),
                         errmsg("CFS: map file is missing for "
                                "relation %u/%u/%u",
                                rl.locator.spcOid, rl.locator.dbOid,
                                rl.locator.relNumber),
                         errdetail("Sidecar journal \"%s\" exists but "
                                   "\"%s\" does not.",
                                   jrn_path, map_path)));
            if (errno != ENOENT)
                ereport(ERROR,
                        (errcode_for_file_access(),
                         errmsg("CFS: could not stat journal file \"%s\": %m",
                                jrn_path)));
 
            /*
             * The journal is gone too, so the pair may be mid-drop - but
             * only the whole triple disappears at once, and the .cfp is
             * the witness that decides: a surviving data file with
             * neither map nor journal is external damage and must fail
             * loudly exactly like the journal witness above; all three
             * gone is the drop (or rewrite) race, and zero is the true
             * answer.  A surviving numbered segment (.cfp.1, .cfp.2,
             * ...) is the same witness, so the walk below checks the
             * whole chain.
             */
            cfp_path = cfs_make_filename(rl, forknum, CFS_FILE_DATA);
            if (stat(cfp_path, &jst) == 0)
                ereport(ERROR,
                        (errcode(ERRCODE_DATA_CORRUPTED),
                         errmsg("CFS: map file is missing for "
                                "relation %u/%u/%u",
                                rl.locator.spcOid, rl.locator.dbOid,
                                rl.locator.relNumber),
                         errdetail("Sidecar data file \"%s\" exists but "
                                   "neither \"%s\" nor \"%s\" does.",
                                   cfp_path, map_path, jrn_path)));
            if (errno != ENOENT)
                ereport(ERROR,
                        (errcode_for_file_access(),
                         errmsg("CFS: could not stat data file \"%s\": %m",
                                cfp_path)));
 
            /*
             * The data file is segmented (.cfp.1, .cfp.2, ... for large
             * relations), so a missing base segment is not yet a missing
             * data witness: walk the chain until the first hole.  The
             * chain is append-ordered and dense, so the first ENOENT ends
             * it; any surviving segment is the same loud witness as the
             * base file above.
             */
            for (segno = 1;; segno++)
            {
                char       *seg_path =
                    cfs_make_segment_filename(rl, forknum,
                                              CFS_FILE_DATA, segno);
 
                if (stat(seg_path, &jst) == 0)
                    ereport(ERROR,
                            (errcode(ERRCODE_DATA_CORRUPTED),
                             errmsg("CFS: map file is missing for "
                                    "relation %u/%u/%u",
                                    rl.locator.spcOid, rl.locator.dbOid,
                                    rl.locator.relNumber),
                             errdetail("Sidecar data file \"%s\" exists "
                                       "but neither \"%s\" nor \"%s\" "
                                       "does.",
                                       seg_path, map_path, jrn_path)));
                if (errno != ENOENT)
                    ereport(ERROR,
                            (errcode_for_file_access(),
                             errmsg("CFS: could not stat data file \"%s\": %m",
                                    seg_path)));
                pfree(seg_path);
                break;
            }
            pfree(cfp_path);
            pfree(map_path);
            pfree(jrn_path);
            *nblocks = 0;
            return CFS_JOURNAL_MEASURE_OK;
        }
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not stat map file \"%s\": %m",
                        map_path)));
    }
    base_rows = cfs_map_rows_from_size((uint64) st.st_size);
 
    fd = OpenTransientFile(jrn_path, O_RDONLY | PG_BINARY);
    if (fd < 0)
    {
        /*
         * No journal at all: no RESIZE can exist past the fold, and the
         * base rows are the whole answer.
         */
        if (errno == ENOENT)
        {
            pfree(map_path);
            pfree(jrn_path);
            *nblocks = (BlockNumber) base_rows;
            return CFS_JOURNAL_MEASURE_OK;
        }
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not open journal \"%s\": %m", jrn_path)));
    }
 
    PG_TRY();
    {
        CfsJournalMeasureCtx ctx;
        CfsJournalSink sink;
        CfsJournalScanPolicy policy;
        CfsJournalScanResult scan;
        CfsJournalFileHeader jhdr;
        int         rc;
 
        /*
         * Header first, with the load path's exact policy: a short read is
         * the legal fresh state (folded into NOENT below), while a
         * full-size header that fails validation means the records cannot
         * even be trusted to describe themselves.
         */
        rc = cfs_pread_all(fd, &jhdr, sizeof(jhdr), 0);
        if (rc == CFS_STORAGE_NOENT)
        {
            *nblocks = (BlockNumber) base_rows;
            status = CFS_JOURNAL_MEASURE_OK;
        }
        else
        {
            if (rc != CFS_STORAGE_OK)
                ereport(ERROR,
                        (errcode_for_file_access(),
                     errmsg("CFS: could not read journal header of \"%s\": %m",
                            jrn_path)));
            if (cfs_journal_header_validate(&jhdr) != CFS_FORMAT_OK)
            {
                /*
                 * A full-size header that fails validation is structural
                 * damage.  Outside a normal backend session it stays a
                 * hard ERROR (parity with the full replay path); a normal
                 * backend routes it through cfs_report_corruption()
                 * (QDB-1507 U8), so the cfs_checksum_failure GUC decides
                 * ERROR or PANIC exactly like every other structural
                 * header site (cfs_corruption_guc_applies).
                 */
                if (!cfs_corruption_guc_applies())
                    ereport(ERROR,
                            (errcode(ERRCODE_DATA_CORRUPTED),
                             errmsg("CFS: corrupt page map journal"),
                             errdetail("Invalid .cfsjrn header in \"%s\".",
                                       jrn_path)));
                else
                    cfs_report_corruption(rl, forknum, InvalidBlockNumber,
                                          psprintf("invalid .cfsjrn header "
                                                   "in file \"%s\"",
                                                   jrn_path),
                                          false);
            }
 
            ctx.resize_target = 0;
            ctx.have_resize = false;
 
            memset(&sink, 0, sizeof(sink));
            sink.see_record = cfs_journal_measure_record;
            sink.arg = &ctx;
 
            memset(&policy, 0, sizeof(policy));
            policy.role = "nblocks";
 
            (void) cfs_journal_scan_fd(fd, jrn_path,
                                       (off_t) CFS_JOURNAL_HEADER_SIZE,
                                       &policy, &sink, &scan);
 
            /* The transport already logged the failed pread with its errno. */
            if (scan.reason == CFS_SCAN_STOP_IO_ERROR)
                ereport(ERROR,
                        (errcode_for_file_access(),
                         errmsg("CFS: could not read journal \"%s\" to "
                                "measure the relation size",
                                jrn_path)));
 
            /*
             * Mid-file damage: never answer a size here - the unreachable
             * records behind the torn one may hold the real last RESIZE.
             * Hand the torn offset back; the caller owns the severity
             * decision (its context decides, not this file).
             */
            if (scan.reason == CFS_SCAN_STOP_TORN_MIDFILE)
            {
                *torn_off = scan.stop_off;
                status = CFS_JOURNAL_MEASURE_MIDFILE;
            }
            else
            {
                *nblocks = ctx.have_resize ? ctx.resize_target :
                    (BlockNumber) base_rows;
                status = (scan.reason == CFS_SCAN_STOP_TORN_TAIL)
                    ? CFS_JOURNAL_MEASURE_TORN_TAIL
                    : CFS_JOURNAL_MEASURE_OK;
            }
        }
    }
    PG_CATCH();
    {
        CloseTransientFile(fd);
        PG_RE_THROW();
    }
    PG_END_TRY();
 
    CloseTransientFile(fd);
    pfree(map_path);
    pfree(jrn_path);
 
    return status;
}
 
/*
 * The one documented exception to the "no race checks outside cfs_state.c"
 * rule (README.md, "Review rules"): the size signal below is fetched
 * directly because the caller needs the byte count, and re-reading one
 * record past the torn offset is record CONTENT, not pair identity.
 * Everything else about staleness here is derived by the judge.
 */
bool
cfs_journal_tail_changed(CfsRelation *cfs, off_t rec_off)
{
    CfsJournalEntry rec;
    off_t       jrn_size = cfs_fd_size(cfs->jrn_fd);
    ssize_t     n;
 
    if (jrn_size < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not determine the journal size of \"%s\"",
                        cfs->jrn_path)));
 
    /* Any bytes behind the torn record are a change phase 1 never saw. */
    if (jrn_size - rec_off > (off_t) sizeof(rec))
        return true;
 
    /* A record that validates now was completed by a writer meanwhile. */
    do
    {
        n = pg_pread(cfs->jrn_fd, &rec, sizeof(rec), rec_off);
    } while (n < 0 && errno == EINTR);
 
    return (n == (ssize_t) sizeof(rec) &&
            cfs_journal_entry_validate(&rec) == CFS_FORMAT_OK);
}
 
/*
 * Verify that the .cfp record an UPDATE journal record references is on
 * disk and structurally intact.
 */
static bool
cfs_journal_update_data_durable(CfsRelation *cfs, const CfsJournalEntry *je)
{
    CfsCompressedBlockHeader bh;
    off_t       offset = (off_t) je->new_entry.physical_offset;
    int         fd;
 
    if (offset < (off_t) CFS_CFP_BASE_OFFSET)
        return false;
 
    fd = cfs_cfp_read_segment_fd(cfs, CFS_CFP_SEGNO(offset));
    if (fd < 0)
        return false;
 
    if (cfs_pread_all(fd, &bh, sizeof(bh),
                      CFS_CFP_SEG_OFF(offset)) != CFS_STORAGE_OK)
        return false;
 
    return cfs_block_header_validate(&bh) == CFS_FORMAT_OK;
}
 
/*
 * Decide whether an UPDATE record's referenced .cfp data is trustworthy.
 * The journal record can be durable while the data it points at never
 * reached the disk (the kernel may write .cfsjrn pages ahead of .cfp).
 * The replay skips such a record, and the checkpoint fold must apply the
 * same policy: installing the row would freeze the missing data in the
 * map and let the journal reset erase the only evidence.  Reports through
 * the same channel in every caller (WARNING in the normal mode, the
 * centralised corruption handler in strict mode) and returns false when
 * the record must be skipped.
 */
static bool
cfs_journal_update_data_usable(CfsRelation *cfs, const CfsJournalEntry *je,
                               bool during_recovery)
{
    if (cfs_journal_update_data_durable(cfs, je))
        return true;
 
    if (cfs->strict)
        cfs_report_corruption(cfs->rlocator, cfs->forknum, je->blocknum,
                              psprintf("journal UPDATE references missing "
                                       ".cfp data at offset %llu",
                                       (unsigned long long) je->new_entry.physical_offset),
                              during_recovery);
    ereport(WARNING,
            (errcode(ERRCODE_DATA_CORRUPTED),
             errmsg("CFS: skipping journal UPDATE for block %u: "
                    "no valid record at .cfp offset %llu",
                    je->blocknum,
                    (unsigned long long) je->new_entry.physical_offset)));
    return false;
}
 
void
cfs_journal_apply_record(CfsRelation *cfs, const CfsJournalEntry *je,
                         CfsJournalSink *sink)
{
    if (je->op == CFS_JRN_OP_UPDATE)
    {
        /*
         * The generation must be considered occupied even when the record is
         * later skipped for missing .cfp data: the write path must never
         * reuse a value already present in the journal.
         */
        if (je->new_entry.generation > sink->max_generation)
            sink->max_generation = je->new_entry.generation;
        if (sink->filter_range &&
            (je->blocknum < sink->first_block ||
             je->blocknum >= sink->last_block))
            return;
        if (sink->update_usable != NULL)
        {
            if (!sink->update_usable(sink->arg, je))
                return;
        }
        else if (!cfs_journal_update_data_usable(cfs, je,
                                                 sink->recovery_severity))
            return;
        sink->write_row(sink->arg, je->blocknum, &je->new_entry);
    }
    else if (je->op == CFS_JRN_OP_DELETE)
    {
        if (sink->filter_range &&
            (je->blocknum < sink->first_block ||
             je->blocknum >= sink->last_block))
            return;
        {
            CfsMapEntry row;
 
            cfs_map_entry_init(&row);
            sink->write_row(sink->arg, je->blocknum, &row);
        }
    }
    else if (je->op == CFS_JRN_OP_RESIZE)
    {
        sink->resize_target = je->blocknum;
        sink->have_resize = true;
        if (sink->resize != NULL)
            sink->resize(sink->arg, je->blocknum);
    }
}
 
/*
 * cfs_journal_identity()/cfs_journal_identity_equal() were absorbed by the
 * ownership-state judge: the snapshot and the identity comparison now live
 * in cfs_state.c (CfsStateSnapshot, CFS_STATE_JRN_IDENTITY_MOVED).
 */