Исходный код СУБД 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
/*-------------------------------------------------------------------------
 *
 * cfs_state.c
 *    Single ownership-state judge for the CFS sidecar pair.
 *
 * Every staleness/ownership signal CFS has is derived HERE:
 *
 *  - the .cfsmap inode behind the handle vs the one at the path
 *    (compaction swap, immedsync snapshot)  -> CFS_STATE_MAP_SWAPPED;
 *  - the journal header incarnation          -> CFS_STATE_JRN_RESET;
 *  - the journal file size vs a replay cursor-> SHRANK / GREW;
 *  - the journal inode/watermark/header
 *    validity as a whole                     -> CFS_STATE_JRN_IDENTITY_MOVED;
 *  - the shared-cache map generation         -> CFS_STATE_GEN_MOVED.
 *
 * Caller masks (what each site acts on — and everything it ever derived
 * on its own before this judge existed):
 *
 *  cfs_map_load (storage.c)        IDENTITY_MOVED|RESET|SHRANK|GREW:
 *                  retry the load once on the fresh files; MAP_SWAPPED
 *                  within the retry decides whether the map fd is
 *                  reopened first.
 *  cfs_map_needs_refresh (storage.c)   any journal flag: the map is not
 *                  in sync with the journal.
 *  cfs_refresh_map (storage.c)     STAT_FAILED -> ERROR; RESET or SHRANK
 *                  -> full reload; GREW -> delta replay; HEADER_STALE
 *                  alone -> the size comparison decides, exactly like
 *                  the unreadable-header fallback used to.
 *  cfs_shared_map_sync_segment (shmem.c)   STAT_FAILED or HEADER_STALE ->
 *                  give up; RESET or SHRANK -> re-baseline the segment;
 *                  GREW -> replay the delta below.
 *  cfs_checkpoint_fold_tail (checkpoint.c) STAT_FAILED first (the size is
 *                  unknowable: no boundary can be proven, the
 *                  reset must not run); MAP_SWAPPED, RESET,
 *                  GEN_MOVED or HEADER_STALE (in this order,
 *                  distinct DEBUG reports) -> not_ours;
 *                  HEADER_STALE covers only the window
 *                  "readable at the capture, unreadable by
 *                  the check" (capture-time damage is
 *                  phase 1's ERROR, never this skip).
 *
 * cfs_journal_tail_changed() keeps re-reading one record beyond the torn
 * offset: that is record content, not pair identity, and stays in
 * cfs_journal.c (the single documented exception to the "no race checks
 * outside cfs_state" review rule).
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 2026, Diasoft
 *
 * src/backend/storage/cfs/cfs_state.c
 *
 *-------------------------------------------------------------------------
 */
 
#include "postgres.h"
 
#include <sys/stat.h>
 
#include "storage/cfs/cfs_journal.h"
#include "storage/cfs/cfs_state.h"
#include "storage/cfs/cfs_storage.h"
#include "utils/injection_point.h"
 
/*
 * The shared-cache generation provider, installed by the relmeta layer at
 * shared-memory initialisation (see cfs_state.h).  NULL means "no
 * shared cache yet": every generation comparison then sees 0 == 0 and
 * reports no movement, which is correct before the cache exists.
 */
static CfsGenerationProvider cfs_generation_provider = NULL;
 
void
cfs_state_set_generation_provider(CfsGenerationProvider fn)
{
    cfs_generation_provider = fn;
}
 
uint64
cfs_state_relation_generation(RelFileLocatorBackend rlocator,
                              ForkNumber forknum)
{
    if (cfs_generation_provider == NULL)
        return 0;
    return cfs_generation_provider(rlocator, forknum);
}
 
/*
 * The online-compaction liveness provider (QDB-1514).  Installed by the
 * relmeta layer at shared-memory initialisation; NULL reports "no
 * compaction running", which is correct before the cache exists — no
 * backend can be compacting then.
 */
static CfsCompactionActiveProvider cfs_compaction_provider = NULL;
 
void
cfs_state_set_compaction_provider(CfsCompactionActiveProvider fn)
{
    cfs_compaction_provider = fn;
}
 
bool
cfs_state_compaction_active(RelFileLocatorBackend rlocator,
                            ForkNumber forknum)
{
    if (cfs_compaction_provider == NULL)
        return false;
    return cfs_compaction_provider(rlocator, forknum);
}
 
/*
 * The sidecar-open guard (QDB-1514): a shared hold of the append lock
 * around the lock-free sidecar opens, so a concurrent online compaction's
 * swap phase (exclusive) cannot interleave with the descriptor resolution
 * and the generation tagging.  Without a provider (before the shared
 * memory exists) there is nothing to serialize with: startup is
 * single-threaded.
 */
static const CfsOpenGuardOps *cfs_open_guard_ops = NULL;
 
void
cfs_state_set_open_guard_ops(const CfsOpenGuardOps *ops)
{
    cfs_open_guard_ops = ops;
}
 
