Исходный код СУБД 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
/*-------------------------------------------------------------------------
 * cfs_cfp.c
 *    Compressed File Store (CFS) — the segmented .cfp data chain, one
 *    module.
 *
 * Implements cfs_cfp.h: segment path building, the sidecar opener, the
 * append-segment switch, the global append EOF discovery, the read
 * cache, the stat walk and the per-segment fsync.  Page-level readers
 * and writers build on these primitives from cfs_storage.c.
 *
 * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
 *
 * IDENTIFICATION
 *    src/backend/storage/cfs/cfs_cfp.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
 
#include <sys/stat.h>
#include <unistd.h>
 
#include "storage/aio.h"
#include "storage/cfs/cfs.h"
#include "storage/cfs/cfs_cfp.h"
#include "storage/cfs/cfs_storage.h"
#include "storage/cfs/cfs_guc.h"
#include "storage/fd.h"
#include "utils/palloc.h"
#include "utils/wait_event.h"
 
/*
 * cfs_cfp_close_fd — close a descriptor cached in a CfsRelation (.cfp
 * reader/writer caches).  Since the P4-2 read offload, such a descriptor
 * may also sit in a staged or in-flight AIO handle (op_data.read.fd), so
 * the vanilla fd-close discipline applies: submit everything staged with
 * this fd (and let the method wait for in-flight users when it asks for
 * it), exactly what FileClose() does for vfd descriptors (fd.c).  A raw
 * close(2) could otherwise recycle the number while an IO still names
 * it, and a backend-side synchronous execution would read through the
 * recycled descriptor into unrelated bytes.  No-op for descriptors that
 * never reached an IO.
 */
void
cfs_cfp_close_fd(int fd)
{
    pgaio_closing_fd(fd);
    close(fd);
}
 
/* Build the path of .cfp segment 'segno' for an open handle. */
static char *
cfs_cfp_segment_path(const CfsRelation *cfs, uint32 segno)
{
    return cfs_segment_path(cfs->cfp_path, segno);
}
 
int
cfs_open_sidecar(const char *path, int flags, bool create)
{
    int         oflags = PG_BINARY;
    int         fd;
 
    if (flags & CFS_OPEN_RDONLY)
        oflags |= O_RDONLY;
    else
        oflags |= O_RDWR;
 
    if (create)
        oflags |= O_CREAT;
 
    fd = BasicOpenFile(path, oflags);
    if (fd < 0 && !(create && errno == EEXIST))
    {
        ereport(WARNING,
                (errcode_for_file_access(),
                 errmsg("CFS: could not open sidecar file \"%s\": %m",
                        path)));
        return -1;
    }
    return fd;
}
 
char *
cfs_segment_path(const char *base_path, uint32 segno)
{
    if (segno == 0)
        return pstrdup(base_path);
    return psprintf("%s.%u", base_path, segno);
}
 
char *
cfs_segment_suffixed(const char *base_path, uint32 segno,
                     const char *suffix)
{
    if (segno == 0)
        return psprintf("%s%s", base_path, suffix);
    return psprintf("%s.%u%s", base_path, segno, suffix);
}
 
/*
 * Open (and optionally create) .cfp segment 'segno' of an open handle.
 * Returns the fd, -1 when the segment does not exist and 'create' is
 * false, or -2 on a hard error (the segment may exist but cannot be
 * stat'ed or opened).  Callers walking the segment chain must treat -2
 * as fatal: mistaking it for the end of the chain truncates the append
 * EOF and lets a later append overwrite live records.
 */
static int
cfs_cfp_open_segment(const CfsRelation *cfs, uint32 segno, bool create)
{
    char       *path = cfs_cfp_segment_path(cfs, segno);
    int         fd;
    struct stat st;
 
    if (!create && stat(path, &st) != 0)
    {
        if (errno == ENOENT)
        {
            pfree(path);
            return -1;
        }
        ereport(WARNING,
                (errcode_for_file_access(),
                 errmsg("CFS: could not stat .cfp segment \"%s\": %m", path)));
        pfree(path);
        return -2;
    }
 
    fd = cfs_open_sidecar(path, cfs->flags, create);
    pfree(path);
    if (fd < 0)
        return -2;              /* cfs_open_sidecar already warned */
    return fd;
}
 
/*
 * Switch the append descriptor of 'cfs' to segment 'segno', creating the
 * segment when the handle is writable.  The previous append segment is
 * closed; its durability is covered by the per-segment fsync loop in
 * cfs_fsync_kind() and by the checkpointer sync handler, both of which
 * walk the segment chain by path.
 */
