/*------------------------------------------------------------------------- * * 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 */