Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/*-------------------------------------------------------------------------
 *
 * cfs_stats.h
 *    Per-relation CFS statistics API (see cfs_stats.c): counters, the
 *    snapshot/enumeration accessors and the pg_cfs_stats statsfile.  A
 *    leaf module — nothing here calls back into the shmem or storage
 *    layers.
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 2026, Diasoft
 *
 * src/include/storage/cfs/cfs_stats.h
 *
 *-------------------------------------------------------------------------
 */
 
#ifndef CFS_STATS_H
#define CFS_STATS_H
 
#include "postgres.h"
 
#include "port/atomics.h"
#include "storage/cfs/cfs.h"
#include "storage/relfilelocator.h"
 
/*
 * Statistics slots per partition: the default and the bounds of the
 * cfs_stats_slots_per_partition GUC (an int, PGC_POSTMASTER).  The total
 * number of tracked CFS relations is CFS_MAP_CACHE_NUM_PARTITIONS times
 * the value; a working set beyond the capacity is served by the statistics
 * LRU (evicted relations restart their counters from zero).
 */
#define CFS_STATS_SLOTS_PER_PART_DEFAULT    16
#define CFS_STATS_SLOTS_PER_PART_MIN        4
#define CFS_STATS_SLOTS_PER_PART_MAX        128
 
/*
 * CfsRelationStats — aggregated statistics for one CFS relation.
 *
 * The counters are pg_atomic_uint64: increments run under LW_SHARED of the
 * statistics partition lock (pg_atomic_fetch_add_u64), while creation,
 * eviction, reset and the wholesale publications after a fold or compaction
 * run under LW_EXCLUSIVE (pg_atomic_write_u64).  A snapshot therefore has
 * sequential consistency per counter but no cross-counter consistency —
 * the same approximation the core pgstat counters accept.  The slot pointer
 * stays valid for the whole shared-lock critical section because eviction
 * needs LW_EXCLUSIVE.
 *
 * The key (hash, rlocator, forknum), the timestamps (last_reset,
 * last_compaction) and the chain bookkeeping (chain_next) are plain fields,
 * written only under LW_EXCLUSIVE.  The LRU stamp (access_clock) is a plain
 * field written by cfs_stats_touch() while the partition lock is held in
 * EITHER mode: under LW_SHARED two backends may race the store, which can
 * lose one of the two ticks - benign, because the value only orders
 * eviction and is compared (for victim selection) under LW_EXCLUSIVE.
 *
 * Timestamps (last_reset, last_compaction) store the internal TimestampTz
 * representation (microseconds since 2000-01-01) as plain int64 so that this
 * header does not have to pull in the timestamp type machinery.
 */
typedef struct CfsRelationStats
{
    uint32      hash;           /* hash of the key; 0 == empty slot         */
    int32       chain_next;     /* index of the next slot in the partition's
                                 * hash chain; -1 = end of chain.  Only
                                 * meaningful while the slot is occupied
                                 * (see the chain invariants in
                                 * cfs_shmem_internal.h)                */
    RelFileLocatorBackend rlocator;
    ForkNumber  forknum;
    pg_atomic_uint64 logical_pages; /* highest logical size observed        */
    pg_atomic_uint64 compressed_bytes;  /* bytes written compressed         */
    pg_atomic_uint64 raw_bytes; /* bytes written uncompressed (RAW)         */
    pg_atomic_uint64 dead_bytes;    /* dead payload bytes; exact after the
                                     * next checkpoint recomputation        */
    pg_atomic_uint64 dead_pages;    /* superseded page versions folded by
                                     * checkpoints; accumulates between
                                     * compactions                      */
    pg_atomic_uint64 checkpoint_map_rows_written;   /* map rows checkpoints
                                                     * folded into the map  */
    pg_atomic_uint64 compressed_pages;  /* # of compressed pages written    */
    pg_atomic_uint64 uncompressed_pages; /* # of pages stored RAW (no gain) */
    pg_atomic_uint64 read_count;    /* number of page reads served          */
    pg_atomic_uint64 read_batch_count;  /* number of batched span preads    */
    pg_atomic_uint64 read_batched_pages;    /* pages served by batched span
                                             * reads                        */
    pg_atomic_uint64 read_fallback_pages;   /* pages served by the per-block
                                             * fallback path                */
    pg_atomic_uint64 write_count;   /* number of page writes performed      */
    pg_atomic_uint64 compress_count;    /* number of compress operations    */
    pg_atomic_uint64 decompress_count;  /* number of decompress operations  */
    pg_atomic_uint64 crc_failures;  /* number of integrity failures
                                     * detected                         */
    int64       last_reset;     /* TimestampTz of last stats reset          */
    int64       last_compaction;    /* TimestampTz of last successful
                                     * compaction */
    /*
     * Transient boot flag (QDB-1507 U1): shared memory only, never part
     * of CfsStatsSnapshot or the stats file (the file format must not
     * change).
     */
    bool        stale;          /* restored from the stats file at boot;
                                 * the dead_bytes value predates the last
                                 * crash and must be resynced from the
                                 * map before use                   */
    uint64      access_clock;   /* last touch, for LRU                      */
} CfsRelationStats;
 
