/*------------------------------------------------------------------------- * cfs_bgworker.c * Compressed File Store (CFS) — background compaction worker. * * CfsBgWorker is the launcher of the CFS background compaction, started by * the postmaster after recovery finishes. Every cfs_bg_period_ms it * enumerates the databases of the cluster and, one at a time, starts a * short-lived per-database worker (CfsBgWorkerDbMain) that scans pg_class * of its database for CFS relations whose dead-space ratio exceeds * cfs_bg_threshold and compacts their sidecar files (.cfp / .cfsmap) by * copying the live records into fresh temporary files, fsync'ing them and * atomically renaming them into place (the durable-swap protocol). The * same algorithm is available synchronously through the SQL function * pg_cfs_compact(regclass). * * Key properties: * * Every database of the cluster is visited, not only "postgres": the * launcher itself is database-less (like the autovacuum launcher) and * a background worker cannot re-connect to another database, so each * database is serviced by an ephemeral per-database worker. * * A database that disappears between the enumeration and the worker's * connection attempt kills only that ephemeral worker, never the * launcher; the remaining databases keep being processed. * * Only one per-database worker runs at a time. * * Compaction of one relation holds ShareUpdateExclusiveLock (the VACUUM * lock level: readers and writers keep running, DDL and maintenance * conflict) for the whole call; the background path acquires it with a * timeout (cfs_bg_respond_time_s), on timeout the candidate is skipped * silently. With cfs_compact_online on (the default), only the short * catch-up and swap phases inside cfs_compact_relation() * additionally hold the per-relation append lock; with it off, the * append lock is simply held for the whole operation, serializing * all sidecar appends until compaction finishes (readers keep * running under the ShareUpdateExclusiveLock level taken above). * * relfilenode is never changed; no WAL is generated. * * After a successful swap the relcache is invalidated and the new files * are registered as dirty for the next checkpoint. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/postmaster/cfs_bgworker.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/heapam.h" #include "access/relation.h" #include "access/table.h" #include "access/xlog.h" #include "catalog/pg_class.h" #include "catalog/pg_database.h" #include "catalog/pg_tablespace_d.h" #include "catalog/pg_type.h" #include "miscadmin.h" #include "nodes/pg_list.h" #include "pgstat.h" #include "postmaster/bgworker.h" #include "postmaster/cfs_bgworker.h" #include "postmaster/interrupt.h" #include "storage/bufmgr.h" #include "storage/ipc.h" #include "storage/latch.h" #include "storage/lmgr.h" #include "storage/proc.h" #include "storage/smgr.h" #include "tcop/tcopprot.h" #include "utils/acl.h" #include "utils/builtins.h" #include "utils/fmgroids.h" #include "utils/inval.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/rel.h" #include "utils/snapmgr.h" #include "utils/syscache.h" /* * CFS-specific headers are only available when the feature is enabled. * The SQL function pg_cfs_compact() is always compiled (it has a stub * for the !USE_CFS case), but the background worker and compaction logic * require the full CFS subsystem. */ #ifdef USE_CFS #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_compact.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_path.h" #include "storage/cfs/cfs_shmem.h" #include "storage/cfs/cfs_smgr.h" #include "storage/cfs/cfs_storage.h" #include "utils/wait_event.h" #endif /* * All CFS-specific code (GUC variables, compaction logic, background worker) * is compiled only when the feature is enabled. The SQL function * pg_cfs_compact() below is always compiled — it has a stub for the * !USE_CFS case. */ #ifdef USE_CFS /* ================================================================ * GUC parameters — defined in cfs_guc.c, declared in cfs_guc.h. * ================================================================ */ /* ================================================================ * Core compaction routine — shared by SQL function and bgworker. * * The last-compaction history used by the cfs_bg_min_interval_s throttle * lives in shared memory (cfs_shmem.c), so that the short-lived * per-database workers share one cluster-wide ring. * ================================================================ */ /* * CfsCompactRelationByOid — compact one CFS relation. * * 'is_automatic' is true when called from the background worker (uses a * conditional lock with timeout) and false when called from the SQL function * pg_cfs_compact() (uses a blocking lock). * * Returns true on success, false if the relation is not CFS or the lock * could not be acquired (automatic mode only). Errors on I/O failure. */ bool CfsCompactRelationByOid(Oid reloid, bool is_automatic, CfsCompactResult *out_result) { Relation rel; RelFileLocatorBackend rlocator; CfsCompactResult result; CfsCompactOptions opts = CFS_COMPACT_OPTIONS_DEFAULT; bool got_lock = false; /* * The compaction swaps the .cfp/.cfsmap pair wholesale, invalidating * every physical offset. A base backup (or pg_rewind) that is * concurrently copying the sidecar files would assemble a mismatched trio * that no WAL replay can repair, so compaction is refused while a * non-exclusive backup is in progress. cfs_compact_relation() re-checks * this right before the swap commit point. */ if (BackupInProgress()) { if (is_automatic) { ereport(DEBUG1, (errmsg("CFS bgworker: backup in progress, skipping compaction of relation %u", reloid))); return false; } ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("cannot compact CFS relation while a base backup is in progress"), errhint("Retry the compaction after the backup has finished."))); } if (is_automatic) { /* * Try to acquire ShareUpdateExclusiveLock with a timeout. The timeout * is cfs_bg_respond_time_s seconds; we poll every 200 ms. The lock * level is VACUUM's: it conflicts only with DDL and other * maintenance (VACUUM, CLUSTER, a second compaction), never with * ordinary reads and writes — so an actively used relation is a * compactable candidate, unlike the historical, stronger lock * level where it could only ever be skipped (QDB-1514). * * The tick is a latch wait, like every daemon-scale wait in vanilla * (see the autovacuum launcher nap): a signal reaches us at once and * the wait is visible in pg_stat_activity as CfsBgworkerLock. A * plain pg_usleep would be invisible and silently lose its remainder * on any signal (see the CAUTION in pgsleep.c). * * The elapsed time is measured against the wall clock, like * ConditionVariableTimedSleep(): a signal or barrier that wakes the * latch early shortens the tick, and counting that tick as a full * step would silently shrink the response window below * cfs_bg_respond_time_s. */ int step_ms = 200; int timeout_ms = cfs_bg_respond_time_s * 1000; instr_time start_time; instr_time cur_time; INSTR_TIME_SET_CURRENT(start_time); while (!got_lock) { int elapsed_ms; int wait_ms; INSTR_TIME_SET_CURRENT(cur_time); INSTR_TIME_SUBTRACT(cur_time, start_time); elapsed_ms = (int) INSTR_TIME_GET_MILLISEC(cur_time); if (elapsed_ms >= timeout_ms) break; ResetLatch(MyLatch); if (ConditionalLockRelationOid(reloid, ShareUpdateExclusiveLock)) { got_lock = true; break; } wait_ms = Min(step_ms, timeout_ms - elapsed_ms); (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, wait_ms, WAIT_EVENT_CFS_BGWORKER_LOCK); /* * Handle whatever woke us: shutdown aborts with the * administrator-command FATAL (SIGTERM is handled by die(), like * in the autovacuum worker), a procsignal barrier is absorbed in * place by ProcessInterrupts() and the polling continues, a * config reload just shortens this one tick. */ CHECK_FOR_INTERRUPTS(); } if (!got_lock) { ereport(DEBUG1, (errmsg("CFS bgworker: could not acquire lock on relation %u, skipping", reloid))); return false; } } else { LockRelationOid(reloid, ShareUpdateExclusiveLock); got_lock = true; } /* * The signal may have arrived while the lock was being acquired: check * for interrupts before starting the compaction proper, so that a pending * shutdown does not begin a new copy loop (the autovacuum * CHECK_FOR_INTERRUPTS discipline). */ CHECK_FOR_INTERRUPTS(); rel = relation_open(reloid, NoLock); /* Verify this is a relation with physical storage. */ if (!RelationIsValid(rel) || !RELKIND_HAS_STORAGE(rel->rd_rel->relkind)) { relation_close(rel, NoLock); if (got_lock) UnlockRelationOid(reloid, ShareUpdateExclusiveLock); if (is_automatic) ereport(DEBUG1, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("relation %u is not a stored relation, skipping", reloid))); else ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("relation %u is not a stored relation", reloid))); return false; } { bool uses_cfs; RelFileLocatorBackend rel_rlocator; rel_rlocator.locator = rel->rd_locator; rel_rlocator.backend = rel->rd_backend; uses_cfs = RelFileLocatorUsesCfs(rel_rlocator, MAIN_FORKNUM); if (!uses_cfs) { relation_close(rel, NoLock); if (got_lock) UnlockRelationOid(reloid, ShareUpdateExclusiveLock); if (is_automatic) ereport(DEBUG1, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("relation \"%s\" does not use CFS compression, skipping", RelationGetRelationName(rel)))); else ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("relation \"%s\" does not use CFS compression", RelationGetRelationName(rel)))); return false; } } /* * The compaction primitives operate on a bare RelFileLocatorBackend, so * we copy it from the relation's smgr handle. */ rlocator = RelationGetSmgr(rel)->smgr_rlocator; ereport(LOG, (errmsg("CFS: compacting relation \"%s\" (oid=%u)", RelationGetRelationName(rel), reloid))); /* * Flush every dirty buffer of this relation through the normal smgr write * path before the compaction rebuilds the sidecar files. The lock level * does not stop the checkpointer / bgwriter from flushing dirty buffers * (nor does it stop foreground writes), and in the online mode that is * fine by design: whatever is flushed or written during the copy is * appended to the old chain, journaled, and carried over by the * catch-up phase under the append lock. The flush is a density * optimization — the copied pair then includes the flushed versions and * does not carry them as dead weight (the CLUSTER / VACUUM FULL pattern). */ FlushRelationBuffers(rel); /* * Close the relation (keeping the lock) before calling * cfs_compact_relation(), because it opens and closes the sidecar files * itself. The ShareUpdateExclusiveLock we hold keeps DDL and competing * maintenance (a second compaction, VACUUM FULL) out for the whole * operation; concurrent readers and writers are the append lock's and * the ownership mark's business inside cfs_compact_relation(). */ relation_close(rel, NoLock); if (cfs_compact_relation(rlocator, MAIN_FORKNUM, &opts, &result, reloid) != CFS_STORAGE_OK) { if (got_lock) UnlockRelationOid(reloid, ShareUpdateExclusiveLock); ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: compaction failed for relation %u", reloid))); } /* * The sidecar files (.cfp and .cfsmap) have just been atomically replaced * with freshly compacted copies whose map entries contain *different* * physical offsets. Every backend that has a cached CfsRelation handle * for this relation still holds the *old* in-memory map and the *old* * file descriptors — reading through them would decompress garbage from * the new .cfp at the old offsets. * * We must therefore: 1. flush the shared-memory map cache (stale * per-block entries; done inside cfs_compact_relation() under the append * lock, together with the map generation bump); 2. broadcast an * smgr-level invalidation so that every other backend calls * smgrreleaserellocator() and drops its cached CfsRelation; 3. drop our * own backend's cached SMgrRelation + CfsRelation handle so that the next * access re-opens the new sidecars from disk. * * smgrreleaserellocator() operates on this backend's own SMgrRelationHash * (the smgr cache is per-process), so the earlier relation_close() plus * this call are simply idempotent: there is no cross-backend race. */ CacheInvalidateSmgr(rlocator); smgrreleaserellocator(rlocator); /* * Invalidate the relcache so that backends re-open the (now compacted) * sidecar files. This reuses the standard relcache invalidation path * employed by VACUUM FULL / CLUSTER. */ CacheInvalidateRelcacheByRelid(reloid); /* * Register the new .cfp and .cfsmap and the reset .cfsjrn as dirty so the * next checkpoint fsyncs them (the compaction already fsync'd all three * directly; this is the belt-and-braces registration through the standard * sync queue). */ cfs_register_dirty_file(rlocator, MAIN_FORKNUM, CFS_FILE_DATA); cfs_register_dirty_file(rlocator, MAIN_FORKNUM, CFS_FILE_MAP); cfs_register_dirty_file(rlocator, MAIN_FORKNUM, CFS_FILE_JOURNAL); /* * Record the compaction timestamp (the dead counters are reset inside * cfs_compact_relation(), under the append lock with the swap). */ cfs_bg_history_set(reloid, GetCurrentTimestamp()); if (got_lock) UnlockRelationOid(reloid, ShareUpdateExclusiveLock); if (out_result != NULL) *out_result = result; ereport(LOG, (errmsg("CFS: compaction complete for relation %u: %llu live, %llu dead, " "cfp %llu -> %llu bytes, reclaimed %llu", reloid, (unsigned long long) result.live_blocks, (unsigned long long) result.dead_blocks, (unsigned long long) result.old_cfp_size, (unsigned long long) result.new_cfp_size, (unsigned long long) result.reclaimed_bytes))); return true; } #endif /* USE_CFS */ /* ================================================================ * SQL function: pg_cfs_compact(regclass) * * Always compiled — returns an error when CFS is not enabled. * ================================================================ */ /* * pg_cfs_compact — synchronously compact one CFS relation. * Takes ShareUpdateExclusiveLock on the relation. * Returns a human-readable summary of the compaction result. */ Datum pg_cfs_compact(PG_FUNCTION_ARGS) { #ifdef USE_CFS Oid reloid = PG_GETARG_OID(0); CfsCompactResult result; char buf[256]; /* * Compaction takes ShareUpdateExclusiveLock on the relation, so only * its owner (or a superuser) may force it — the same permission model * as VACUUM FULL / CLUSTER. This matters when an administrator grants * EXECUTE on pg_cfs_compact to a non-superuser role. */ if (!object_ownercheck(RelationRelationId, reloid, GetUserId())) aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(reloid)), get_rel_name(reloid)); CfsCompactRelationByOid(reloid, false, &result); snprintf(buf, sizeof(buf), "compacted: %llu live blocks, %llu dead blocks, " "cfp %llu -> %llu bytes, reclaimed %llu", (unsigned long long) result.live_blocks, (unsigned long long) result.dead_blocks, (unsigned long long) result.old_cfp_size, (unsigned long long) result.new_cfp_size, (unsigned long long) result.reclaimed_bytes); PG_RETURN_TEXT_P(cstring_to_text(buf)); #else ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("unsupported CFS feature"), errdetail("This functionality requires the server to be built with cfs support."))); PG_RETURN_NULL(); #endif } /* * Background worker — compiled only when CFS is enabled. */ #ifdef USE_CFS /* ================================================================ * Background worker * ================================================================ */ /* * cfs_bg_scan_one — callback for scanning pg_class for CFS relations. * Compiles a candidate list ordered by dead-space ratio. */ typedef struct CfsBgCandidate { Oid relid; uint64 dead_bytes; } CfsBgCandidate; typedef struct CfsBgScanState { CfsBgCandidate candidates[256]; int n_candidates; } CfsBgScanState; /* * cfs_bg_resync_dead - recompute one relation's dead-space counter * from its sidecar files after a crash boot (QDB-1507 U1). * * A full cfs_open (no lazy flag) loads the map with the journal * replayed into it, so the valid map rows describe exactly the live * records: their CFS_RECORD_SIZE payloads summed are the live bytes, * and the segmented .cfp chain size minus that total is the dead * space. The sweep is a pure reader and takes no append lock: it * opens read-only and without CFS_OPEN_REPAIR_TAIL. A persistent * torn journal tail was already repaired by the startup scan * (CfsRecoveryInit runs before any backend), and the only torn tail a * sweep can observe is a concurrent writer's half-written record, * which the tail-repair contract (cfs_storage.c, the gate of the * cfs_map_load truncation) forbids truncating outside the recovery * scan or the append lock; a read-only handle cannot write anything * anyway - every ensure/repair step of cfs_open_paths is skipped for * read-only handles. A compaction that swaps the sidecars mid-load * is resolved by cfs_map_load's own ownership-state retry (the * journal identity / map swap re-read), and the conditional * publication of cfs_stats_resync_dead keeps a newer owner's exact * value (a checkpoint's or a compaction's) from being regressed. * The caller wraps the call in PG_TRY / PG_CATCH (an open failure * only skips the relation); the handle is closed here on every path * that returns. */ static bool cfs_bg_resync_dead(RelFileLocatorBackend rlocator) { CfsRelation *cfs; uint64 live_bytes = 0; uint64 dead; uint64 i; int64 cfp_size; cfs = cfs_open(rlocator, MAIN_FORKNUM, CFS_OPEN_RDONLY); if (cfs == NULL) return false; for (i = 0; i < cfs->map_hdr.nblocks; i++) { CfsMapEntry *entry = &cfs->map[i]; if (CFS_MAP_ENTRY_VALID(entry)) live_bytes += CFS_RECORD_SIZE(entry->compressed_size); } cfp_size = cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM, CFS_FILE_DATA); /* * Conservative upper bound: the chain lead-in and inter-segment * padding count as dead, which matches what compaction can actually * reclaim. */ dead = (cfp_size > 0 && (uint64) cfp_size > live_bytes) ? (uint64) cfp_size - live_bytes : 0; cfs_close(cfs); return cfs_stats_resync_dead(rlocator, MAIN_FORKNUM, dead, true); } static void cfs_bg_collect_candidates(CfsBgScanState *state) { Relation rel; TableScanDesc scan; HeapTuple tuple; Snapshot snapshot; state->n_candidates = 0; rel = table_open(RelationRelationId, AccessShareLock); snapshot = RegisterSnapshot(GetTransactionSnapshot()); scan = table_beginscan(rel, snapshot, 0, NULL, 0); while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) { Form_pg_class classform = (Form_pg_class) GETSTRUCT(tuple); Oid reloid = classform->oid; RelFileLocatorBackend rlocator; CfsStatsSnapshot stats; /* Only consider relations with physical storage. */ if (!RELKIND_HAS_STORAGE(classform->relkind)) continue; /* Skip partitioned tables — they have no physical data. */ if (classform->relkind == RELKIND_PARTITIONED_TABLE) continue; /* * Skip shared relations — they live in the global tablespace with * dbOid = 0 and are never CFS candidates. Trying to build a * per-database rlocator for them would Assert-fail in * GetRelationPath(). */ if (classform->relisshared) continue; /* Build the rlocator for this relation. */ rlocator.locator.spcOid = classform->reltablespace ? classform->reltablespace : MyDatabaseTableSpace; /* * Shared relations live in the global tablespace with dbOid = 0; all * other relations belong to the current database. Mixing these up * causes GetRelationPath() to Assert-fail. */ if (rlocator.locator.spcOid == GLOBALTABLESPACE_OID) rlocator.locator.dbOid = InvalidOid; else rlocator.locator.dbOid = MyDatabaseId; rlocator.locator.relNumber = classform->relfilenode; rlocator.backend = INVALID_PROC_NUMBER; /* Skip non-CFS relations. */ if (!RelFileLocatorUsesCfs(rlocator, MAIN_FORKNUM)) continue; /* * Read the statistics (dead_bytes) without skipping a missing * entry yet: on the first pass after a crash restart the * restored dead_bytes predates the crash (the stats file is * written only at a clean shutdown), so the counter is resynced * from the relation's own map before any threshold decision - * including relations that have no entry in the file at all * (QDB-1507 U1). A resync failure only skips the relation: the * error is logged and the relation is left to the checkpoint's * map-based base. */ cfs_stats_snapshot(rlocator, MAIN_FORKNUM, &stats); if (cfs_stats_boot_sweep_pending() && (!stats.found || cfs_stats_slot_stale(rlocator, MAIN_FORKNUM))) { bool resynced; PG_TRY(); { resynced = cfs_bg_resync_dead(rlocator); } PG_CATCH(); { /* * Log the original error the way the per-candidate * isolation below does, then drop it: the transaction * was never aborted (the error never escaped to the * main loop), so the scan simply continues - aborting * here would destroy the open scan's registered * snapshot. CHECK_FOR_INTERRUPTS afterwards turns a * termination request that surfaced as the caught * error into the standard worker FATAL instead of * swallowing it. */ EmitErrorReport(); FlushErrorState(); CHECK_FOR_INTERRUPTS(); ereport(LOG, (errmsg("CFS: bgworker could not resync dead-space " "counters for %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); resynced = false; } PG_END_TRY(); if (!resynced) continue; /* retry healed by checkpoint or next boot */ if (!cfs_stats_snapshot(rlocator, MAIN_FORKNUM, &stats)) continue; } if (!stats.found) continue; /* Check the threshold. */ if (stats.dead_bytes == 0) continue; /* * Vanilla-shaped ratio: the numerator is the dead space since the * last compaction (cfs_stats_note_compaction resets it), the * denominator is the LIVE payload of the chain -- exactly how * autovacuum divides the dead-tuple count by the live tuples, never * by "everything ever inserted" (QDB-1492) and not even by the * current total size: dead bytes in the denominator would dampen * their own ratio, and a relation whose dead share kept growing * would approach the threshold ever more slowly (QDB-1514). */ { int64 cfp_size = cfs_segmented_sidecar_size(rlocator, MAIN_FORKNUM, CFS_FILE_DATA); uint64 live_bytes; if (cfp_size <= 0) continue; /* * Clamp at one byte: fully dead space is a candidate at any * threshold. */ live_bytes = ((uint64) cfp_size > stats.dead_bytes) ? (uint64) cfp_size - stats.dead_bytes : 1; /* * dead_bytes * 100 overflows only beyond 2^57.6 bytes (184 PiB) * of dead space in a single relation -- unreachable today, but * the arithmetic must not wrap into a wrong verdict, so saturate: * that much dead space makes the relation a candidate at any * threshold. ponytail: below the bound the comparison is exact; * an exact 128-bit cross-product compare for the unreachable * regime is not worth a helper. */ if (stats.dead_bytes <= UINT64_MAX / 100 && stats.dead_bytes * 100 / live_bytes < (uint64) cfs_bg_threshold_percent) continue; } /* Respect the minimum interval between compactions. */ { TimestampTz last = cfs_bg_history_get(reloid); TimestampTz now = GetCurrentTimestamp(); if (last > 0 && TimestampDifferenceMilliseconds(last, now) < (int64) cfs_bg_min_interval_s * 1000) continue; } if (state->n_candidates < 256) { state->candidates[state->n_candidates].relid = reloid; state->candidates[state->n_candidates].dead_bytes = stats.dead_bytes; state->n_candidates++; } } table_endscan(scan); UnregisterSnapshot(snapshot); table_close(rel, AccessShareLock); } static int cfs_bg_candidate_cmp(const void *a, const void *b) { const CfsBgCandidate *ca = (const CfsBgCandidate *) a; const CfsBgCandidate *cb = (const CfsBgCandidate *) b; if (ca->dead_bytes < cb->dead_bytes) return 1; if (ca->dead_bytes > cb->dead_bytes) return -1; return 0; } /* * One entry of the launcher's per-cycle database list. */ typedef struct CfsBgDatabase { Oid dboid; char *dbname; } CfsBgDatabase; /* * cfs_bg_get_database_list — return the list of databases the launcher * should service, modeled on get_database_list() in autovacuum.c. * * The launcher is connected to no database, but a DB-less process can * still run transactions that see the shared catalogs; a seqscan of * pg_database is exactly what the autovacuum launcher does here. The * caller owns the transaction; the results are allocated in 'resultcxt' * so that they survive its commit. */ static List * cfs_bg_get_database_list(MemoryContext resultcxt) { List *dblist = NIL; Relation rel; TableScanDesc scan; HeapTuple tup; rel = table_open(DatabaseRelationId, AccessShareLock); scan = table_beginscan_catalog(rel, 0, NULL); while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection))) { Form_pg_database datform = (Form_pg_database) GETSTRUCT(tup); CfsBgDatabase *db; MemoryContext oldcxt; /* * Ignore databases that are not allowing connections, as the * autovacuum launcher does: they may be in the middle of being * dropped or altered, and the per-database worker could not connect * to them anyway. */ if (!datform->datallowconn) continue; /* * Ignore invalid databases, as the autovacuum launcher does: these * are leftovers of an interrupted CREATE DATABASE (or a DROP DATABASE * that failed midway), and the per-database worker would just die * with FATAL trying to connect to one. */ if (database_is_invalid_form(datform)) { elog(DEBUG1, "CFS bgworker: skipping invalid database \"%s\"", NameStr(datform->datname)); continue; } /* * Allocate the results in the caller's context, not the * transaction's, so that the list survives the commit. */ oldcxt = MemoryContextSwitchTo(resultcxt); db = (CfsBgDatabase *) palloc(sizeof(CfsBgDatabase)); db->dboid = datform->oid; db->dbname = pstrdup(NameStr(datform->datname)); dblist = lappend(dblist, db); MemoryContextSwitchTo(oldcxt); } table_endscan(scan); table_close(rel, AccessShareLock); return dblist; } /* * CfsBgWorkerMain — the CFS compaction launcher. * * The launcher is database-less and never compacts anything itself: every * cfs_bg_period_ms it enumerates pg_database and processes the databases * one at a time by starting a short-lived CfsBgWorkerDbMain worker and * waiting for its shutdown. */ void CfsBgWorkerMain(Datum main_arg) { TimestampTz next_run; /* * Value of cfs_bg_period_ms as of the last schedule computation: a * reload that moved the GUC re-arms the CURRENT wait (see below), * while an unchanged value keeps the absolute schedule. */ int last_period_ms; /* Establish signal handlers. */ pqsignal(SIGTERM, SignalHandlerForShutdownRequest); pqsignal(SIGHUP, SignalHandlerForConfigReload); BackgroundWorkerUnblockSignals(); /* * Initialize without connecting to any database, like the autovacuum * launcher: an InvalidOid database makes InitPostgres() return early on * the "background worker not bound to any particular database" path (see * utils/init/postinit.c), leaving us able to run transactions that reach * the shared catalogs — pg_database in particular. A background worker * cannot re-connect to another database later, so the per-database work * is done by the ephemeral workers started below. */ BackgroundWorkerInitializeConnectionByOid(InvalidOid, InvalidOid, 0); ereport(LOG, (errmsg("CFS background compaction worker started"))); /* * Fixed schedule, like the autovacuum launcher ("We sleep until the next * scheduled vacuum", launcher_determine_sleep): next_run holds the time * of the next pass, and after any non-timeout wake only the REMAINDER of * the period is waited out. Restarting the whole cfs_bg_period_ms after * every wake would let a config-reloading observer (an HA agent * re-reading the config every few seconds) postpone automatic compaction * indefinitely. A reloaded cfs_bg_period_ms is the one exception: the * wait is re-armed to the new period (see the re-arm below), so a * lowered value applies within one new period instead of after the * remainder of the old one. */ next_run = GetCurrentTimestamp() + cfs_bg_period_ms * INT64CONST(1000); last_period_ms = cfs_bg_period_ms; /* Main loop. */ while (!ShutdownRequestPending) { int rc; MemoryContext dblistcxt; List *dblist; ListCell *cell; long remaining_ms; bool cycle_complete = true; /* Wait for the remaining part of the period. */ remaining_ms = TimestampDifferenceMilliseconds(GetCurrentTimestamp(), next_run); rc = WaitLatch(&MyProc->procLatch, WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, remaining_ms, WAIT_EVENT_CFS_BGWORKER_MAIN); if (rc & WL_LATCH_SET) ResetLatch(&MyProc->procLatch); /* Handle SIGHUP / barrier / shutdown requests. */ ProcessMainLoopInterrupts(); if (ShutdownRequestPending) break; /* * Re-arm the CURRENT wait when a reload moved cfs_bg_period_ms: * without this, the absolute next_run above would keep sleeping * out the remainder of the old period (an hour, at the default) * and a lowered period would only apply after the first full * pass. A wake with an UNCHANGED value keeps the schedule, so * the anti-postpone property of the remainder logic above is * preserved for config re-reads that change nothing. */ if (cfs_bg_period_ms != last_period_ms) { last_period_ms = cfs_bg_period_ms; next_run = GetCurrentTimestamp() + cfs_bg_period_ms * INT64CONST(1000); } /*---------- * Only a fully elapsed period advances the cycle. The latch can * be left set by the process startup machinery, and stray latch * wakes (config reload, barrier) must not start a pass either: an * immediate pass right after server startup would connect a * per-database worker to every database the moment the server * comes up, which is both against the documented period-first * cycle and observable in pg_stat_have_stats() as freshly created * database entries (breaking the assumption of crash-restart * statistics tests). A stray wake costs only the remainder of * the period now, not the whole of it. *---------- */ if (!(rc & WL_TIMEOUT)) continue; StartTransactionCommand(); SetCurrentStatementStartTimestamp(); /* Record the start of this compaction cycle. */ cfs_bg_set_cycle_started(); /* * While paused, no per-database workers are started; the cycle * timestamps keep being refreshed so the worker status reflects * launcher activity. A timed pause self-clears on read. * * A paused pass re-arms the FULL period instead of leaving the * schedule in the past: with a stale next_run the remainder is 0, * WaitLatch(0) returns instantly, and the launcher would spin through * a full transactional iteration at machine speed for the whole * (possibly indefinite) pause. The "cannot launch workers right now" * branch of launcher_determine_sleep() does the same: it assigns the * whole autovacuum_naptime, never a remainder. */ if (cfs_bg_is_paused()) { CommitTransactionCommand(); cfs_bg_set_cycle_finished(); next_run = GetCurrentTimestamp() + cfs_bg_period_ms * INT64CONST(1000); last_period_ms = cfs_bg_period_ms; continue; } /* * Enumerate the databases of the cluster. The list lives in its own * memory context so that it survives the transaction used for the * scan (the pattern of get_database_list() in autovacuum.c); it is * released at the end of the cycle. */ dblistcxt = AllocSetContextCreate(TopMemoryContext, "CFS bgworker database list", ALLOCSET_DEFAULT_SIZES); dblist = cfs_bg_get_database_list(dblistcxt); CommitTransactionCommand(); /* * Process the databases strictly one at a time: start a worker * connected to the database and wait for it to finish before moving * on to the next one. */ foreach(cell, dblist) { CfsBgDatabase *db = lfirst(cell); BackgroundWorker worker; BackgroundWorkerHandle *handle; BgwHandleStatus status; if (ShutdownRequestPending) { cycle_complete = false; break; } MemSet(&worker, 0, sizeof(worker)); worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION; worker.bgw_start_time = BgWorkerStart_RecoveryFinished; worker.bgw_restart_time = BGW_NEVER_RESTART; snprintf(worker.bgw_library_name, sizeof(worker.bgw_library_name), "postgres"); snprintf(worker.bgw_function_name, sizeof(worker.bgw_function_name), "CfsBgWorkerDbMain"); snprintf(worker.bgw_name, sizeof(worker.bgw_name), "CFS background compaction worker for database \"%s\"", db->dbname); worker.bgw_main_arg = ObjectIdGetDatum(db->dboid); worker.bgw_notify_pid = MyProcPid; if (!RegisterDynamicBackgroundWorker(&worker, &handle)) { /* * No free worker slot: skip this database in this cycle * instead of dying; the next cycle retries it. */ elog(DEBUG1, "CFS bgworker: could not start worker for database \"%s\", skipping", db->dbname); cycle_complete = false; continue; } /* * Wait for the worker to finish so that compaction proceeds one * database at a time. However the worker exits is not an error * of the launcher: in particular, a database dropped between the * enumeration and its connection attempt makes the worker exit * with a FATAL error, which must not stop the remaining databases * from being processed. */ status = WaitForBackgroundWorkerShutdown(handle); pfree(handle); if (status == BGWH_POSTMASTER_DIED) { cycle_complete = false; break; } /* * Consume a config reload that arrived while we were blocked * in WaitForBackgroundWorkerShutdown(): that wait resets the * latch internally, so without this a pending SIGHUP would * stay unapplied until the next timeout wake and the schedule * computed at the end of the cycle would still use the old * cfs_bg_period_ms. Shutdown is deliberately not processed * here: the loop head above breaks out gracefully. */ if (ConfigReloadPending) { ConfigReloadPending = false; ProcessConfigFile(PGC_SIGHUP); } elog(DEBUG1, "CFS bgworker: processed database \"%s\"", db->dbname); } MemoryContextDelete(dblistcxt); /* * Retire history entries whose cfs_bg_min_interval_s window has * expired: they cannot matter any more, and retiring them also * retires the entries of dropped relations. */ cfs_bg_history_sweep(); /* Record the end of this compaction cycle. */ cfs_bg_set_cycle_finished(); /* * The crash-boot sweep (QDB-1507 U1) must cover every database * of the cluster: the per-database workers are short-lived and * run one at a time, so the shared marker may only be cleared * when a whole launcher cycle has serviced every database. A * cycle cut short - a shutdown or postmaster death breaking the * database loop, or a database skipped because no worker slot * was free - leaves the marker set, and the next cycle sweeps * what remains; clearing it on a partial cycle would let a * subsequent clean shutdown persist the unresynced values as * authoritative. A cycle that ran under a pause is not * complete either: its per-database workers exit before * collecting candidates, so the still-paused check keeps the * marker armed for the next unpaused cycle. A worker that * itself dies mid-pass still counts as serviced: the launcher * cannot see the exit code, and the expected FATAL (a dropped * database) leaves no relations to sweep. */ if (cycle_complete && !cfs_bg_is_paused() && cfs_stats_boot_sweep_pending()) cfs_stats_boot_sweep_done(); /* Schedule the next pass from the end of this one. */ next_run = GetCurrentTimestamp() + cfs_bg_period_ms * INT64CONST(1000); last_period_ms = cfs_bg_period_ms; } ereport(LOG, (errmsg("CFS background compaction worker shutting down"))); proc_exit(0); } /* * CfsBgWorkerDbMain — short-lived per-database worker started by the * launcher. It connects to the database whose OID arrives in main_arg, * performs a single compaction pass (the body the launcher's loop had * back when the worker was a single process) and exits. Waiting between * passes is the launcher's business. */ void CfsBgWorkerDbMain(Datum main_arg) { Oid dboid = DatumGetObjectId(main_arg); CfsBgScanState state; int processed = 0; int i; /* Establish signal handlers. */ /* * SIGTERM means "abort and exit cleanly", exactly like in the autovacuum * worker ("SIGTERM means abort and exit cleanly", autovacuum.c): die() * raises ProcDiePending, and the next CHECK_FOR_INTERRUPTS() -- in the * lock-wait tick, before the copy loop, or per copied block -- aborts * with the standard "terminating background worker due to administrator * command" FATAL instead of playing the current compaction out to its * end. */ pqsignal(SIGTERM, die); pqsignal(SIGHUP, SignalHandlerForConfigReload); BackgroundWorkerUnblockSignals(); /* * Connect to the target database. A database dropped between the * launcher's enumeration and this connection attempt makes us exit with a * FATAL error; that is expected — the launcher treats any exit of this * worker as "database done" and moves on. */ BackgroundWorkerInitializeConnectionByOid(dboid, InvalidOid, 0); /* Handle SIGHUP / barrier / shutdown requests that arrived meanwhile. */ ProcessMainLoopInterrupts(); StartTransactionCommand(); SetCurrentStatementStartTimestamp(); /* * A pause may have been requested after the launcher decided to start us: * honor it by doing nothing. */ if (cfs_bg_is_paused()) { CommitTransactionCommand(); proc_exit(0); } cfs_bg_collect_candidates(&state); /* Sort candidates by dead_bytes descending. */ if (state.n_candidates > 1) qsort(state.candidates, state.n_candidates, sizeof(CfsBgCandidate), cfs_bg_candidate_cmp); /* Compact up to cfs_bg_max_relations. */ for (i = 0; i < state.n_candidates && processed < cfs_bg_max_relations; i++) { /* * Absorb whatever signal arrived during the previous candidate -- * procsignal barriers, config reloads, shutdown -- right here, the * way vanilla background processes do in their main loops. A merely * pending barrier must not throw away the rest of the pass: the * relation being dropped waits for our absorption, not for our exit. * CHECK_FOR_INTERRUPTS turns a pending shutdown into the * administrator-command FATAL at once. */ ProcessMainLoopInterrupts(); CHECK_FOR_INTERRUPTS(); /* * Isolate each candidate: a compaction error (disk full, corrupted * sidecar, TOCTOU race against concurrent DDL) must not kill the * worker, otherwise the same broken candidate -- always first in the * dead-bytes order -- would stop automatic compaction for the whole * cluster on every restart. This mirrors the per-table error * isolation of the autovacuum launcher. */ PG_TRY(); { CfsCompactRelationByOid(state.candidates[i].relid, true, NULL); } PG_CATCH(); { /* * Abort the transaction, start a new one, and proceed with the * next candidate in our list. */ HOLD_INTERRUPTS(); errcontext("automatic CFS compaction of relation %u", state.candidates[i].relid); EmitErrorReport(); /* this resets ProcGlobal->statusFlags[i] too */ AbortOutOfAnyTransaction(); FlushErrorState(); /* * Record the failed attempt so that a persistently broken * relation is throttled by cfs_bg_min_interval_s like a compacted * one, instead of being retried (and failing) on every cycle * ahead of the healthy candidates. The history lives in shared * memory, so the record survives this short-lived worker. */ cfs_bg_history_set(state.candidates[i].relid, GetCurrentTimestamp()); /* restart our transaction for the following operations */ StartTransactionCommand(); RESUME_INTERRUPTS(); } PG_END_TRY(); processed++; if (i + 1 < state.n_candidates && processed < cfs_bg_max_relations) { /* * Pace the pass with a latch wait, like the autovacuum launcher * nap: visible in pg_stat_activity as CfsBgworkerDelay, and a * signal (shutdown, barrier) wakes it at once; pg_usleep would * silently discard the remainder on any signal (see the CAUTION * in pgsleep.c). */ ResetLatch(MyLatch); (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, cfs_bg_delay_ms, WAIT_EVENT_CFS_BGWORKER_DELAY); } } CommitTransactionCommand(); proc_exit(0); } void CfsBgWorkerRegister(void) { BackgroundWorker worker; MemSet(&worker, 0, sizeof(worker)); worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION; worker.bgw_start_time = BgWorkerStart_RecoveryFinished; worker.bgw_restart_time = 300; /* restart after 5 min if it crashes */ sprintf(worker.bgw_library_name, "postgres"); sprintf(worker.bgw_function_name, "CfsBgWorkerMain"); snprintf(worker.bgw_name, sizeof(worker.bgw_name), "CFS background compaction worker"); worker.bgw_main_arg = (Datum) 0; worker.bgw_notify_pid = 0; RegisterBackgroundWorker(&worker); } #endif /* USE_CFS */