From 42e609852671acabc96ef17ec06a495aa992cb23 Mon Sep 17 00:00:00 2001
From: Sami Imseih <samimseih@gmail.com>
Date: Thu, 2 Jul 2026 16:15:05 -0500
Subject: [PATCH v2 1/3] Add validations for required callbacks during
 pgstat_register_kind()

pgstat_register_kind() did not validate that required callbacks were
set, which could lead to NULL pointer dereferences.

For fixed-amount kinds, init_shmem_cb, reset_all_cb, and snapshot_cb
are called unconditionally. A missing callback crashes the server at
startup or during recovery.

For variable-numbered kinds, flush_pending_cb is called unconditionally
when flushing pending entries. If pending_size is set but
flush_pending_cb is NULL, the server crashes when that callback is run.

Add validation checks at registration time for custom kinds.
---
 src/backend/utils/activity/pgstat.c | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/src/backend/utils/activity/pgstat.c b/src/backend/utils/activity/pgstat.c
index c4fa14f138f..f6223d2a3dd 100644
--- a/src/backend/utils/activity/pgstat.c
+++ b/src/backend/utils/activity/pgstat.c
@@ -1533,11 +1533,34 @@ pgstat_register_kind(PgStat_Kind kind, const PgStat_KindInfo *kind_info)
 			ereport(ERROR,
 					(errmsg("custom cumulative statistics property is invalid"),
 					 errhint("Custom cumulative statistics require a shared memory size for fixed-numbered objects.")));
+		if (kind_info->init_shmem_cb == NULL)
+			ereport(ERROR,
+					(errmsg("failed to register custom cumulative statistics \"%s\" with ID %u", kind_info->name, kind),
+					 errhint("Custom cumulative statistics require a \"%s\" callback for fixed-numbered objects.",
+							 "init_shmem_cb")));
+		if (kind_info->reset_all_cb == NULL)
+			ereport(ERROR,
+					(errmsg("failed to register custom cumulative statistics \"%s\" with ID %u", kind_info->name, kind),
+					 errhint("Custom cumulative statistics require a \"%s\" callback for fixed-numbered objects.",
+							 "reset_all_cb")));
+		if (kind_info->snapshot_cb == NULL)
+			ereport(ERROR,
+					(errmsg("failed to register custom cumulative statistics \"%s\" with ID %u", kind_info->name, kind),
+					 errhint("Custom cumulative statistics require a \"%s\" callback for fixed-numbered objects.",
+							 "snapshot_cb")));
 		if (kind_info->track_entry_count)
 			ereport(ERROR,
 					(errmsg("custom cumulative statistics property is invalid"),
 					 errhint("Custom cumulative statistics cannot use entry count tracking for fixed-numbered objects.")));
 	}
+	else
+	{
+		if (kind_info->pending_size > 0 && kind_info->flush_pending_cb == NULL)
+			ereport(ERROR,
+					(errmsg("failed to register custom cumulative statistics \"%s\" with ID %u", kind_info->name, kind),
+					 errhint("Custom cumulative statistics require a \"%s\" callback when pending_size is set.",
+							 "flush_pending_cb")));
+	}
 
 	/*
 	 * If pgstat_kind_custom_infos is not available yet, allocate it.
-- 
2.50.1 (Apple Git-155)