int
cfs_cfp_switch_append_segment(CfsRelation *cfs, uint32 segno)
{
    char       *path;
    int         fd;
    struct stat st;
    bool        existed;
 
    Assert(!cfs->read_only);
 
    path = cfs_cfp_segment_path(cfs, segno);
    existed = (stat(path, &st) == 0);
 
    fd = cfs_cfp_open_segment(cfs, segno, true);
    if (fd < 0)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not open .cfp segment \"%s\"", path)));
 
    if (cfs->cfp_fd >= 0)
        cfs_cfp_close_fd(cfs->cfp_fd);
    cfs->cfp_fd = fd;
    cfs->cfp_append_segno = segno;
 
    /*
     * A freshly created segment gets no WAL record (unlike the base sidecars,
     * which the XLOG_SMGR_CFS_POLICY redo recreates), so make its directory
     * entry durable right away: a crash that loses the dirent while the
     * journal record survives would leave map entries pointing at a segment
     * that does not exist.
     */
    if (!existed)
        cfs_fsync_parent_dir(path, WARNING);
 
    pfree(path);
 
    ereport(DEBUG1,
            (errmsg("CFS: switched .cfp append segment to %u for relation %u/%u/%u",
                    segno,
                    cfs->rlocator.locator.spcOid,
                    cfs->rlocator.locator.dbOid,
                    cfs->rlocator.locator.relNumber)));
    return CFS_STORAGE_OK;
}
 
/*
 * Discover the append EOF of the segmented .cfp chain: walk forward from
 * the current append segment to the last existing one and return the
 * global EOF offset.  A non-final segment may be SHORT — its rollover
 * padding was never written — so "size < CFS_SEGMENT_SIZE" does NOT
 * terminate the chain; only a missing next segment does.  When the last
 * segment is exactly full, the EOF lands on the next boundary and the
 * first append creates that segment.
 */
off_t
cfs_cfp_discover_eof(CfsRelation *cfs)
{
    uint32      segno = cfs->cfp_append_segno;
    int         fd = cfs->cfp_fd;
    off_t       sz = cfs_fd_size(fd);
 
    for (;;)
    {
        int         next_fd;
 
        /*
         * The engine never writes a segment larger than CFS_SEGMENT_SIZE, so
         * an oversized one can only come from outside interference with the
         * data directory.
         */
        if (sz > (off_t) CFS_SEGMENT_SIZE)
            ereport(ERROR,
                    (errcode(ERRCODE_DATA_CORRUPTED),
                     errmsg("CFS: .cfp segment %u of relation %u/%u/%u is larger than the segment size",
                            segno,
                            cfs->rlocator.locator.spcOid,
                            cfs->rlocator.locator.dbOid,
                            cfs->rlocator.locator.relNumber)));
 
        /*
         * Fast path: while the last segment still has room for one more
         * maximal record, no peer append can have rolled into a new segment,
         * so the next-segment probe can be skipped.  (This also keeps the
         * common single-segment case at one fstat per append, same as before
         * segmentation.)
         */
        if (sz <= (off_t) (CFS_SEGMENT_SIZE - CFS_RECORD_SIZE(CFS_BLCKSZ)))
            break;
 
        next_fd = cfs_cfp_open_segment(cfs, segno + 1, false);
        if (next_fd == -2)
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("CFS: could not open .cfp segment %u of relation %u/%u/%u",
                            segno + 1,
                            cfs->rlocator.locator.spcOid,
                            cfs->rlocator.locator.dbOid,
                            cfs->rlocator.locator.relNumber)));
        if (next_fd < 0)
            break;              /* end of the chain */
        if (fd >= 0)
            cfs_cfp_close_fd(fd);
        fd = next_fd;
        segno++;
 
        /*
         * Keep the handle's descriptor fields in sync with the walk: an ERROR
         * raised by the probes above (oversized segment, or a hard open error
         * on the next iteration) must not leave cfs->cfp_fd holding a
         * descriptor this loop has already closed.  The OS is free to recycle
         * the numeric value for an unrelated file, and a later append through
         * the handle would then write into that file.
         */
        cfs->cfp_fd = fd;
        cfs->cfp_append_segno = segno;
 
        sz = cfs_fd_size(fd);
    }
 
    return (off_t) ((uint64) segno * CFS_SEGMENT_SIZE) + sz;
}
 
int
cfs_cfp_read_segment_fd(CfsRelation *cfs, uint32 segno)
{
    if (cfs->cfp_fd >= 0 && cfs->cfp_append_segno == segno)
        return cfs->cfp_fd;
 
    if (cfs->cfp_read_fd >= 0 && cfs->cfp_read_segno == segno)
        return cfs->cfp_read_fd;
 
    if (cfs->cfp_read_fd >= 0)
        cfs_cfp_close_fd(cfs->cfp_read_fd);
 
    cfs->cfp_read_fd = cfs_cfp_open_segment(cfs, segno, false);
    cfs->cfp_read_segno = segno;
 
    /*
     * ponytail: a single cached read descriptor; reads that alternate between
     * two segments reopen on every switch.  Upgrade path: a small LRU of
     * segment descriptors.
     */
    return cfs->cfp_read_fd;
}
 