bool
cfs_state_open_guard_acquire(RelFileLocatorBackend rlocator,
                             ForkNumber forknum)
{
    if (cfs_open_guard_ops == NULL ||
        cfs_open_guard_ops->open_guard_acquire == NULL)
        return false;
    return cfs_open_guard_ops->open_guard_acquire(rlocator, forknum);
}
 
void
cfs_state_open_guard_release(RelFileLocatorBackend rlocator,
                             ForkNumber forknum, bool after_error)
{
    if (cfs_open_guard_ops == NULL ||
        cfs_open_guard_ops->open_guard_release == NULL)
        return;
    cfs_open_guard_ops->open_guard_release(rlocator, forknum, after_error);
}
 
/*
 * The authoritative .cfp tail provider (the D1 write-path protocol, see
 * cfs_shmem.h).  Installed by the relmeta layer at shared-memory
 * initialisation; NULL keeps every operation at the historical
 * discover-on-every-append behaviour, which is correct for callers that
 * run before the cache exists or without a metadata slot.
 */
static CfsCfpTailOps cfs_cfp_tail_ops;
 
void
cfs_state_set_cfp_tail_ops(const CfsCfpTailOps *ops)
{
    cfs_cfp_tail_ops = *ops;
}
 
bool
cfs_state_cfp_tail_fetch(RelFileLocatorBackend rlocator, ForkNumber forknum,
                         uint64 *out_tail)
{
    if (cfs_cfp_tail_ops.tail_fetch == NULL)
        return false;
    return cfs_cfp_tail_ops.tail_fetch(rlocator, forknum, out_tail);
}
 
void
cfs_state_cfp_tail_begin(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    if (cfs_cfp_tail_ops.tail_begin != NULL)
        cfs_cfp_tail_ops.tail_begin(rlocator, forknum);
}
 
void
cfs_state_cfp_tail_commit(RelFileLocatorBackend rlocator, ForkNumber forknum,
                          uint64 new_tail)
{
    if (cfs_cfp_tail_ops.tail_commit != NULL)
        cfs_cfp_tail_ops.tail_commit(rlocator, forknum, new_tail);
}
 
void
cfs_state_cfp_tail_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    if (cfs_cfp_tail_ops.tail_dirty != NULL)
        cfs_cfp_tail_ops.tail_dirty(rlocator, forknum);
}
 
/*
 * Read the journal header twice, the way the two original callers did:
 * the fully validated read backs the identity comparison (map_load reads
 * the journal lock-free and must treat a mid-reset torn header as "no
 * usable identity"), while the raw-fields read with the handle fallback
 * is what the under-lock incarnation check compared (checkpoint phase 1/2).
 */
static uint16
cfs_state_incarnation_stamped(CfsRelation *cfs)
{
    CfsJournalFileHeader jhdr;
 
    if (cfs_journal_read_header_fields(cfs->jrn_fd, &jhdr))
        return jhdr.incarnation;
    return cfs->jrn_incarnation;
}
 
void
cfs_state_capture(CfsRelation *cfs, CfsStateSnapshot *snap)
{
    struct stat st;
    CfsJournalFileHeader jhdr;
 
    memset(snap, 0, sizeof(*snap));
 
    snap->map_fd_valid = cfs->map_fd >= 0 && fstat(cfs->map_fd, &st) == 0;
    if (snap->map_fd_valid)
    {
        snap->map_dev = st.st_dev;
        snap->map_ino = st.st_ino;
    }
 
    /*
     * Test seam: simulate the fstat failure so the suite can prove the
     * checkpoint refuses to fold and reset against an unknown journal size
     * (the N2 review contract).  No-op in production.
     */
    if (IS_INJECTION_POINT_ATTACHED("cfs-fail-jrn-fstat"))
        snap->jrn_fd_valid = false;
    else
        snap->jrn_fd_valid = cfs->jrn_fd >= 0 && fstat(cfs->jrn_fd, &st) == 0;
    if (snap->jrn_fd_valid)
    {
        snap->jrn_dev = st.st_dev;
        snap->jrn_ino = st.st_ino;
        snap->jrn_size = st.st_size;
    }
 
    /*
     * Identity fields with the cfs_journal_identity() fallback: an unreadable
     * header keeps dev/ino/size as the identity and zeroes the header-carried
     * fields, so comparing two snapshots stays conservative.
     */
    snap->jrn_header_valid = cfs_journal_read_header(cfs->jrn_fd, &jhdr);
    if (snap->jrn_header_valid)
    {
        snap->jrn_incarnation = jhdr.incarnation;
        snap->jrn_watermark = jhdr.max_generation;
    }
 
    /* The under-lock incarnation baseline (see the comment above). */
    snap->jrn_incarnation_stamped = cfs_state_incarnation_stamped(cfs);
 
    snap->map_generation =
        cfs_state_relation_generation(cfs->rlocator, cfs->forknum);
}
 