/*
 * CfsStatsSnapshot — a consistent point-in-time copy of CfsRelationStats,
 * returned to callers that must not touch shared memory directly.
 */
typedef struct CfsStatsSnapshot
{
    bool        found;          /* relation had a stats entry               */
    uint64      logical_pages;
    uint64      compressed_bytes;
    uint64      raw_bytes;
    uint64      dead_bytes;
    uint64      dead_pages;
    uint64      checkpoint_map_rows_written;
    uint64      compressed_pages;
    uint64      uncompressed_pages;
    uint64      read_count;
    uint64      read_batch_count;
    uint64      read_batched_pages;
    uint64      read_fallback_pages;
    uint64      write_count;
    uint64      compress_count;
    uint64      decompress_count;
    uint64      crc_failures;
    int64       last_reset;
    int64       last_compaction;
} CfsStatsSnapshot;
 
/* Allocate the stats locks/slots (called from CfsShmemInit). */
extern void cfs_stats_shmem_init(void);
 
/*
 * cfs_stats_note_logical_pages — the logical-size high-water mark (only
 * grows).  'rel_hash' is the caller's cfs_cache_hash_rel() value.
 */
extern void cfs_stats_note_logical_pages(uint32 rel_hash,
                                         RelFileLocatorBackend rlocator,
                                         ForkNumber forknum, uint64 nblocks);
 
/* ================================================================
 * Statistics
 * ================================================================ */
 
extern void cfs_stats_count_read(RelFileLocatorBackend rlocator,
                                 ForkNumber forknum,
                                 uint64 compressed_bytes);
 
/*
 * Batched-read accounting (QDB-1513 evidence base): every successful span
 * pread of nentries records counts one batch; every block the batch wrapper
 * degrades to the per-block path counts as fallback.  Together with
 * read_count they preserve the invariant
 * read_count == read_batched_pages + read_fallback_pages for smgr reads.
 */
extern void cfs_stats_count_read_span(RelFileLocatorBackend rlocator,
                                      ForkNumber forknum,
                                      uint32 npages);
extern void cfs_stats_count_read_fallback(RelFileLocatorBackend rlocator,
                                          ForkNumber forknum,
                                          uint32 npages);
extern void cfs_stats_count_write(RelFileLocatorBackend rlocator,
                                  ForkNumber forknum,
                                  uint64 compressed_bytes, bool is_raw);
extern void cfs_stats_count_crc_failure(RelFileLocatorBackend rlocator,
                                        ForkNumber forknum);
 
 
 
/*
 * Publish the checkpoint's dead-space value: the previous baseline plus
 * this checkpoint's delta (the fold's superseded payloads, and the
 * payloads of the rows the truncating RESIZE drops - the checkpoint is
 * the one that truncates them off the map file, so it is the single
 * moment those rows are still readable), plus the dead-pages delta
 * accumulated by the fold's superseded-row accounting.  Compaction
 * publishes the exact recomputation the same way.
 */
extern void cfs_stats_set_dead(RelFileLocatorBackend rlocator,
                               ForkNumber forknum, uint64 dead_bytes,
                               uint64 dead_pages_add);
 