void
cfs_fsync_parent_dir(const char *path, int elevel)
{
    char       *dname = pstrdup(path);
    char       *slash = strrchr(dname, '/');
 
    if (slash != NULL)
    {
        if (slash == dname)
            slash[1] = '\0';    /* keep the root "/" */
        else
            *slash = '\0';
        (void) fsync_fname_ext(dname, true, false, elevel);
    }
    pfree(dname);
}
 
/*
 * Stat-walk the segmented .cfp chain rooted at 'cfp_path'.  Sets
 * *total_size to the global EOF (segno_last * CFS_SEGMENT_SIZE + size of
 * the last segment) and *closed_padding to the bytes the CLOSED segments
 * never received: a record never crosses a segment boundary, so a
 * non-final segment simply ends short of CFS_SEGMENT_SIZE, and that
 * unwritten tail is structural padding - neither live data nor dead
 * (compaction cannot reclaim it), which the checkpoint's dead-space
 * accounting must subtract.  Either out pointer may be
 * NULL.  Returns false when the chain holds no readable segment.
 */
bool
cfs_cfp_chain_stat(const char *cfp_path, uint64 *total_size,
                   uint64 *closed_padding)
{
    uint64      total = 0;
    uint64      padding = 0;
    uint64      prev_size = 0;
    bool        any = false;
    uint32      segno;
 
    /* A NULL path is "no chain at all", like a missing base segment. */
    if (cfp_path == NULL)
    {
        if (total_size != NULL)
            *total_size = 0;
        if (closed_padding != NULL)
            *closed_padding = 0;
        return false;
    }
 
    for (segno = 0;; segno++)
    {
        char       *seg_path = cfs_segment_path(cfp_path, segno);
        struct stat st;
        uint64      size;
 
        if (stat(seg_path, &st) != 0 || st.st_size < 0)
        {
            pfree(seg_path);
            break;
        }
        any = true;
 
        /*
         * The engine never writes past the boundary; clamp defensively so an
         * oversized segment (outside interference) cannot wrap the unsigned
         * arithmetic below.
         */
        size = (uint64) Min(st.st_size, (off_t) CFS_SEGMENT_SIZE);
 
        /*
         * The existence of THIS segment closes the previous one: its
         * unwritten tail is padding.  The LAST segment (the one the loop ends
         * on) is still growing - including when it is exactly full (total %
         * SEG == 0: the next segment appears lazily on the next append) - and
         * contributes no padding.
         */
        if (segno > 0)
            padding += (uint64) CFS_SEGMENT_SIZE - prev_size;
 
        prev_size = size;
        total = (uint64) segno * CFS_SEGMENT_SIZE + size;
        pfree(seg_path);
    }
 
    if (!any)
        return false;
 
    if (total_size != NULL)
        *total_size = total;
    if (closed_padding != NULL)
        *closed_padding = padding;
    return true;
}
 
/*
 * fsync every existing .cfp segment of the handle.  The per-relation
 * append descriptor covers only the current append segment, and other
 * backends may have written earlier segments through their own handles,
 * so durability is arranged by walking the segment chain by path.
 */
int
cfs_fsync_cfp_segments(CfsRelation *cfs)
{
    uint32      segno;
 
    for (segno = 0;; segno++)
    {
        char       *path;
        int         fd;
        bool        close_needed = false;
        int         status;
        int         save_errno;
 
        /*
         * Reuse the already-open append descriptor for its segment (the
         * common single-segment case then costs no extra open/close).
         */
        path = cfs_cfp_segment_path(cfs, segno);
        if (segno == cfs->cfp_append_segno && cfs->cfp_fd >= 0)
        {
            fd = cfs->cfp_fd;
        }
        else
        {
            fd = BasicOpenFile(path, O_RDWR | PG_BINARY);
            if (fd < 0)
            {
                save_errno = errno;
                pfree(path);
                if (save_errno == ENOENT && segno > 0)
                    break;      /* end of the segment chain */
                errno = save_errno;
                ereport(data_sync_elevel(ERROR),
                        (errcode_for_file_access(),
                         errmsg("CFS: could not open .cfp segment %u of \"%s\" for fsync: %m",
                                segno, cfs->cfp_path)));
                return CFS_STORAGE_ERROR;
            }
            close_needed = true;
        }
 
        pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC);
 
        /*
         * Honor the cfs_debug_fail_fsync fault injection exactly like
         * cfs_fsync_kind() does for the single-file kinds.
         */
        if (cfs_debug_fail_fsync > 0)
        {
            cfs_debug_fail_fsync--;
            errno = EIO;
            status = -1;
        }
        else
            status = pg_fsync(fd);
        save_errno = errno;
        if (close_needed)
            close(fd);
        pgstat_report_wait_end();
 
        if (status != 0)
        {
            errno = save_errno;
            ereport(data_sync_elevel(ERROR),
                    (errcode_for_file_access(),
                     errmsg("CFS: fsync of %s failed: %m", path)));
            pfree(path);
            return CFS_STORAGE_ERROR;
        }
        pfree(path);
    }
    return CFS_STORAGE_OK;
}