/*
 * The journal half of the judge, shared by both entry points.  Returns
 * flags and, on request, the freshly read (fully validated) header.
 *
 * 'base_hdr_valid' narrows HEADER_STALE to the window the checkpoint's
 * skip arm describes: the header was readable at the base capture and
 * became unreadable since.  Header damage already present at the capture
 * is not staleness (the checkpoint's phase 1 rejects it before this
 * verdict can run), and the descriptor consumers pass true: they hold no
 * header-validity base, so every currently unreadable header stays a
 * movement signal for them.
 */
static int
cfs_state_journal_flags(CfsRelation *cfs,
                        const CfsJournalFileHeader *now_hdr, bool have_hdr,
                        bool base_hdr_valid, off_t now_size, off_t cursor_off,
                        CfsJournalFileHeader *fresh_jhdr)
{
    int         fl = 0;
 
    if (fresh_jhdr != NULL && have_hdr)
        *fresh_jhdr = *now_hdr;
 
    if (!have_hdr && base_hdr_valid)
        fl |= CFS_STATE_JRN_HEADER_STALE;
 
    if (now_size < cursor_off)
        fl |= CFS_STATE_JRN_SHRANK;
    else if (now_size > cursor_off)
        fl |= CFS_STATE_JRN_GREW;
 
    return fl;
}
 
int
cfs_state_check(const CfsStateSnapshot *base, CfsRelation *cfs,
                off_t cursor_off, CfsJournalFileHeader *fresh_jhdr)
{
    struct stat st;
    CfsJournalFileHeader jhdr;
    bool        have_hdr;
    int         fl;
 
    /* --- journal identity and staleness --- */
    if (cfs->jrn_fd < 0 || fstat(cfs->jrn_fd, &st) != 0)
        return CFS_STATE_JRN_STAT_FAILED;
 
    have_hdr = cfs_journal_read_header(cfs->jrn_fd, &jhdr);
    fl = cfs_state_journal_flags(cfs, &jhdr, have_hdr,
                                 base->jrn_header_valid, st.st_size,
                                 cursor_off, fresh_jhdr);
 
    if (base->jrn_fd_valid &&
        (st.st_dev != base->jrn_dev || st.st_ino != base->jrn_ino ||
         st.st_size != base->jrn_size))
        fl |= CFS_STATE_JRN_IDENTITY_MOVED;
 
    /*
     * The identity comparison of the old cfs_journal_identity_equal():
     * header-carried fields join in with the zero fallback, so a header that
     * became (un)readable while the inode stayed counts as a change.
     */
    if (have_hdr != base->jrn_header_valid ||
        (have_hdr && (jhdr.incarnation != base->jrn_incarnation ||
                      jhdr.max_generation != base->jrn_watermark)))
        fl |= CFS_STATE_JRN_IDENTITY_MOVED;
 
    /* The under-lock incarnation check (checkpoint phase 1 -> phase 2). */
    if (cfs_state_incarnation_stamped(cfs) != base->jrn_incarnation_stamped)
        fl |= CFS_STATE_JRN_RESET;
 
    /* --- map swap --- */
    if (cfs_map_file_swapped(cfs))
        fl |= CFS_STATE_MAP_SWAPPED;
 
    /* --- shared generation --- */
    if (cfs_state_relation_generation(cfs->rlocator, cfs->forknum) !=
        base->map_generation)
        fl |= CFS_STATE_GEN_MOVED;
 
    return fl;
}
 
int
cfs_state_journal_moved(CfsRelation *cfs, uint16 base_incarnation,
                        off_t cursor_off, CfsJournalFileHeader *fresh_jhdr)
{
    struct stat st;
    CfsJournalFileHeader jhdr;
    bool        have_hdr;
    int         fl;
 
    if (cfs->jrn_fd < 0 || fstat(cfs->jrn_fd, &st) != 0)
        return CFS_STATE_JRN_STAT_FAILED;
 
    have_hdr = cfs_journal_read_header(cfs->jrn_fd, &jhdr);
    fl = cfs_state_journal_flags(cfs, &jhdr, have_hdr, true, st.st_size,
                                 cursor_off, fresh_jhdr);
 
    if (have_hdr && jhdr.incarnation != base_incarnation)
        fl |= CFS_STATE_JRN_RESET;
 
    return fl;
}
 
/*
 * Moved verbatim from cfs_storage.c: the map-side half of the judge.
 * A missing path keeps the old descriptor semantics (not a swap).
 */
bool
cfs_map_file_swapped(CfsRelation *cfs)
{
    struct stat st_fd;
    struct stat st_path;
 
    if (cfs->map_fd < 0)
        return true;
    if (fstat(cfs->map_fd, &st_fd) != 0)
        return true;
    if (stat(cfs->map_path, &st_path) != 0)
        return false;           /* path missing: keep the old fd semantics */
    return st_fd.st_ino != st_path.st_ino || st_fd.st_dev != st_path.st_dev;
}