/*
 * Boot-time dead-space resync (QDB-1507 U1).
 *
 * cfs_stats_slot_stale returns true when the slot's dead_bytes was
 * restored from the stats file and still predates the last crash.  It
 * looks the slot up under the partition's shared lock and never
 * creates one.
 *
 * cfs_stats_resync_dead publishes a map-derived dead_bytes into a
 * stale slot (creating the slot when create_slot is set and none
 * exists) and clears the stale mark.  A slot whose owner has already
 * published an exact value (the checkpoint, a compaction) keeps that
 * value; the return value says whether this call published.
 *
 * cfs_stats_forget_stale_flags clears the stale mark of every
 * occupied slot: a clean shutdown's persisted values stay
 * authoritative, no map resync runs on a clean start.
 *
 * cfs_stats_boot_after_crash / cfs_stats_boot_sweep_pending /
 * cfs_stats_boot_sweep_done maintain the shared crash-boot marker
 * gating the background worker's single resync pass; the sweep
 * retires (and the persistent marker file is unlinked) only in
 * cfs_stats_boot_sweep_done.
 * cfs_stats_boot_restore_marker arms the sweep from the persistent
 * marker file at startup (presence detection only, no removal): a
 * clean shutdown that overtook the sweep wrote it, and the next
 * (clean) boot must keep the sweep armed instead of declaring the
 * unresynced values authoritative; removing the marker only when the
 * sweep completes keeps a boot interrupted before the sweep from
 * losing the obligation.
 */
extern bool cfs_stats_slot_stale(RelFileLocatorBackend rlocator,
                                 ForkNumber forknum);
extern bool cfs_stats_resync_dead(RelFileLocatorBackend rlocator,
                                  ForkNumber forknum, uint64 dead_bytes,
                                  bool create_slot);
extern void cfs_stats_forget_stale_flags(void);
extern void cfs_stats_boot_after_crash(void);
extern bool cfs_stats_boot_sweep_pending(void);
extern void cfs_stats_boot_sweep_done(void);
extern void cfs_stats_boot_restore_marker(void);
 
/*
 * Record a successful compaction: stamp the last-compaction time and reset
 * the dead-space counters, so they measure dead space since the last
 * compaction (or manual reset) rather than over the relation's lifetime.
 */
extern void cfs_stats_note_compaction(RelFileLocatorBackend rlocator,
                                      ForkNumber forknum, int64 ts);
 
/*
 * Account map rows that a checkpoint (or another full-snapshot writer)
 * wrote out for the relation.  The counter is the observability base for
 * the incremental checkpoint: with the fold in place it grows by exactly
 * the number of journal rows the checkpoint carried into the map - the
 * changed blocks - instead of the relation's full row count.
 */
extern void cfs_stats_count_checkpoint_rows(RelFileLocatorBackend rlocator,
                                            ForkNumber forknum,
                                            uint64 nrows);
 
/*
 * cfs_stats_for_each — invoke the callback for every relation that currently
 * has a statistics slot in shared memory.  Used by the pg_stat_cfs view.
 * The snapshot is taken under the per-partition lock before the callback is
 * invoked.  Returning false from the callback stops the iteration.
 */
typedef bool (*CfsStatsEnumCB) (RelFileLocatorBackend rlocator,
                                ForkNumber forknum,
                                const CfsStatsSnapshot *stats,
                                void *arg);
extern void cfs_stats_for_each(CfsStatsEnumCB cb, void *arg);
 
/*
 * Persist the per-relation statistics to PGDATA/pg_cfs_stats at a regular
 * shutdown (the checkpointer calls this from its before_shmem_exit hook,
 * the PG15 pgstat pattern) and restore them in the postmaster at startup.
 * A crash loses everything since the last regular shutdown -- the same
 * degradation vanilla pgstat accepts.
 */
extern void cfs_stats_write_statsfile(int code, Datum arg);
extern void cfs_stats_restore_statsfile(void);
 
/* Take a consistent snapshot of a relation's statistics. */
extern bool cfs_stats_snapshot(RelFileLocatorBackend rlocator,
                               ForkNumber forknum,
                               CfsStatsSnapshot *out);
 
/*
 * Reset a relation's statistics counters to zero.  When 'all' is true every
 * slot in every partition is reset (used by pg_cfs_reset_stats(NULL)).
 */
extern void cfs_stats_reset(RelFileLocatorBackend rlocator,
                            ForkNumber forknum);
extern void cfs_stats_reset_all(void);
 
#endif                          /* CFS_STATS_H */