[PATCH] Add tests for Bitmapset

Started by Greg Burd5 months ago75 messages
#1Greg Burd
greg@burd.me
1 attachment(s)

Hello,

I noticed that there are no tests for Bitmapset in src/test/modules as
is the case for other similar things like radixtree, rbtree, etc. so I
created one. I realize that Bitmapset is already "tested" by all the
other code that uses it, but I was able to find one minor oversight[1]/messages/by-id/2000A717-1FFE-4031-827B-9330FB2E9065@getmailspring.com
in that code with these new tests.

I hope I've covered all the bases, but if you have thoughts on other
ways to test Bitmapset I'll happily add them to the patch.

best.

-greg

[1]: /messages/by-id/2000A717-1FFE-4031-827B-9330FB2E9065@getmailspring.com

Attachments:

v1-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From 3a1423b27fdcc5a9ac812418aa39b239ff9d80ed Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v1] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |   1 +
 src/test/modules/meson.build                  |   1 +
 src/test/modules/test_bitmapset/.gitignore    |   4 +
 src/test/modules/test_bitmapset/Makefile      |  23 +
 .../expected/test_bitmapset.out               |  19 +
 src/test/modules/test_bitmapset/meson.build   |  33 ++
 .../test_bitmapset/sql/test_bitmapset.sql     |   7 +
 .../test_bitmapset/test_bitmapset--1.0.sql    |   8 +
 .../modules/test_bitmapset/test_bitmapset.c   | 419 ++++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |   4 +
 10 files changed, 519 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..32093d81f67
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,19 @@
+CREATE EXTENSION test_bitmapset;
+--
+-- All the logic is in the test_bitmapset() function. It will throw
+-- an error if something fails.
+--
+SELECT test_bitmapset();
+NOTICE:  starting bitmapset tests
+NOTICE:  testing empty bitmapset operations
+NOTICE:  testing single element bitmapset operations
+NOTICE:  testing multiple elements and set operations
+NOTICE:  testing edge cases and boundary conditions
+NOTICE:  testing iteration functions
+NOTICE:  testing comprehensive set operations
+NOTICE:  all bitmapset tests passed
+ test_bitmapset 
+----------------
+ 
+(1 row)
+
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..ceb524ee51b
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,7 @@
+CREATE EXTENSION test_bitmapset;
+
+--
+-- All the logic is in the test_bitmapset() function. It will throw
+-- an error if something fails.
+--
+SELECT test_bitmapset();
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..ba8af997044
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,8 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+CREATE FUNCTION test_bitmapset()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..39e28781893
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,419 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include "fmgr.h"
+#include "nodes/bitmapset.h"
+
+PG_MODULE_MAGIC;
+
+PG_FUNCTION_INFO_V1(test_bitmapset);
+
+/* Test assertion macros following test_bitmapset pattern */
+#define EXPECT_TRUE(expr) \
+    do { \
+        if (!(expr)) \
+            elog(ERROR, \
+                 "%s was unexpectedly false in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_FALSE(expr) \
+    do { \
+        if (expr) \
+            elog(ERROR, \
+                 "%s was unexpectedly true in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_EQ_INT(result_expr, expected_expr) \
+    do { \
+        int _result = (result_expr); \
+        int _expected = (expected_expr); \
+        if (_result != _expected) \
+            elog(ERROR, \
+                 "%s yielded %d, expected %d (%s) in file \"%s\" line %u", \
+                 #result_expr, _result, _expected, #expected_expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_NULL(expr) \
+    do { \
+        if ((expr) != NULL) \
+            elog(ERROR, \
+                 "%s was unexpectedly non-NULL in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_NOT_NULL(expr) \
+    do { \
+        if ((expr) == NULL) \
+            elog(ERROR, \
+                 "%s was unexpectedly NULL in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+/* Test empty bitmapset operations */
+static void
+test_empty_bitmapset(void)
+{
+	Bitmapset  *result,
+			   *bms = NULL;
+
+	elog(NOTICE, "testing empty bitmapset operations");
+
+	/* Test operations on NULL bitmapset */
+	EXPECT_TRUE(bms_is_empty(bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 0);
+	EXPECT_FALSE(bms_is_member(0, bms));
+	EXPECT_FALSE(bms_is_member(1, bms));
+	EXPECT_FALSE(bms_is_member(100, bms));
+	EXPECT_EQ_INT(bms_next_member(bms, -1), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, -1), -2);
+
+	/* Test copy of empty set */
+	result = bms_copy(bms);
+	EXPECT_NULL(result);
+
+	/* Test union with empty set */
+	result = bms_union(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test intersection with empty set */
+	result = bms_intersect(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test difference with empty set */
+	result = bms_difference(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test equal comparison */
+	EXPECT_TRUE(bms_equal(bms, NULL));
+	EXPECT_TRUE(bms_equal(NULL, bms));
+
+	/* Test subset operations */
+	EXPECT_TRUE(bms_is_subset(bms, NULL));
+	EXPECT_TRUE(bms_is_subset(NULL, bms));
+
+	/* Test overlap */
+	EXPECT_FALSE(bms_overlap(bms, NULL));
+	EXPECT_FALSE(bms_overlap(NULL, bms));
+}
+
+/* Test single element bitmapset operations */
+static void
+test_single_element(void)
+{
+	Bitmapset  *result,
+			   *bms = NULL;
+	int			test_member = 42;
+
+	elog(NOTICE, "testing single element bitmapset operations");
+
+	/* Add single element */
+	bms = bms_add_member(bms, test_member);
+	EXPECT_NOT_NULL(bms);
+	EXPECT_FALSE(bms_is_empty(bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_TRUE(bms_is_member(test_member, bms));
+	EXPECT_FALSE(bms_is_member(test_member - 1, bms));
+	EXPECT_FALSE(bms_is_member(test_member + 1, bms));
+
+	/* Test iteration */
+	EXPECT_EQ_INT(bms_next_member(bms, -1), test_member);
+	EXPECT_EQ_INT(bms_next_member(bms, test_member), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, test_member + 1), test_member);
+	EXPECT_EQ_INT(bms_prev_member(bms, test_member), -2);
+
+	/* Test copy */
+	result = bms_copy(bms);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_equal(bms, result));
+	EXPECT_TRUE(bms_is_member(test_member, result));
+
+	/* Test remove member */
+	result = bms_del_member(result, test_member);
+	EXPECT_NULL(result);
+
+	/* Test remove non-existent member */
+	result = bms_copy(bms);
+	EXPECT_NOT_NULL(result);
+	result = bms_del_member(result, test_member + 1);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_equal(bms, result));
+
+	bms_free(bms);
+	bms_free(result);
+}
+
+/* Test multiple elements and set operations */
+static void
+test_multiple_elements(void)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *result = NULL;
+	int			elements1[] = {1, 5, 10, 15, 20, 100};
+	int			elements2[] = {3, 5, 12, 15, 25, 200};
+	int			num_elements1 = sizeof(elements1) / sizeof(elements1[0]);
+	int			num_elements2 = sizeof(elements2) / sizeof(elements2[0]);
+
+	elog(NOTICE, "testing multiple elements and set operations");
+
+	/* Build first set */
+	for (int i = 0; i < num_elements1; i++)
+		bms1 = bms_add_member(bms1, elements1[i]);
+
+	EXPECT_EQ_INT(bms_num_members(bms1), num_elements1);
+
+	/* Build second set */
+	for (int i = 0; i < num_elements2; i++)
+		bms2 = bms_add_member(bms2, elements2[i]);
+
+	EXPECT_EQ_INT(bms_num_members(bms2), num_elements2);
+
+	/* Test membership */
+	for (int i = 0; i < num_elements1; i++)
+		EXPECT_TRUE(bms_is_member(elements1[i], bms1));
+
+	for (int i = 0; i < num_elements2; i++)
+		EXPECT_TRUE(bms_is_member(elements2[i], bms2));
+
+	/* Test union */
+	result = bms_union(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	for (int i = 0; i < num_elements1; i++)
+		EXPECT_TRUE(bms_is_member(elements1[i], result));
+	for (int i = 0; i < num_elements2; i++)
+		EXPECT_TRUE(bms_is_member(elements2[i], result));
+	EXPECT_EQ_INT(bms_num_members(result), 10); /* 1,3,5,10,12,15,20,25,100,200 */
+	bms_free(result);
+
+	/* Test intersection */
+	result = bms_intersect(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_is_member(5, result));
+	EXPECT_TRUE(bms_is_member(15, result));
+	EXPECT_EQ_INT(bms_num_members(result), 2);	/* 5, 15 */
+	bms_free(result);
+
+	/* Test difference */
+	result = bms_difference(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_is_member(1, result));
+	EXPECT_TRUE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(20, result));
+	EXPECT_TRUE(bms_is_member(100, result));
+	EXPECT_FALSE(bms_is_member(5, result));
+	EXPECT_FALSE(bms_is_member(15, result));
+	EXPECT_EQ_INT(bms_num_members(result), 4);	/* 1, 10, 20, 100 */
+	bms_free(result);
+
+	/* Test overlap */
+	EXPECT_TRUE(bms_overlap(bms1, bms2));
+
+	/* Test subset operations */
+	result = NULL;
+	result = bms_add_member(result, 5);
+	result = bms_add_member(result, 15);
+	EXPECT_TRUE(bms_is_subset(result, bms1));
+	EXPECT_TRUE(bms_is_subset(result, bms2));
+	EXPECT_FALSE(bms_is_subset(bms1, result));
+	bms_free(result);
+
+	bms_free(bms1);
+	bms_free(bms2);
+}
+
+/* Test edge cases and boundary conditions */
+static void
+test_edge_cases(void)
+{
+	int			large_element = 10000;
+	int			count;
+	int			member;
+	Bitmapset  *result;
+	Bitmapset  *bms = NULL;
+
+	elog(NOTICE, "testing edge cases and boundary conditions");
+
+	/* Test element 0 */
+	bms = bms_add_member(bms, 0);
+	EXPECT_TRUE(bms_is_member(0, bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_EQ_INT(bms_next_member(bms, -1), 0);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test large element numbers */
+	bms = bms_add_member(bms, large_element);
+	EXPECT_TRUE(bms_is_member(large_element, bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test adding same element multiple times */
+	bms = bms_add_member(bms, 42);
+	bms = bms_add_member(bms, 42);
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_TRUE(bms_is_member(42, bms));
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test removing from single-element set */
+	bms = bms_add_member(bms, 99);
+	result = bms_del_member(bms, 99);
+	EXPECT_NULL(result);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test dense range */
+	for (int i = 0; i < 64; i++)
+		bms = bms_add_member(bms, i);
+	EXPECT_EQ_INT(bms_num_members(bms), 64);
+
+	/* Test iteration over dense range */
+	count = 0;
+	member = -1;
+	while ((member = bms_next_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, count);
+		count++;
+	}
+	EXPECT_EQ_INT(count, 64);
+
+	bms_free(bms);
+}
+
+/* Test iterator functions thoroughly */
+static void
+test_iteration(void)
+{
+	Bitmapset  *bms = NULL;
+	int			member;
+	int			index;
+	int			elements[] = {2, 7, 15, 31, 63, 127, 255, 511, 1023};
+	int			num_elements = sizeof(elements) / sizeof(elements[0]);
+
+	elog(NOTICE, "testing iteration functions");
+
+	/* Build test set */
+	for (int i = 0; i < num_elements; i++)
+		bms = bms_add_member(bms, elements[i]);
+
+	/* Test forward iteration */
+	member = -1;
+	index = 0;
+	while ((member = bms_next_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, elements[index]);
+		index++;
+	}
+	EXPECT_EQ_INT(index, num_elements);
+
+	/* Test backward iteration */
+	member = bms->nwords * BITS_PER_BITMAPWORD;
+	index = num_elements - 1;
+	while ((member = bms_prev_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, elements[index]);
+		index--;
+	}
+	EXPECT_EQ_INT(index, -1);
+
+	/* Test iteration bounds */
+	EXPECT_EQ_INT(bms_next_member(bms, 1023), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, 2), -2);
+
+	bms_free(bms);
+}
+
+/* Test set operations with various combinations */
+static void
+test_set_operations(void)
+{
+	Bitmapset  *empty = NULL;
+	Bitmapset  *single = NULL;
+	Bitmapset  *multi = NULL;
+	Bitmapset  *result = NULL;
+	Bitmapset  *single_copy = NULL;
+
+	elog(NOTICE, "testing comprehensive set operations");
+
+	single = bms_add_member(single, 10);
+	multi = bms_add_member(multi, 5);
+	multi = bms_add_member(multi, 10);
+	multi = bms_add_member(multi, 15);
+
+	/* Union operations */
+	result = bms_union(empty, single);
+	EXPECT_TRUE(bms_equal(result, single));
+	bms_free(result);
+
+	result = bms_union(single, empty);
+	EXPECT_TRUE(bms_equal(result, single));
+	bms_free(result);
+
+	result = bms_union(single, multi);
+	EXPECT_EQ_INT(bms_num_members(result), 3);
+	EXPECT_TRUE(bms_is_member(5, result));
+	EXPECT_TRUE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(15, result));
+	bms_free(result);
+
+	/* Intersection operations */
+	result = bms_intersect(empty, single);
+	EXPECT_NULL(result);
+
+	result = bms_intersect(single, multi);
+	EXPECT_EQ_INT(bms_num_members(result), 1);
+	EXPECT_TRUE(bms_is_member(10, result));
+	bms_free(result);
+
+	/* Difference operations */
+	result = bms_difference(single, multi);
+	EXPECT_NULL(result);
+
+	result = bms_difference(multi, single);
+	EXPECT_EQ_INT(bms_num_members(result), 2);
+	EXPECT_TRUE(bms_is_member(5, result));
+	EXPECT_TRUE(bms_is_member(15, result));
+	EXPECT_FALSE(bms_is_member(10, result));
+	bms_free(result);
+
+	/* Equality tests */
+	EXPECT_FALSE(bms_equal(single, multi));
+	EXPECT_TRUE(bms_equal(empty, NULL));
+
+	single_copy = bms_copy(single);
+	EXPECT_TRUE(bms_equal(single, single_copy));
+	bms_free(single_copy);
+
+	bms_free(single);
+	bms_free(multi);
+}
+
+/* Main test function */
+Datum
+test_bitmapset(PG_FUNCTION_ARGS)
+{
+	elog(NOTICE, "starting bitmapset tests");
+
+	test_empty_bitmapset();
+	test_single_element();
+	test_multiple_elements();
+	test_edge_cases();
+	test_iteration();
+	test_set_operations();
+
+	elog(NOTICE, "all bitmapset tests passed");
+
+	PG_RETURN_VOID();
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#2Nathan Bossart
nathandbossart@gmail.com
In reply to: Greg Burd (#1)
Re: [PATCH] Add tests for Bitmapset

On Fri, Aug 15, 2025 at 11:39:23AM -0400, Greg Burd wrote:

I noticed that there are no tests for Bitmapset in src/test/modules as
is the case for other similar things like radixtree, rbtree, etc. so I
created one. I realize that Bitmapset is already "tested" by all the
other code that uses it, but I was able to find one minor oversight[1]
in that code with these new tests.

I hope I've covered all the bases, but if you have thoughts on other
ways to test Bitmapset I'll happily add them to the patch.

Adding some tests here seems like a good idea. I might look into some ways
to trim it down a bit, but that'd just be minor editorialization. One
other thing to consider is adding randomness to the tests (see
test_radixtree and test_binaryheap for examples).

--
nathan

#3Burd, Greg
greg@burd.me
In reply to: Nathan Bossart (#2)
Re: [PATCH] Add tests for Bitmapset

On Sep 4, 2025, at 10:00 PM, Nathan Bossart <nathandbossart@gmail.com> wrote:

On Fri, Aug 15, 2025 at 11:39:23AM -0400, Greg Burd wrote:

I noticed that there are no tests for Bitmapset in src/test/modules as
is the case for other similar things like radixtree, rbtree, etc. so I
created one. I realize that Bitmapset is already "tested" by all the
other code that uses it, but I was able to find one minor oversight[1]
in that code with these new tests.

I hope I've covered all the bases, but if you have thoughts on other
ways to test Bitmapset I'll happily add them to the patch.

Adding some tests here seems like a good idea. I might look into some ways
to trim it down a bit, but that'd just be minor editorialization. One
other thing to consider is adding randomness to the tests (see
test_radixtree and test_binaryheap for examples).

Nathan,

Thank you for your interest in this patch, I appreciate that your time is
limited and highly valuable to the community. This patch isn't "earth
shattering", but I think it's valuable to have test coverage even in cases
where the code being tested is already very well exercised.

I looked at both radix tree and binary heap and how they use random sets when
testing. Binary heap uses it to create different random sets of numbers to
use across multiple tests while radix tree has a single function that focuses
on randomized data. I decided not to add randomization into the tests of
Bitmapset simply because I like avoiding non-deterministic behavior. But in
tests I guess that can be helpful finding future unknown corner cases. I'm
on the fence as to the value, your call. :)

Let me know if you'd like that or not.

--
Nathan

best, and thanks again for the attention,

-greg

#4Nathan Bossart
nathandbossart@gmail.com
In reply to: Burd, Greg (#3)
Re: [PATCH] Add tests for Bitmapset

On Fri, Sep 05, 2025 at 10:48:21AM -0400, Burd, Greg wrote:

I looked at both radix tree and binary heap and how they use random sets when
testing. Binary heap uses it to create different random sets of numbers to
use across multiple tests while radix tree has a single function that focuses
on randomized data. I decided not to add randomization into the tests of
Bitmapset simply because I like avoiding non-deterministic behavior. But in
tests I guess that can be helpful finding future unknown corner cases. I'm
on the fence as to the value, your call. :)

I'm not too concerned about it. We've lived without a dedicated test suite
for Bitmapset for a very long time, so any amount of test coverage is an
improvement. Like you said, adding some randomization might be helpful for
finding weird bugs we wouldn't have thought to test. And, given the many,
many machines that run the tests, IMHO it'd only help build even more
confidence in the code. If my suggestion inspires you to update the patch,
great, but I'm fine with proceeding with what you already wrote, too.

--
nathan

#5Burd, Greg
greg@burd.me
In reply to: Nathan Bossart (#4)
Re: [PATCH] Add tests for Bitmapset

On Sep 5, 2025, at 2:43 PM, Nathan Bossart <nathandbossart@gmail.com> wrote:

On Fri, Sep 05, 2025 at 10:48:21AM -0400, Burd, Greg wrote:

I looked at both radix tree and binary heap and how they use random sets when
testing. Binary heap uses it to create different random sets of numbers to
use across multiple tests while radix tree has a single function that focuses
on randomized data. I decided not to add randomization into the tests of
Bitmapset simply because I like avoiding non-deterministic behavior. But in
tests I guess that can be helpful finding future unknown corner cases. I'm
on the fence as to the value, your call. :)

I'm not too concerned about it. We've lived without a dedicated test suite
for Bitmapset for a very long time, so any amount of test coverage is an
improvement. Like you said, adding some randomization might be helpful for
finding weird bugs we wouldn't have thought to test. And, given the many,
many machines that run the tests, IMHO it'd only help build even more
confidence in the code. If my suggestion inspires you to update the patch,
great, but I'm fine with proceeding with what you already wrote, too.

Nathan, thanks for considering the patch. Honestly, I'm fine with it as is.
We can revisit later if needed. This does what I'd intended, test and document
in code the API and implementation making future changes to that more
transparent.

Thanks!

-greg

--

Show quoted text

nathan

#6Masahiko Sawada
sawada.mshk@gmail.com
In reply to: Burd, Greg (#5)
Re: [PATCH] Add tests for Bitmapset

On Mon, Sep 8, 2025 at 11:21 AM Burd, Greg <greg@burd.me> wrote:

On Sep 5, 2025, at 2:43 PM, Nathan Bossart <nathandbossart@gmail.com> wrote:

On Fri, Sep 05, 2025 at 10:48:21AM -0400, Burd, Greg wrote:

I looked at both radix tree and binary heap and how they use random sets when
testing. Binary heap uses it to create different random sets of numbers to
use across multiple tests while radix tree has a single function that focuses
on randomized data. I decided not to add randomization into the tests of
Bitmapset simply because I like avoiding non-deterministic behavior. But in
tests I guess that can be helpful finding future unknown corner cases. I'm
on the fence as to the value, your call. :)

I'm not too concerned about it. We've lived without a dedicated test suite
for Bitmapset for a very long time, so any amount of test coverage is an
improvement. Like you said, adding some randomization might be helpful for
finding weird bugs we wouldn't have thought to test. And, given the many,
many machines that run the tests, IMHO it'd only help build even more
confidence in the code. If my suggestion inspires you to update the patch,
great, but I'm fine with proceeding with what you already wrote, too.

Nathan, thanks for considering the patch. Honestly, I'm fine with it as is.
We can revisit later if needed. This does what I'd intended, test and document
in code the API and implementation making future changes to that more
transparent.

I appreciate your work on this. While I agree that adding more tests
to bitmapset.c is a good idea, I'm concerned about the minimal
improvement in test coverage despite the addition of new test cases
(only three lines of code are newly covered). Apart from adding some
randomness to the tests we've discussed, given that we're implementing
a dedicated test module for bitmapset.c, I would expect to see a more
increase in test coverage.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

#7Greg Burd
greg@burd.me
In reply to: Masahiko Sawada (#6)
Re: [PATCH] Add tests for Bitmapset

On Thu, Sep 11, 2025, at 2:48 AM, Masahiko Sawada wrote:

On Mon, Sep 8, 2025 at 11:21 AM Burd, Greg <greg@burd.me> wrote:

On Sep 5, 2025, at 2:43 PM, Nathan Bossart <nathandbossart@gmail.com> wrote:

On Fri, Sep 05, 2025 at 10:48:21AM -0400, Burd, Greg wrote:

I looked at both radix tree and binary heap and how they use random sets when
testing. Binary heap uses it to create different random sets of numbers to
use across multiple tests while radix tree has a single function that focuses
on randomized data. I decided not to add randomization into the tests of
Bitmapset simply because I like avoiding non-deterministic behavior. But in
tests I guess that can be helpful finding future unknown corner cases. I'm
on the fence as to the value, your call. :)

I'm not too concerned about it. We've lived without a dedicated test suite
for Bitmapset for a very long time, so any amount of test coverage is an
improvement. Like you said, adding some randomization might be helpful for
finding weird bugs we wouldn't have thought to test. And, given the many,
many machines that run the tests, IMHO it'd only help build even more
confidence in the code. If my suggestion inspires you to update the patch,
great, but I'm fine with proceeding with what you already wrote, too.

Nathan, thanks for considering the patch. Honestly, I'm fine with it as is.
We can revisit later if needed. This does what I'd intended, test and document
in code the API and implementation making future changes to that more
transparent.

I appreciate your work on this. While I agree that adding more tests
to bitmapset.c is a good idea, I'm concerned about the minimal
improvement in test coverage despite the addition of new test cases
(only three lines of code are newly covered). Apart from adding some
randomness to the tests we've discussed, given that we're implementing
a dedicated test module for bitmapset.c, I would expect to see a more
increase in test coverage.

Good point and thanks for taking the time to reply. The only thing it identified
was a small issue fixed in b463288 so I'd not expect coverage to increase much.

I'll take a stab at adding some randomness to the tests and check the delta in
coverage. Thanks for the nudge. :)

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Just for reference I started this not to increase coverage, which is a good
goal just not the one I had. I was reviewing the API and considering some
changes based on other work I've done. Now that I see how deeply baked in
this code is I think that's unlikely. Maybe something else distinct for
bitmaps over 64-bit space at some point will be useful. I wrote this code
just to capture the API in test form.

best,

-greg

#8Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#7)
Re: [PATCH] Add tests for Bitmapset

On Thu, Sep 11, 2025 at 06:56:07AM -0400, Greg Burd wrote:

Just for reference I started this not to increase coverage, which is a good
goal just not the one I had. I was reviewing the API and considering some
changes based on other work I've done. Now that I see how deeply baked in
this code is I think that's unlikely. Maybe something else distinct for
bitmaps over 64-bit space at some point will be useful. I wrote this code
just to capture the API in test form.

How much does this measure in terms of numbers produced by
coverage-html (see [1]https://www.postgresql.org/docs/devel/regress-coverage.html -- Michael)? The paths taken don't always matter as it
can also be important to check combinations of code paths that are
taken by other tests when checking after edge cases, but that would
give an idea of gain vs extra runtime. Not objecting to your patch,
just being curious as I am not seeing any numbers posted on this
thread.

[1]: https://www.postgresql.org/docs/devel/regress-coverage.html -- Michael
--
Michael

#9Greg Burd
greg@burd.me
In reply to: Michael Paquier (#8)
Re: [PATCH] Add tests for Bitmapset

On Sep 11, 2025, at 9:36 PM, Michael Paquier <michael@paquier.xyz> wrote:

On Thu, Sep 11, 2025 at 06:56:07AM -0400, Greg Burd wrote:

Just for reference I started this not to increase coverage, which is a good
goal just not the one I had. I was reviewing the API and considering some
changes based on other work I've done. Now that I see how deeply baked in
this code is I think that's unlikely. Maybe something else distinct for
bitmaps over 64-bit space at some point will be useful. I wrote this code
just to capture the API in test form.

How much does this measure in terms of numbers produced by
coverage-html (see [1])? The paths taken don't always matter as it
can also be important to check combinations of code paths that are
taken by other tests when checking after edge cases, but that would
give an idea of gain vs extra runtime. Not objecting to your patch,
just being curious as I am not seeing any numbers posted on this
thread.

[1]: https://www.postgresql.org/docs/devel/regress-coverage.html
--
Michael

Sawada-san, Michael,

Thank you both for the push to measure. Before the patch as it stands now the
coverage for src/backend/nodes/bitmapset.c is 63.5% and after it is 66.5%. Not
an amazing difference, but something. I guess I expected this to be higher given
the degree to which this datatype is used.

I'll review the gaps in coverage and update the tests. I'll look for a way to add
meaningful randomization.

-greg

#10Greg Burd
greg@burd.me
In reply to: Greg Burd (#9)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 13 2025, at 10:23 am, Greg Burd <greg@burd.me> wrote:

Sawada-san, Michael,

Thank you both for the push to measure.  Before the patch as it stands
now the
coverage for src/backend/nodes/bitmapset.c is 63.5% and after it is
66.5%.  Not
an amazing difference, but something.  I guess I expected this to be
higher given
the degree to which this datatype is used.

I'll review the gaps in coverage and update the tests.  I'll look for
a way to add meaningful randomization.

-greg

Hello hackers,

Here's the progress I've made in coverage for testing Bitmapset.

coverage: HEAD v1 v2
lines......: 87.1 87.7 91.3
functions..: 100 100 100
branches...: 63.5 66.5 77.9

I've also added a function that performs a variety of operations using
random data.

For reference radixtree has:

coverage: HEAD
lines......: 98.3
functions..: 97.2
branches...: 89.4

best,

-greg

Attachments:

v2-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From 7ef400ec9e7ac0842a593de01db462e80d5ef19a Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v2] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |   1 +
 src/test/modules/meson.build                  |   1 +
 src/test/modules/test_bitmapset/.gitignore    |   4 +
 src/test/modules/test_bitmapset/Makefile      |  23 +
 .../expected/test_bitmapset.out               |  24 +
 src/test/modules/test_bitmapset/meson.build   |  33 +
 .../test_bitmapset/sql/test_bitmapset.sql     |   7 +
 .../test_bitmapset/test_bitmapset--1.0.sql    |   8 +
 .../modules/test_bitmapset/test_bitmapset.c   | 767 ++++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |   4 +
 10 files changed, 872 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..f2669f14501
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,24 @@
+CREATE EXTENSION test_bitmapset;
+--
+-- All the logic is in the test_bitmapset() function. It will throw
+-- an error if something fails.
+--
+SELECT test_bitmapset();
+NOTICE:  starting bitmapset tests
+NOTICE:  testing empty bitmapset operations
+NOTICE:  testing single element bitmapset operations
+NOTICE:  testing multiple elements and set operations
+NOTICE:  testing error conditions
+NOTICE:  testing prev_member edge cases
+NOTICE:  testing edge cases and boundary conditions
+NOTICE:  testing iteration functions
+NOTICE:  testing comprehensive set operations
+NOTICE:  testing randomized operations
+NOTICE:  randomized testing completed successfully
+NOTICE:  testing advanced functions
+NOTICE:  all bitmapset tests passed
+ test_bitmapset 
+----------------
+ 
+(1 row)
+
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..ceb524ee51b
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,7 @@
+CREATE EXTENSION test_bitmapset;
+
+--
+-- All the logic is in the test_bitmapset() function. It will throw
+-- an error if something fails.
+--
+SELECT test_bitmapset();
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..ba8af997044
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,8 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+CREATE FUNCTION test_bitmapset()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..70614bd6e71
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,767 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include "common/pg_prng.h"
+#include "utils/timestamp.h"
+#include "fmgr.h"
+#include "nodes/pg_list.h"
+#include "nodes/bitmapset.h"
+
+PG_MODULE_MAGIC;
+
+PG_FUNCTION_INFO_V1(test_bitmapset);
+
+#define EXPECT_TRUE(expr) \
+    do { \
+        if (!(expr)) \
+            elog(ERROR, \
+                 "%s was unexpectedly false in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_FALSE(expr) \
+    do { \
+        if (expr) \
+            elog(ERROR, \
+                 "%s was unexpectedly true in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_EQ_INT(result_expr, expected_expr) \
+    do { \
+        int _result = (result_expr); \
+        int _expected = (expected_expr); \
+        if (_result != _expected) \
+            elog(ERROR, \
+                 "%s yielded %d, expected %d (%s) in file \"%s\" line %u", \
+                 #result_expr, _result, _expected, #expected_expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_NULL(expr) \
+    do { \
+        if ((expr) != NULL) \
+            elog(ERROR, \
+                 "%s was unexpectedly non-NULL in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_NOT_NULL(expr) \
+    do { \
+        if ((expr) == NULL) \
+            elog(ERROR, \
+                 "%s was unexpectedly NULL in file \"%s\" line %u", \
+                 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#ifdef DEBUG
+
+static void
+elog_bitmapset(int elevel, const char *label, const Bitmapset *bms)
+{
+	StringInfoData buf;
+	int			member;
+	bool		first = true;
+
+	initStringInfo(&buf);
+
+	if (label)
+		appendStringInfo(&buf, "%s: ", label);
+
+	if (!bms_is_empty(bms))
+	{
+		appendStringInfoChar(&buf, '{');
+		member = -1;
+		while ((member = bms_next_member(bms, member)) >= 0)
+		{
+			if (!first)
+				appendStringInfoString(&buf, ", ");
+			appendStringInfo(&buf, "%d", member);
+			first = false;
+		}
+		appendStringInfoChar(&buf, '}');
+	}
+	else
+		appendStringInfoString(&buf, "EMPTY");
+
+	elog(elevel, "%s", buf.data);
+	pfree(buf.data);
+}
+
+#endif
+
+/* Test error conditions for negative members */
+static void
+test_error_conditions(void)
+{
+	Bitmapset  *bms = NULL;
+	bool		error_caught;
+
+	elog(NOTICE, "testing error conditions");
+
+	/* Test negative member in bms_make_singleton */
+	error_caught = false;
+	PG_TRY();
+	{
+		bms_make_singleton(-1);
+	}
+	PG_CATCH();
+	{
+		error_caught = true;
+		FlushErrorState();
+	}
+	PG_END_TRY();
+	EXPECT_TRUE(error_caught);
+
+	/* Test negative member in bms_is_member */
+	error_caught = false;
+	PG_TRY();
+	{
+		bms_is_member(-5, bms);
+	}
+	PG_CATCH();
+	{
+		error_caught = true;
+		FlushErrorState();
+	}
+	PG_END_TRY();
+	EXPECT_TRUE(error_caught);
+
+	/* Test negative member in bms_add_member */
+	error_caught = false;
+	PG_TRY();
+	{
+		bms = bms_add_member(bms, -10);
+	}
+	PG_CATCH();
+	{
+		error_caught = true;
+		FlushErrorState();
+	}
+	PG_END_TRY();
+	EXPECT_TRUE(error_caught);
+
+	/* Test negative member in bms_del_member */
+	error_caught = false;
+	PG_TRY();
+	{
+		bms = bms_del_member(bms, -20);
+	}
+	PG_CATCH();
+	{
+		error_caught = true;
+		FlushErrorState();
+	}
+	PG_END_TRY();
+	EXPECT_TRUE(error_caught);
+
+	/* Test negative member in bms_add_range */
+	error_caught = false;
+	PG_TRY();
+	{
+		bms = bms_add_range(bms, -5, 10);
+	}
+	PG_CATCH();
+	{
+		error_caught = true;
+		FlushErrorState();
+	}
+	PG_END_TRY();
+	EXPECT_TRUE(error_caught);
+
+	/* Test empty set error in bms_singleton_member */
+	error_caught = false;
+	PG_TRY();
+	{
+		bms_singleton_member(NULL);
+	}
+	PG_CATCH();
+	{
+		error_caught = true;
+		FlushErrorState();
+	}
+	PG_END_TRY();
+	EXPECT_TRUE(error_caught);
+
+	/* Test multiple members error in bms_singleton_member */
+	bms = bms_add_member(bms, 1);
+	bms = bms_add_member(bms, 2);
+	error_caught = false;
+	PG_TRY();
+	{
+		bms_singleton_member(bms);
+	}
+	PG_CATCH();
+	{
+		error_caught = true;
+		FlushErrorState();
+	}
+	PG_END_TRY();
+	EXPECT_TRUE(error_caught);
+}
+
+/* Test hash functions and advanced operations */
+static void
+test_advanced_functions(void)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *result = NULL;
+	List	   *int_list = NIL;
+	uint32		hash1,
+				hash2;
+	Bitmapset  *ptr1,
+			   *ptr2;
+
+	elog(NOTICE, "testing advanced functions");
+
+	/* Test hash functions */
+	bms1 = bms_add_member(bms1, 10);
+	bms1 = bms_add_member(bms1, 20);
+	bms2 = bms_add_member(bms2, 10);
+	bms2 = bms_add_member(bms2, 20);
+
+	hash1 = bms_hash_value(bms1);
+	hash2 = bms_hash_value(bms2);
+	EXPECT_EQ_INT(hash1, hash2);
+
+	/* Test bitmap_hash and bitmap_match */
+	ptr1 = bms1;
+	ptr2 = bms2;
+	EXPECT_EQ_INT(bitmap_hash(&ptr1, sizeof(Bitmapset *)),
+				  bitmap_hash(&ptr2, sizeof(Bitmapset *)));
+	EXPECT_EQ_INT(bitmap_match(&ptr1, &ptr2, sizeof(Bitmapset *)), 0);
+
+	/* Test bms_overlap_list */
+	int_list = lappend_int(int_list, 5);
+	int_list = lappend_int(int_list, 10);
+	int_list = lappend_int(int_list, 30);
+
+	EXPECT_TRUE(bms_overlap_list(bms1, int_list));
+	EXPECT_FALSE(bms_overlap_list(NULL, int_list));
+	EXPECT_FALSE(bms_overlap_list(bms1, NIL));
+
+	/* Test bms_add_range */
+	result = bms_add_range(NULL, 5, 8);
+	EXPECT_EQ_INT(bms_num_members(result), 4);	/* 5, 6, 7, 8 */
+	for (int i = 5; i <= 8; i++)
+		EXPECT_TRUE(bms_is_member(i, result));
+	bms_free(result);
+
+	/* Test empty range */
+	result = bms_add_range(NULL, 10, 5);
+	EXPECT_NULL(result);
+
+	/* Test recycling operations */
+	result = bms_add_members(bms1, bms2);
+	EXPECT_TRUE(bms1 == result);	/* bms1 is recycled */
+	EXPECT_EQ_INT(bms_num_members(result), 2);
+
+	result = bms_replace_members(result, bms2);
+	EXPECT_TRUE(bms_equal(result, bms2));
+
+	bms_free(result);			/* which is bms1 */
+	bms_free(bms2);
+	list_free(int_list);
+}
+
+/* Test prev_member edge cases */
+static void
+test_prev_member_edge_cases(void)
+{
+	Bitmapset  *bms = NULL;
+
+	elog(NOTICE, "testing prev_member edge cases");
+
+	/* Test prev_member with -1 on empty set */
+	EXPECT_EQ_INT(bms_prev_member(bms, -1), -2);
+
+	/* Test prev_member with -1 on non-empty set (find highest) */
+	bms = bms_add_member(bms, 100);
+	EXPECT_EQ_INT(bms_prev_member(bms, -1), 100);
+
+	bms_free(bms);
+}
+
+/* Randomized testing similar to test_radixtree.c */
+static void
+test_random_operations(void)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *result = NULL;
+	pg_prng_state state;
+	uint64		seed = GetCurrentTimestamp();
+	int			num_ops = 5000;
+	int			max_range = 2000;
+	int		   *members;
+	int			num_members = 0;
+
+	elog(NOTICE, "testing randomized operations");
+
+	pg_prng_seed(&state, seed);
+	members = palloc(sizeof(int) * num_ops);
+
+	/* Phase 1: Random insertions */
+	for (int i = 0; i < num_ops / 2; i++)
+	{
+		int			member = pg_prng_uint32(&state) % max_range;
+
+		if (!bms_is_member(member, bms1))
+		{
+			members[num_members++] = member;
+			bms1 = bms_add_member(bms1, member);
+		}
+	}
+
+	/* Phase 2: Random set operations */
+	for (int i = 0; i < num_ops / 4; i++)
+	{
+		int			member = pg_prng_uint32(&state) % max_range;
+
+		bms2 = bms_add_member(bms2, member);
+	}
+
+	/* Test union */
+	result = bms_union(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+
+	/* Verify union contains all members from first set */
+	for (int i = 0; i < num_members; i++)
+	{
+		if (!bms_is_member(members[i], result))
+			elog(ERROR, "union missing member %d", members[i]);
+	}
+	bms_free(result);
+
+	/* Test intersection */
+	result = bms_intersect(bms1, bms2);
+	if (result != NULL)
+	{
+		int			member = -1;
+
+		while ((member = bms_next_member(result, member)) >= 0)
+		{
+			if (!bms_is_member(member, bms1) || !bms_is_member(member, bms2))
+				elog(ERROR, "intersection contains invalid member %d", member);
+		}
+		bms_free(result);
+	}
+
+	/* Phase 3: Test range operations */
+	result = NULL;
+	for (int i = 0; i < 5; i++)
+	{
+		int			lower = pg_prng_uint32(&state) % 100;
+		int			upper = lower + (pg_prng_uint32(&state) % 20);
+
+		result = bms_add_range(result, lower, upper);
+	}
+	if (result != NULL)
+	{
+		EXPECT_TRUE(bms_num_members(result) > 0);
+		bms_free(result);
+	}
+
+	/* Cleanup */
+	pfree(members);
+	bms_free(bms1);
+	bms_free(bms2);
+
+	elog(NOTICE, "randomized testing completed successfully");
+}
+
+/* Test empty bitmapset operations */
+static void
+test_empty_bitmapset(void)
+{
+	Bitmapset  *result,
+			   *bms = NULL;
+
+	elog(NOTICE, "testing empty bitmapset operations");
+
+	/* Test operations on NULL bitmapset */
+	EXPECT_TRUE(bms_is_empty(bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 0);
+	EXPECT_FALSE(bms_is_member(0, bms));
+	EXPECT_FALSE(bms_is_member(1, bms));
+	EXPECT_FALSE(bms_is_member(100, bms));
+	EXPECT_EQ_INT(bms_next_member(bms, -1), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, -1), -2);
+
+	/* Test hash of empty set */
+	EXPECT_EQ_INT(bms_hash_value(bms), 0);
+
+	/* Test comparison with empty sets */
+	EXPECT_EQ_INT(bms_compare(bms, NULL), 0);
+
+	/* Test copy of empty set */
+	result = bms_copy(bms);
+	EXPECT_NULL(result);
+
+	/* Test union with empty set */
+	result = bms_union(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test intersection with empty set */
+	result = bms_intersect(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test difference with empty set */
+	result = bms_difference(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test equal comparison */
+	EXPECT_TRUE(bms_equal(bms, NULL));
+	EXPECT_TRUE(bms_equal(NULL, bms));
+
+	/* Test subset operations */
+	EXPECT_TRUE(bms_is_subset(bms, NULL));
+	EXPECT_TRUE(bms_is_subset(NULL, bms));
+
+	/* Test overlap */
+	EXPECT_FALSE(bms_overlap(bms, NULL));
+	EXPECT_FALSE(bms_overlap(NULL, bms));
+}
+
+/* Test single element bitmapset operations */
+static void
+test_single_element(void)
+{
+	Bitmapset  *result,
+			   *bms = NULL;
+	int			test_member = 42;
+
+	elog(NOTICE, "testing single element bitmapset operations");
+
+	/* Add single element */
+	bms = bms_add_member(bms, test_member);
+	EXPECT_NOT_NULL(bms);
+	EXPECT_FALSE(bms_is_empty(bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_TRUE(bms_is_member(test_member, bms));
+	EXPECT_FALSE(bms_is_member(test_member - 1, bms));
+	EXPECT_FALSE(bms_is_member(test_member + 1, bms));
+
+	/* Test iteration */
+	EXPECT_EQ_INT(bms_next_member(bms, -1), test_member);
+	EXPECT_EQ_INT(bms_next_member(bms, test_member), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, test_member + 1), test_member);
+	EXPECT_EQ_INT(bms_prev_member(bms, test_member), -2);
+
+	/* Test copy */
+	result = bms_copy(bms);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_equal(bms, result));
+	EXPECT_TRUE(bms_is_member(test_member, result));
+
+	/* Test member index */
+	EXPECT_EQ_INT(bms_member_index(bms, 42), 0);
+	EXPECT_EQ_INT(bms_member_index(bms, 43), -1);
+
+	/* Test comparison */
+	EXPECT_EQ_INT(bms_compare(bms, result), 0);
+
+	/* Test remove member */
+	result = bms_del_member(result, test_member);
+	EXPECT_NULL(result);
+
+	/* Test comparison again */
+	EXPECT_EQ_INT(bms_compare(bms, result), 1);
+
+	/* Test remove non-existent member */
+	result = bms_copy(bms);
+	EXPECT_NOT_NULL(result);
+	result = bms_del_member(result, test_member + 1);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_equal(bms, result));
+
+	bms_free(bms);
+	bms_free(result);
+}
+
+/* Test multiple elements and set operations */
+static void
+test_multiple_elements(void)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *result = NULL;
+	int			elements1[] = {1, 5, 10, 15, 20, 100};
+	int			elements2[] = {3, 5, 12, 15, 25, 200};
+	int			num_elements1 = sizeof(elements1) / sizeof(elements1[0]);
+	int			num_elements2 = sizeof(elements2) / sizeof(elements2[0]);
+
+	elog(NOTICE, "testing multiple elements and set operations");
+
+	/* Build first set */
+	for (int i = 0; i < num_elements1; i++)
+		bms1 = bms_add_member(bms1, elements1[i]);
+
+	EXPECT_EQ_INT(bms_num_members(bms1), num_elements1);
+
+	/* Build second set */
+	for (int i = 0; i < num_elements2; i++)
+		bms2 = bms_add_member(bms2, elements2[i]);
+
+	EXPECT_EQ_INT(bms_num_members(bms2), num_elements2);
+
+	/* Test membership */
+	for (int i = 0; i < num_elements1; i++)
+		EXPECT_TRUE(bms_is_member(elements1[i], bms1));
+
+	for (int i = 0; i < num_elements2; i++)
+		EXPECT_TRUE(bms_is_member(elements2[i], bms2));
+
+	/* Test union */
+	result = bms_union(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	for (int i = 0; i < num_elements1; i++)
+		EXPECT_TRUE(bms_is_member(elements1[i], result));
+	for (int i = 0; i < num_elements2; i++)
+		EXPECT_TRUE(bms_is_member(elements2[i], result));
+	EXPECT_EQ_INT(bms_num_members(result), 10); /* 1,3,5,10,12,15,20,25,100,200 */
+	bms_free(result);
+
+	/* Test intersection */
+	result = bms_intersect(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_is_member(5, result));
+	EXPECT_TRUE(bms_is_member(15, result));
+	EXPECT_EQ_INT(bms_num_members(result), 2);	/* 5, 15 */
+	bms_free(result);
+
+	/* Test difference */
+	result = bms_difference(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_is_member(1, result));
+	EXPECT_TRUE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(20, result));
+	EXPECT_TRUE(bms_is_member(100, result));
+	EXPECT_FALSE(bms_is_member(5, result));
+	EXPECT_FALSE(bms_is_member(15, result));
+	EXPECT_EQ_INT(bms_num_members(result), 4);	/* 1, 10, 20, 100 */
+	bms_free(result);
+
+	/* Test overlap */
+	EXPECT_TRUE(bms_overlap(bms1, bms2));
+
+	/* Test subset operations */
+	result = NULL;
+	result = bms_add_member(result, 5);
+	result = bms_add_member(result, 15);
+	EXPECT_TRUE(bms_is_subset(result, bms1));
+	EXPECT_TRUE(bms_is_subset(result, bms2));
+	EXPECT_FALSE(bms_is_subset(bms1, result));
+	bms_free(result);
+
+	/* Test subset comparison */
+	bms2 = bms_add_member(NULL, 5);
+	EXPECT_EQ_INT(bms_subset_compare(bms2, bms1), BMS_SUBSET1);
+	EXPECT_EQ_INT(bms_subset_compare(bms1, bms2), BMS_SUBSET2);
+
+	result = bms_add_member(NULL, 999);
+	EXPECT_EQ_INT(bms_subset_compare(bms2, result), BMS_DIFFERENT);
+	bms_free(result);
+
+	bms_free(bms1);
+	bms_free(bms2);
+}
+
+/* Test edge cases and boundary conditions */
+static void
+test_edge_cases(void)
+{
+	int			large_element = 10000;
+	int			count;
+	int			member;
+	Bitmapset  *result;
+	Bitmapset  *bms = NULL;
+
+	elog(NOTICE, "testing edge cases and boundary conditions");
+
+	/* Test element 0 */
+	bms = bms_add_member(bms, 0);
+	EXPECT_TRUE(bms_is_member(0, bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_EQ_INT(bms_next_member(bms, -1), 0);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test large element numbers */
+	bms = bms_add_member(bms, large_element);
+	EXPECT_TRUE(bms_is_member(large_element, bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test adding same element multiple times */
+	bms = bms_add_member(bms, 42);
+	bms = bms_add_member(bms, 42);
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_TRUE(bms_is_member(42, bms));
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test removing from single-element set */
+	bms = bms_add_member(bms, 99);
+	result = bms_del_member(bms, 99);
+	EXPECT_NULL(result);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test dense range */
+	for (int i = 0; i < 64; i++)
+		bms = bms_add_member(bms, i);
+	EXPECT_EQ_INT(bms_num_members(bms), 64);
+
+	/* Test iteration over dense range */
+	count = 0;
+	member = -1;
+	while ((member = bms_next_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, count);
+		count++;
+	}
+	EXPECT_EQ_INT(count, 64);
+
+	bms_free(bms);
+}
+
+/* Test iterator functions */
+static void
+test_iteration(void)
+{
+	Bitmapset  *bms = NULL;
+	int			member;
+	int			index;
+	int			elements[] = {2, 7, 15, 31, 63, 127, 255, 511, 1023};
+	int			num_elements = sizeof(elements) / sizeof(elements[0]);
+
+	elog(NOTICE, "testing iteration functions");
+
+	/* Build test set */
+	for (int i = 0; i < num_elements; i++)
+		bms = bms_add_member(bms, elements[i]);
+
+	/* Test forward iteration */
+	member = -1;
+	index = 0;
+	while ((member = bms_next_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, elements[index]);
+		index++;
+	}
+	EXPECT_EQ_INT(index, num_elements);
+
+	/* Test backward iteration */
+	member = bms->nwords * BITS_PER_BITMAPWORD;
+	index = num_elements - 1;
+	while ((member = bms_prev_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, elements[index]);
+		index--;
+	}
+	EXPECT_EQ_INT(index, -1);
+
+	/* Test iteration bounds */
+	EXPECT_EQ_INT(bms_next_member(bms, 1023), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, 2), -2);
+
+	bms_free(bms);
+}
+
+/* Test set operations with various combinations */
+static void
+test_set_operations(void)
+{
+	Bitmapset  *empty = NULL;
+	Bitmapset  *single = NULL;
+	Bitmapset  *multi = NULL;
+	Bitmapset  *result = NULL;
+	Bitmapset  *single_copy = NULL;
+
+	elog(NOTICE, "testing comprehensive set operations");
+
+	single = bms_make_singleton(10);
+	multi = bms_add_range(multi, 9, 11);
+
+	result = bms_union(single, multi);
+	EXPECT_EQ_INT(bms_num_members(single), 1);
+	EXPECT_EQ_INT(bms_num_members(multi), 3);
+	EXPECT_EQ_INT(bms_num_members(result), 3);
+	EXPECT_TRUE(bms_is_member(9, result));
+	EXPECT_TRUE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(11, result));
+	bms_free(result);
+
+	/* Union operations */
+	result = bms_union(empty, single);
+	EXPECT_TRUE(bms_equal(result, single));
+	bms_free(result);
+
+	result = bms_union(single, empty);
+	EXPECT_TRUE(bms_equal(result, single));
+	bms_free(result);
+
+	/* Intersection operations */
+	result = bms_intersect(empty, single);
+	EXPECT_NULL(result);
+
+	result = bms_intersect(single, multi);
+	EXPECT_EQ_INT(bms_num_members(result), 1);
+	EXPECT_TRUE(bms_is_member(10, result));
+	bms_free(result);
+
+	/* Difference operations */
+	result = bms_difference(single, multi);
+	EXPECT_NULL(result);
+
+	result = bms_difference(multi, single);
+	EXPECT_EQ_INT(bms_num_members(result), 2);
+	EXPECT_TRUE(bms_is_member(9, result));
+	EXPECT_FALSE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(11, result));
+	bms_free(result);
+
+	/* Equality tests */
+	EXPECT_FALSE(bms_equal(single, multi));
+	EXPECT_TRUE(bms_equal(empty, NULL));
+
+	single_copy = bms_copy(single);
+	EXPECT_TRUE(bms_equal(single, single_copy));
+	bms_free(single_copy);
+
+	bms_free(single);
+	bms_free(multi);
+}
+
+/* Main test function */
+Datum
+test_bitmapset(PG_FUNCTION_ARGS)
+{
+	elog(NOTICE, "starting bitmapset tests");
+
+	test_empty_bitmapset();
+	test_single_element();
+	test_multiple_elements();
+	test_error_conditions();
+	test_prev_member_edge_cases();
+	test_edge_cases();
+	test_iteration();
+	test_set_operations();
+	test_random_operations();
+	test_advanced_functions();
+
+	elog(NOTICE, "all bitmapset tests passed");
+
+	PG_RETURN_VOID();
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#11Robert Haas
robertmhaas@gmail.com
In reply to: Greg Burd (#10)
Re: [PATCH] Add tests for Bitmapset

On Mon, Sep 15, 2025 at 2:00 PM Greg Burd <greg@burd.me> wrote:

For reference radixtree has:

coverage: HEAD
lines......: 98.3
functions..: 97.2
branches...: 89.4

+ /* Test negative member in bms_make_singleton */
+ error_caught = false;
+ PG_TRY();
+ {
+ bms_make_singleton(-1);
+ }
+ PG_CATCH();
+ {
+ error_caught = true;
+ FlushErrorState();
+ }
+ PG_END_TRY();
+ EXPECT_TRUE(error_caught);

This is an anti-pattern for PostgreSQL code. You can't just flush an
error without aborting a transaction or subtransaction to recover.
Even if it could be shown that this were harmless here, I think it's a
terrible idea to have code like this in the tree, as it encourages
people to do exactly the wrong thing.

But backing up a step, this also doesn't really seem like the right
way to test the error conditions. It deliberately throws away the
error message. All this verifies is that you caught an error. If you
let the error escape to the client you could have the expected output
test that you got the expected message.

I think it would be a better idea to structure this as a set of
SQL-callable functions and move a bunch of the logic into SQL.

--
Robert Haas
EDB: http://www.enterprisedb.com

#12Greg Burd
greg@burd.me
In reply to: Robert Haas (#11)
Re: [PATCH] Add tests for Bitmapset

On Sep 15 2025, at 2:54 pm, Robert Haas <robertmhaas@gmail.com> wrote:

On Mon, Sep 15, 2025 at 2:00 PM Greg Burd <greg@burd.me> wrote:

For reference radixtree has:

coverage: HEAD
lines......: 98.3
functions..: 97.2
branches...: 89.4

+ /* Test negative member in bms_make_singleton */
+ error_caught = false;
+ PG_TRY();
+ {
+ bms_make_singleton(-1);
+ }
+ PG_CATCH();
+ {
+ error_caught = true;
+ FlushErrorState();
+ }
+ PG_END_TRY();
+ EXPECT_TRUE(error_caught);

This is an anti-pattern for PostgreSQL code. You can't just flush an
error without aborting a transaction or subtransaction to recover.
Even if it could be shown that this were harmless here, I think it's a
terrible idea to have code like this in the tree, as it encourages
people to do exactly the wrong thing.

Fair enough, I'll rework it.

But backing up a step, this also doesn't really seem like the right
way to test the error conditions. It deliberately throws away the
error message. All this verifies is that you caught an error. If you
let the error escape to the client you could have the expected output
test that you got the expected message.

I think it would be a better idea to structure this as a set of
SQL-callable functions and move a bunch of the logic into SQL.

I'll give that approach a try, thanks for the suggestion.

-greg

Show quoted text

--
Robert Haas
EDB: http://www.enterprisedb.com

#13Greg Burd
greg@burd.me
In reply to: Greg Burd (#12)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 15 2025, at 3:03 pm, Greg Burd <greg@burd.me> wrote:

On Sep 15 2025, at 2:54 pm, Robert Haas <robertmhaas@gmail.com> wrote:

On Mon, Sep 15, 2025 at 2:00 PM Greg Burd <greg@burd.me> wrote:

For reference radixtree has:

coverage: HEAD
lines......: 98.3
functions..: 97.2
branches...: 89.4

+ /* Test negative member in bms_make_singleton */
+ error_caught = false;
+ PG_TRY();
+ {
+ bms_make_singleton(-1);
+ }
+ PG_CATCH();
+ {
+ error_caught = true;
+ FlushErrorState();
+ }
+ PG_END_TRY();
+ EXPECT_TRUE(error_caught);

This is an anti-pattern for PostgreSQL code. You can't just flush an
error without aborting a transaction or subtransaction to recover.
Even if it could be shown that this were harmless here, I think it's a
terrible idea to have code like this in the tree, as it encourages
people to do exactly the wrong thing.

Fair enough, I'll rework it.

But backing up a step, this also doesn't really seem like the right
way to test the error conditions. It deliberately throws away the
error message. All this verifies is that you caught an error. If you
let the error escape to the client you could have the expected output
test that you got the expected message.

I think it would be a better idea to structure this as a set of
SQL-callable functions and move a bunch of the logic into SQL.

I'll give that approach a try, thanks for the suggestion.

-greg

Robert,

Reworked as indicated, thanks for pointing out the anti-pattern I'd
missed.

best.

-greg

Show quoted text

--
Robert Haas
EDB: http://www.enterprisedb.com

Attachments:

v3-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From e83b0e7a3d62b14a14c57ab6ce5996efcde38af3 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v3] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |   1 +
 src/test/modules/meson.build                  |   1 +
 src/test/modules/test_bitmapset/.gitignore    |   4 +
 src/test/modules/test_bitmapset/Makefile      |  23 +
 .../expected/test_bitmapset.out               |  46 ++
 src/test/modules/test_bitmapset/meson.build   |  33 +
 .../test_bitmapset/sql/test_bitmapset.sql     |  32 +
 .../test_bitmapset/test_bitmapset--1.0.sql    |  38 +
 .../modules/test_bitmapset/test_bitmapset.c   | 728 ++++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |   4 +
 10 files changed, 910 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..9cc2f9f9552
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,46 @@
+CREATE EXTENSION test_bitmapset;
+--
+-- All the logic is in the test_bitmapset() function. It will throw
+-- an error if something fails.
+--
+-- Run the main comprehensive tests
+SELECT test_bitmapset();
+NOTICE:  starting bitmapset tests
+NOTICE:  testing empty bitmapset operations
+NOTICE:  testing single element bitmapset operations
+NOTICE:  testing multiple elements and set operations
+NOTICE:  testing prev_member edge cases
+NOTICE:  testing edge cases and boundary conditions
+NOTICE:  testing iteration functions
+NOTICE:  testing comprehensive set operations
+NOTICE:  testing randomized operations
+NOTICE:  randomized testing completed successfully
+NOTICE:  testing advanced functions
+NOTICE:  all bitmapset tests passed
+ test_bitmapset 
+----------------
+ 
+(1 row)
+
+-- Test error conditions - these should all fail with specific error messages
+-- Test bms_make_singleton with negative member
+SELECT test_bms_make_singleton_negative(); -- This should ERROR
+ERROR:  negative bitmapset member not allowed
+-- Test bms_is_member with negative member
+SELECT test_bms_is_member_negative(); -- This should ERROR
+ERROR:  negative bitmapset member not allowed
+-- Test bms_add_member with negative member
+SELECT test_bms_add_member_negative(); -- This should ERROR
+ERROR:  negative bitmapset member not allowed
+-- Test bms_del_member with negative member
+SELECT test_bms_del_member_negative(); -- This should ERROR
+ERROR:  negative bitmapset member not allowed
+-- Test bms_add_range with negative lower bound
+SELECT test_bms_add_range_negative(); -- This should ERROR
+ERROR:  negative bitmapset member not allowed
+-- Test bms_singleton_member on empty set
+SELECT test_bms_singleton_member_empty(); -- This should ERROR
+ERROR:  bitmapset is empty
+-- Test bms_singleton_member on multiple member set
+SELECT test_bms_singleton_member_multiple(); -- This should ERROR
+ERROR:  bitmapset has multiple members
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..15b946b1661
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,32 @@
+CREATE EXTENSION test_bitmapset;
+
+--
+-- All the logic is in the test_bitmapset() function. It will throw
+-- an error if something fails.
+--
+
+-- Run the main comprehensive tests
+SELECT test_bitmapset();
+
+-- Test error conditions - these should all fail with specific error messages
+
+-- Test bms_make_singleton with negative member
+SELECT test_bms_make_singleton_negative(); -- This should ERROR
+
+-- Test bms_is_member with negative member
+SELECT test_bms_is_member_negative(); -- This should ERROR
+
+-- Test bms_add_member with negative member
+SELECT test_bms_add_member_negative(); -- This should ERROR
+
+-- Test bms_del_member with negative member
+SELECT test_bms_del_member_negative(); -- This should ERROR
+
+-- Test bms_add_range with negative lower bound
+SELECT test_bms_add_range_negative(); -- This should ERROR
+
+-- Test bms_singleton_member on empty set
+SELECT test_bms_singleton_member_empty(); -- This should ERROR
+
+-- Test bms_singleton_member on multiple member set
+SELECT test_bms_singleton_member_multiple(); -- This should ERROR
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..9f72c1ce2d8
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,38 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+-- Main test function
+CREATE FUNCTION test_bitmapset()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+-- Error condition testing functions
+CREATE FUNCTION test_bms_make_singleton_negative()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_member_negative()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_member_negative()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_del_member_negative()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_range_negative()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_singleton_member_empty()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_singleton_member_multiple()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..3a5469bc6ae
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,728 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include "common/pg_prng.h"
+#include "utils/timestamp.h"
+#include "fmgr.h"
+#include "nodes/pg_list.h"
+#include "nodes/bitmapset.h"
+
+PG_MODULE_MAGIC;
+
+PG_FUNCTION_INFO_V1(test_bitmapset);
+PG_FUNCTION_INFO_V1(test_bms_make_singleton_negative);
+PG_FUNCTION_INFO_V1(test_bms_is_member_negative);
+PG_FUNCTION_INFO_V1(test_bms_add_member_negative);
+PG_FUNCTION_INFO_V1(test_bms_del_member_negative);
+PG_FUNCTION_INFO_V1(test_bms_add_range_negative);
+PG_FUNCTION_INFO_V1(test_bms_singleton_member_empty);
+PG_FUNCTION_INFO_V1(test_bms_singleton_member_multiple);
+
+#define EXPECT_TRUE(expr) \
+    do { \
+	if (!(expr)) \
+	    elog(ERROR, \
+		 "%s was unexpectedly false in file \"%s\" line %u", \
+		 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_FALSE(expr) \
+    do { \
+	if (expr) \
+	    elog(ERROR, \
+		 "%s was unexpectedly true in file \"%s\" line %u", \
+		 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_EQ_INT(result_expr, expected_expr) \
+    do { \
+	int _result = (result_expr); \
+	int _expected = (expected_expr); \
+	if (_result != _expected) \
+	    elog(ERROR, \
+		 "%s yielded %d, expected %d (%s) in file \"%s\" line %u", \
+		 #result_expr, _result, _expected, #expected_expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_NULL(expr) \
+    do { \
+	if ((expr) != NULL) \
+	    elog(ERROR, \
+		 "%s was unexpectedly non-NULL in file \"%s\" line %u", \
+		 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#define EXPECT_NOT_NULL(expr) \
+    do { \
+	if ((expr) == NULL) \
+	    elog(ERROR, \
+		 "%s was unexpectedly NULL in file \"%s\" line %u", \
+		 #expr, __FILE__, __LINE__); \
+    } while (0)
+
+#ifdef DEBUG
+
+static void
+elog_bitmapset(int elevel, const char *label, const Bitmapset *bms)
+{
+	StringInfoData buf;
+	int			member;
+	bool		first = true;
+
+	initStringInfo(&buf);
+
+	if (label)
+		appendStringInfo(&buf, "%s: ", label);
+
+	if (!bms_is_empty(bms))
+	{
+		appendStringInfoChar(&buf, '{');
+		member = -1;
+		while ((member = bms_next_member(bms, member)) >= 0)
+		{
+			if (!first)
+				appendStringInfoString(&buf, ", ");
+			appendStringInfo(&buf, "%d", member);
+			first = false;
+		}
+		appendStringInfoChar(&buf, '}');
+	}
+	else
+		appendStringInfoString(&buf, "EMPTY");
+
+	elog(elevel, "%s", buf.data);
+	pfree(buf.data);
+}
+
+#endif
+
+Datum
+test_bms_make_singleton_negative(PG_FUNCTION_ARGS)
+{
+	/* This should throw an error for negative member */
+	bms_make_singleton(-1);
+	PG_RETURN_VOID();
+}
+
+Datum
+test_bms_is_member_negative(PG_FUNCTION_ARGS)
+{
+	/* This should throw an error for negative member */
+	bms_is_member(-5, NULL);
+	PG_RETURN_VOID();
+}
+
+Datum
+test_bms_add_member_negative(PG_FUNCTION_ARGS)
+{
+	/* This should throw an error for negative member */
+	bms_add_member(NULL, -10);
+	PG_RETURN_VOID();
+}
+
+Datum
+test_bms_del_member_negative(PG_FUNCTION_ARGS)
+{
+	/* This should throw an error for negative member */
+	bms_del_member(NULL, -20);
+	PG_RETURN_VOID();
+}
+
+Datum
+test_bms_add_range_negative(PG_FUNCTION_ARGS)
+{
+	/* This should throw an error for negative lower bound */
+	bms_add_range(NULL, -5, 10);
+	PG_RETURN_VOID();
+}
+
+Datum
+test_bms_singleton_member_empty(PG_FUNCTION_ARGS)
+{
+	/* This should throw an error for empty set */
+	bms_singleton_member(NULL);
+	PG_RETURN_VOID();
+}
+
+Datum
+test_bms_singleton_member_multiple(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+
+	/* Create a set with multiple members */
+	bms = bms_add_member(bms, 1);
+	bms = bms_add_member(bms, 2);
+
+	/* This should throw an error for multiple members */
+	bms_singleton_member(bms);
+
+	bms_free(bms);
+	PG_RETURN_VOID();
+}
+
+
+/* Test hash functions and advanced operations */
+static void
+test_advanced_functions(void)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *result = NULL;
+	List	   *int_list = NIL;
+	uint32		hash1,
+				hash2;
+	Bitmapset  *ptr1,
+			   *ptr2;
+
+	elog(NOTICE, "testing advanced functions");
+
+	/* Test hash functions */
+	bms1 = bms_add_member(bms1, 10);
+	bms1 = bms_add_member(bms1, 20);
+	bms2 = bms_add_member(bms2, 10);
+	bms2 = bms_add_member(bms2, 20);
+
+	hash1 = bms_hash_value(bms1);
+	hash2 = bms_hash_value(bms2);
+	EXPECT_EQ_INT(hash1, hash2);
+
+	/* Test bitmap_hash and bitmap_match */
+	ptr1 = bms1;
+	ptr2 = bms2;
+	EXPECT_EQ_INT(bitmap_hash(&ptr1, sizeof(Bitmapset *)),
+				  bitmap_hash(&ptr2, sizeof(Bitmapset *)));
+	EXPECT_EQ_INT(bitmap_match(&ptr1, &ptr2, sizeof(Bitmapset *)), 0);
+
+	/* Test bms_overlap_list */
+	int_list = lappend_int(int_list, 5);
+	int_list = lappend_int(int_list, 10);
+	int_list = lappend_int(int_list, 30);
+
+	EXPECT_TRUE(bms_overlap_list(bms1, int_list));
+	EXPECT_FALSE(bms_overlap_list(NULL, int_list));
+	EXPECT_FALSE(bms_overlap_list(bms1, NIL));
+
+	/* Test bms_add_range */
+	result = bms_add_range(NULL, 5, 8);
+	EXPECT_EQ_INT(bms_num_members(result), 4);	/* 5, 6, 7, 8 */
+	for (int i = 5; i <= 8; i++)
+		EXPECT_TRUE(bms_is_member(i, result));
+	bms_free(result);
+
+	/* Test empty range */
+	result = bms_add_range(NULL, 10, 5);
+	EXPECT_NULL(result);
+
+	/* Test recycling operations */
+	result = bms_add_members(bms1, bms2);
+	EXPECT_TRUE(bms1 == result);	/* bms1 is recycled */
+	EXPECT_EQ_INT(bms_num_members(result), 2);
+
+	result = bms_replace_members(result, bms2);
+	EXPECT_TRUE(bms_equal(result, bms2));
+
+	bms_free(result);			/* which is bms1 */
+	bms_free(bms2);
+	list_free(int_list);
+}
+
+/* Test prev_member edge cases */
+static void
+test_prev_member_edge_cases(void)
+{
+	Bitmapset  *bms = NULL;
+
+	elog(NOTICE, "testing prev_member edge cases");
+
+	/* Test prev_member with -1 on empty set */
+	EXPECT_EQ_INT(bms_prev_member(bms, -1), -2);
+
+	/* Test prev_member with -1 on non-empty set (find highest) */
+	bms = bms_add_member(bms, 100);
+	EXPECT_EQ_INT(bms_prev_member(bms, -1), 100);
+
+	bms_free(bms);
+}
+
+/* Randomized testing similar to test_radixtree.c */
+static void
+test_random_operations(void)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *result = NULL;
+	pg_prng_state state;
+	uint64		seed = GetCurrentTimestamp();
+	int			num_ops = 5000;
+	int			max_range = 2000;
+	int		   *members;
+	int			num_members = 0;
+
+	elog(NOTICE, "testing randomized operations");
+
+	pg_prng_seed(&state, seed);
+	members = palloc(sizeof(int) * num_ops);
+
+	/* Phase 1: Random insertions */
+	for (int i = 0; i < num_ops / 2; i++)
+	{
+		int			member = pg_prng_uint32(&state) % max_range;
+
+		if (!bms_is_member(member, bms1))
+		{
+			members[num_members++] = member;
+			bms1 = bms_add_member(bms1, member);
+		}
+	}
+
+	/* Phase 2: Random set operations */
+	for (int i = 0; i < num_ops / 4; i++)
+	{
+		int			member = pg_prng_uint32(&state) % max_range;
+
+		bms2 = bms_add_member(bms2, member);
+	}
+
+	/* Test union */
+	result = bms_union(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+
+	/* Verify union contains all members from first set */
+	for (int i = 0; i < num_members; i++)
+	{
+		if (!bms_is_member(members[i], result))
+			elog(ERROR, "union missing member %d", members[i]);
+	}
+	bms_free(result);
+
+	/* Test intersection */
+	result = bms_intersect(bms1, bms2);
+	if (result != NULL)
+	{
+		int			member = -1;
+
+		while ((member = bms_next_member(result, member)) >= 0)
+		{
+			if (!bms_is_member(member, bms1) || !bms_is_member(member, bms2))
+				elog(ERROR, "intersection contains invalid member %d", member);
+		}
+		bms_free(result);
+	}
+
+	/* Phase 3: Test range operations */
+	result = NULL;
+	for (int i = 0; i < 5; i++)
+	{
+		int			lower = pg_prng_uint32(&state) % 100;
+		int			upper = lower + (pg_prng_uint32(&state) % 20);
+
+		result = bms_add_range(result, lower, upper);
+	}
+	if (result != NULL)
+	{
+		EXPECT_TRUE(bms_num_members(result) > 0);
+		bms_free(result);
+	}
+
+	/* Cleanup */
+	pfree(members);
+	bms_free(bms1);
+	bms_free(bms2);
+
+	elog(NOTICE, "randomized testing completed successfully");
+}
+
+/* Test empty bitmapset operations */
+static void
+test_empty_bitmapset(void)
+{
+	Bitmapset  *result,
+			   *bms = NULL;
+
+	elog(NOTICE, "testing empty bitmapset operations");
+
+	/* Test operations on NULL bitmapset */
+	EXPECT_TRUE(bms_is_empty(bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 0);
+	EXPECT_FALSE(bms_is_member(0, bms));
+	EXPECT_FALSE(bms_is_member(1, bms));
+	EXPECT_FALSE(bms_is_member(100, bms));
+	EXPECT_EQ_INT(bms_next_member(bms, -1), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, -1), -2);
+
+	/* Test hash of empty set */
+	EXPECT_EQ_INT(bms_hash_value(bms), 0);
+
+	/* Test comparison with empty sets */
+	EXPECT_EQ_INT(bms_compare(bms, NULL), 0);
+
+	/* Test copy of empty set */
+	result = bms_copy(bms);
+	EXPECT_NULL(result);
+
+	/* Test union with empty set */
+	result = bms_union(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test intersection with empty set */
+	result = bms_intersect(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test difference with empty set */
+	result = bms_difference(bms, NULL);
+	EXPECT_NULL(result);
+
+	/* Test equal comparison */
+	EXPECT_TRUE(bms_equal(bms, NULL));
+	EXPECT_TRUE(bms_equal(NULL, bms));
+
+	/* Test subset operations */
+	EXPECT_TRUE(bms_is_subset(bms, NULL));
+	EXPECT_TRUE(bms_is_subset(NULL, bms));
+
+	/* Test overlap */
+	EXPECT_FALSE(bms_overlap(bms, NULL));
+	EXPECT_FALSE(bms_overlap(NULL, bms));
+}
+
+/* Test single element bitmapset operations */
+static void
+test_single_element(void)
+{
+	Bitmapset  *result,
+			   *bms = NULL;
+	int			test_member = 42;
+
+	elog(NOTICE, "testing single element bitmapset operations");
+
+	/* Add single element */
+	bms = bms_add_member(bms, test_member);
+	EXPECT_NOT_NULL(bms);
+	EXPECT_FALSE(bms_is_empty(bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_TRUE(bms_is_member(test_member, bms));
+	EXPECT_FALSE(bms_is_member(test_member - 1, bms));
+	EXPECT_FALSE(bms_is_member(test_member + 1, bms));
+
+	/* Test iteration */
+	EXPECT_EQ_INT(bms_next_member(bms, -1), test_member);
+	EXPECT_EQ_INT(bms_next_member(bms, test_member), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, test_member + 1), test_member);
+	EXPECT_EQ_INT(bms_prev_member(bms, test_member), -2);
+
+	/* Test copy */
+	result = bms_copy(bms);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_equal(bms, result));
+	EXPECT_TRUE(bms_is_member(test_member, result));
+
+	/* Test member index */
+	EXPECT_EQ_INT(bms_member_index(bms, 42), 0);
+	EXPECT_EQ_INT(bms_member_index(bms, 43), -1);
+
+	/* Test comparison */
+	EXPECT_EQ_INT(bms_compare(bms, result), 0);
+
+	/* Test remove member */
+	result = bms_del_member(result, test_member);
+	EXPECT_NULL(result);
+
+	/* Test comparison again */
+	EXPECT_EQ_INT(bms_compare(bms, result), 1);
+
+	/* Test remove non-existent member */
+	result = bms_copy(bms);
+	EXPECT_NOT_NULL(result);
+	result = bms_del_member(result, test_member + 1);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_equal(bms, result));
+
+	bms_free(bms);
+	bms_free(result);
+}
+
+/* Test multiple elements and set operations */
+static void
+test_multiple_elements(void)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *result = NULL;
+	int			elements1[] = {1, 5, 10, 15, 20, 100};
+	int			elements2[] = {3, 5, 12, 15, 25, 200};
+	int			num_elements1 = sizeof(elements1) / sizeof(elements1[0]);
+	int			num_elements2 = sizeof(elements2) / sizeof(elements2[0]);
+
+	elog(NOTICE, "testing multiple elements and set operations");
+
+	/* Build first set */
+	for (int i = 0; i < num_elements1; i++)
+		bms1 = bms_add_member(bms1, elements1[i]);
+
+	EXPECT_EQ_INT(bms_num_members(bms1), num_elements1);
+
+	/* Build second set */
+	for (int i = 0; i < num_elements2; i++)
+		bms2 = bms_add_member(bms2, elements2[i]);
+
+	EXPECT_EQ_INT(bms_num_members(bms2), num_elements2);
+
+	/* Test membership */
+	for (int i = 0; i < num_elements1; i++)
+		EXPECT_TRUE(bms_is_member(elements1[i], bms1));
+
+	for (int i = 0; i < num_elements2; i++)
+		EXPECT_TRUE(bms_is_member(elements2[i], bms2));
+
+	/* Test union */
+	result = bms_union(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	for (int i = 0; i < num_elements1; i++)
+		EXPECT_TRUE(bms_is_member(elements1[i], result));
+	for (int i = 0; i < num_elements2; i++)
+		EXPECT_TRUE(bms_is_member(elements2[i], result));
+	EXPECT_EQ_INT(bms_num_members(result), 10); /* 1,3,5,10,12,15,20,25,100,200 */
+	bms_free(result);
+
+	/* Test intersection */
+	result = bms_intersect(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_is_member(5, result));
+	EXPECT_TRUE(bms_is_member(15, result));
+	EXPECT_EQ_INT(bms_num_members(result), 2);	/* 5, 15 */
+	bms_free(result);
+
+	/* Test difference */
+	result = bms_difference(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+	EXPECT_TRUE(bms_is_member(1, result));
+	EXPECT_TRUE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(20, result));
+	EXPECT_TRUE(bms_is_member(100, result));
+	EXPECT_FALSE(bms_is_member(5, result));
+	EXPECT_FALSE(bms_is_member(15, result));
+	EXPECT_EQ_INT(bms_num_members(result), 4);	/* 1, 10, 20, 100 */
+	bms_free(result);
+
+	/* Test overlap */
+	EXPECT_TRUE(bms_overlap(bms1, bms2));
+
+	/* Test subset operations */
+	result = NULL;
+	result = bms_add_member(result, 5);
+	result = bms_add_member(result, 15);
+	EXPECT_TRUE(bms_is_subset(result, bms1));
+	EXPECT_TRUE(bms_is_subset(result, bms2));
+	EXPECT_FALSE(bms_is_subset(bms1, result));
+	bms_free(result);
+
+	/* Test subset comparison */
+	bms2 = bms_add_member(NULL, 5);
+	EXPECT_EQ_INT(bms_subset_compare(bms2, bms1), BMS_SUBSET1);
+	EXPECT_EQ_INT(bms_subset_compare(bms1, bms2), BMS_SUBSET2);
+
+	result = bms_add_member(NULL, 999);
+	EXPECT_EQ_INT(bms_subset_compare(bms2, result), BMS_DIFFERENT);
+	bms_free(result);
+
+	bms_free(bms1);
+	bms_free(bms2);
+}
+
+/* Test edge cases and boundary conditions */
+static void
+test_edge_cases(void)
+{
+	int			large_element = 10000;
+	int			count;
+	int			member;
+	Bitmapset  *result;
+	Bitmapset  *bms = NULL;
+
+	elog(NOTICE, "testing edge cases and boundary conditions");
+
+	/* Test element 0 */
+	bms = bms_add_member(bms, 0);
+	EXPECT_TRUE(bms_is_member(0, bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_EQ_INT(bms_next_member(bms, -1), 0);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test large element numbers */
+	bms = bms_add_member(bms, large_element);
+	EXPECT_TRUE(bms_is_member(large_element, bms));
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test adding same element multiple times */
+	bms = bms_add_member(bms, 42);
+	bms = bms_add_member(bms, 42);
+	EXPECT_EQ_INT(bms_num_members(bms), 1);
+	EXPECT_TRUE(bms_is_member(42, bms));
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test removing from single-element set */
+	bms = bms_add_member(bms, 99);
+	result = bms_del_member(bms, 99);
+	EXPECT_NULL(result);
+	bms_free(bms);
+	bms = NULL;
+
+	/* Test dense range */
+	for (int i = 0; i < 64; i++)
+		bms = bms_add_member(bms, i);
+	EXPECT_EQ_INT(bms_num_members(bms), 64);
+
+	/* Test iteration over dense range */
+	count = 0;
+	member = -1;
+	while ((member = bms_next_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, count);
+		count++;
+	}
+	EXPECT_EQ_INT(count, 64);
+
+	bms_free(bms);
+}
+
+/* Test iterator functions */
+static void
+test_iteration(void)
+{
+	Bitmapset  *bms = NULL;
+	int			member;
+	int			index;
+	int			elements[] = {2, 7, 15, 31, 63, 127, 255, 511, 1023};
+	int			num_elements = sizeof(elements) / sizeof(elements[0]);
+
+	elog(NOTICE, "testing iteration functions");
+
+	/* Build test set */
+	for (int i = 0; i < num_elements; i++)
+		bms = bms_add_member(bms, elements[i]);
+
+	/* Test forward iteration */
+	member = -1;
+	index = 0;
+	while ((member = bms_next_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, elements[index]);
+		index++;
+	}
+	EXPECT_EQ_INT(index, num_elements);
+
+	/* Test backward iteration */
+	member = bms->nwords * BITS_PER_BITMAPWORD;
+	index = num_elements - 1;
+	while ((member = bms_prev_member(bms, member)) >= 0)
+	{
+		EXPECT_EQ_INT(member, elements[index]);
+		index--;
+	}
+	EXPECT_EQ_INT(index, -1);
+
+	/* Test iteration bounds */
+	EXPECT_EQ_INT(bms_next_member(bms, 1023), -2);
+	EXPECT_EQ_INT(bms_prev_member(bms, 2), -2);
+
+	bms_free(bms);
+}
+
+/* Test set operations with various combinations */
+static void
+test_set_operations(void)
+{
+	Bitmapset  *empty = NULL;
+	Bitmapset  *single = NULL;
+	Bitmapset  *multi = NULL;
+	Bitmapset  *result = NULL;
+	Bitmapset  *single_copy = NULL;
+
+	elog(NOTICE, "testing comprehensive set operations");
+
+	single = bms_make_singleton(10);
+	multi = bms_add_range(multi, 9, 11);
+
+	result = bms_union(single, multi);
+	EXPECT_EQ_INT(bms_num_members(single), 1);
+	EXPECT_EQ_INT(bms_num_members(multi), 3);
+	EXPECT_EQ_INT(bms_num_members(result), 3);
+	EXPECT_TRUE(bms_is_member(9, result));
+	EXPECT_TRUE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(11, result));
+	bms_free(result);
+
+	/* Union operations */
+	result = bms_union(empty, single);
+	EXPECT_TRUE(bms_equal(result, single));
+	bms_free(result);
+
+	result = bms_union(single, empty);
+	EXPECT_TRUE(bms_equal(result, single));
+	bms_free(result);
+
+	/* Intersection operations */
+	result = bms_intersect(empty, single);
+	EXPECT_NULL(result);
+
+	result = bms_intersect(single, multi);
+	EXPECT_EQ_INT(bms_num_members(result), 1);
+	EXPECT_TRUE(bms_is_member(10, result));
+	bms_free(result);
+
+	/* Difference operations */
+	result = bms_difference(single, multi);
+	EXPECT_NULL(result);
+
+	result = bms_difference(multi, single);
+	EXPECT_EQ_INT(bms_num_members(result), 2);
+	EXPECT_TRUE(bms_is_member(9, result));
+	EXPECT_FALSE(bms_is_member(10, result));
+	EXPECT_TRUE(bms_is_member(11, result));
+	bms_free(result);
+
+	/* Equality tests */
+	EXPECT_FALSE(bms_equal(single, multi));
+	EXPECT_TRUE(bms_equal(empty, NULL));
+
+	single_copy = bms_copy(single);
+	EXPECT_TRUE(bms_equal(single, single_copy));
+	bms_free(single_copy);
+
+	bms_free(single);
+	bms_free(multi);
+}
+
+/* Main test function */
+Datum
+test_bitmapset(PG_FUNCTION_ARGS)
+{
+	elog(NOTICE, "starting bitmapset tests");
+
+	test_empty_bitmapset();
+	test_single_element();
+	test_multiple_elements();
+	test_prev_member_edge_cases();
+	test_edge_cases();
+	test_iteration();
+	test_set_operations();
+	test_random_operations();
+	test_advanced_functions();
+
+	elog(NOTICE, "all bitmapset tests passed");
+
+	PG_RETURN_VOID();
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#14Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#13)
Re: [PATCH] Add tests for Bitmapset

On Mon, Sep 15, 2025 at 03:56:30PM -0400, Greg Burd wrote:

Reworked as indicated, thanks for pointing out the anti-pattern I'd
missed.

Hmm. Should we try to get something closer in shape to what we do for
the SLRU tests, with one SQL function mapping to each C function we
are testing? This counts for bms_is_member(), bms_num_members(), add,
del, mul, hash and make_singleton.

+test_bms_del_member_negative(PG_FUNCTION_ARGS)
+{
+	/* This should throw an error for negative member */
+	bms_del_member(NULL, -20);
+	PG_RETURN_VOID();

For example, this case could use a Bitmapset and a number (or an array
of numbers for repeated operations), with NULL being one option for
the input Bitmapset. This makes the tests a bit more representative
of what they do at SQL level, hence there would be no need to
double-check a given line where a failure happens. The Bitmapset
could then be passed around as bytea blobs using \gset, for example.
This should not be a problem as long as they are palloc'd in the
TopMemoryContext. The SQL output for true/false/NULL/non-NULL
generated as output of the test could then be used instead of the
EXPECT_*() macros reported then in the elogs.

Perhaps my view of things is too cute and artistic, but when these
test suites grow over time and differ across branches, having to dig
into a specific line of a specific branch to get what a problem is
about is more error-prone. Particularly annoying when calling one
single function that does a lot of various actions, like the proposed
test_bitmapset().

Side note: `git diff --check` is reporting a bunch of indents with
spaces around the EXPECT macros.
--
Michael

#15Robert Haas
robertmhaas@gmail.com
In reply to: Michael Paquier (#14)
Re: [PATCH] Add tests for Bitmapset

On Tue, Sep 16, 2025 at 2:04 AM Michael Paquier <michael@paquier.xyz> wrote:

one SQL function mapping to each C function we are testing?

Yes, I think we should do this, if possible.

--
Robert Haas
EDB: http://www.enterprisedb.com

#16Greg Burd
greg@burd.me
In reply to: Robert Haas (#15)
Re: [PATCH] Add tests for Bitmapset

On Sep 16 2025, at 8:02 am, Robert Haas <robertmhaas@gmail.com> wrote:

On Tue, Sep 16, 2025 at 2:04 AM Michael Paquier <michael@paquier.xyz> wrote:

one SQL function mapping to each C function we are testing?

Yes, I think we should do this, if possible.

Michael, Robert,

Thanks for your time reviewing the proposed code and for providing
feedback. This patch started life as simply copy of the test_radixtree
module which uses a single test function triggered in SQL, hence my
approach. I guess I should have copied the test_slru module instead! :)

I see the value in the idea of splitting it up into separate functions
and I'll give that a try.

Michael, apologies for the white space issues. I'll clean that up, and
thank you for the `git diff --check` tip, I'll add that to my toolbox/routine.

--
Robert Haas
EDB: http://www.enterprisedb.com

best.

-greg

#17Greg Burd
greg@burd.me
In reply to: Greg Burd (#16)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

I've re-written the set of tests as suggested (I hope!). I've not
re-run the coverage report (yet) to ensure we're at least as well
covered as v3, but attached is v4 for your inspection (amusement?).
I've tried to author the SQL tests such that failures clearly indicate
what's at gone wrong.

This exercise turned into a lot more LOC than I'd expected, I hope it
provides some value to the community for testing this important data
structure and helps to codify the API clearly.

best.

-greg

Attachments:

v4-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From ca0461d7f08e9c431d72cd5f5018c3a0acb9e09f Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v4] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |    1 +
 src/test/modules/meson.build                  |    1 +
 src/test/modules/test_bitmapset/.gitignore    |    4 +
 src/test/modules/test_bitmapset/Makefile      |   23 +
 .../expected/test_bitmapset.out               |  635 +++++++++
 src/test/modules/test_bitmapset/meson.build   |   33 +
 .../test_bitmapset/sql/test_bitmapset.sql     |  402 ++++++
 .../test_bitmapset/test_bitmapset--1.0.sql    |  151 +++
 .../modules/test_bitmapset/test_bitmapset.c   | 1204 +++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |    4 +
 10 files changed, 2458 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..549c28895a1
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,635 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+-- BASIC FUNCTIONALITY TESTS
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+           test           | result 
+--------------------------+--------
+ NULL input to from_array | t
+(1 row)
+
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+           test            | result 
+---------------------------+--------
+ Empty array to from_array | t
+(1 row)
+
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+          test          | result 
+------------------------+--------
+ NULL input to to_array | t
+(1 row)
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+        test        | result 
+--------------------+--------
+ make_singleton(42) | t
+(1 row)
+
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+       test        | result 
+-------------------+--------
+ make_singleton(0) | t
+(1 row)
+
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+         test         | result 
+----------------------+--------
+ make_singleton(1000) | t
+(1 row)
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+         test         | result 
+----------------------+--------
+ add_member(NULL, 10) | t
+(1 row)
+
+SELECT 'add_member consistency' as test, test_bms_add_member(NULL, 10) = test_bms_make_singleton(10) as result;
+          test          | result 
+------------------------+--------
+ add_member consistency | t
+(1 row)
+
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+          test          | result 
+------------------------+--------
+ add_member to existing | t
+(1 row)
+
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+       test        | result 
+-------------------+--------
+ add_member sorted | t
+(1 row)
+
+SELECT 'add_member idempotent' as test, test_bms_add_member(test_bms_make_singleton(10), 10) = test_bms_make_singleton(10) as result;
+         test          | result 
+-----------------------+--------
+ add_member idempotent | t
+(1 row)
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+         test         | result 
+----------------------+--------
+ del_member from NULL | t
+(1 row)
+
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+                test                | result 
+------------------------------------+--------
+ del_member singleton becomes empty | t
+(1 row)
+
+SELECT 'del_member no change' as test, test_bms_del_member(test_bms_make_singleton(10), 5) = test_bms_make_singleton(10) as result;
+         test         | result 
+----------------------+--------
+ del_member no change | t
+(1 row)
+
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+          test          | result 
+------------------------+--------
+ del_member from middle | t
+(1 row)
+
+-- SET OPERATIONS TESTS
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+          test          | result 
+------------------------+--------
+ union overlapping sets | t
+ union with NULL        | t
+ union NULL with NULL   | t
+(3 rows)
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+            test            | result 
+----------------------------+--------
+ intersect overlapping sets | t
+ intersect disjoint sets    | t
+ intersect with NULL        | t
+(3 rows)
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+            test             | result 
+-----------------------------+--------
+ difference overlapping sets | t
+ difference disjoint sets    | t
+ difference identical sets   | t
+(3 rows)
+
+-- MEMBERSHIP AND COMPARISON TESTS
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+           test            | result 
+---------------------------+--------
+ is_member existing        | t
+ is_member missing         | t
+ is_member existing middle | t
+ is_member NULL set        | t
+(4 rows)
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ num_members NULL | t
+(1 row)
+
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+         test          | result 
+-----------------------+--------
+ num_members small set | t
+(1 row)
+
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+          test          | result 
+------------------------+--------
+ num_members larger set | t
+(1 row)
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+          test           | result 
+-------------------------+--------
+ equal NULL NULL         | t
+ equal NULL set          | t
+ equal set NULL          | t
+ equal identical sets    | t
+ equal different sets    | t
+ compare NULL NULL       | t
+ compare NULL set        | t
+ compare set NULL        | t
+ compare equal sets      | t
+ compare subset superset | t
+ compare superset subset | t
+(11 rows)
+
+-- ADVANCED OPERATIONS TESTS
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+      test       | result 
+-----------------+--------
+ add_range basic | t
+(1 row)
+
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+           test           | result 
+--------------------------+--------
+ add_range single element | t
+(1 row)
+
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+         test          | result 
+-----------------------+--------
+ add_range to existing | t
+(1 row)
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ membership empty | t
+(1 row)
+
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+         test         | result 
+----------------------+--------
+ membership singleton | t
+(1 row)
+
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+        test         | result 
+---------------------+--------
+ membership multiple | t
+(1 row)
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+          test          | result 
+------------------------+--------
+ singleton_member valid | t
+(1 row)
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+            test            | result 
+----------------------------+--------
+ next_member first          | t
+ next_member second         | t
+ next_member past end       | t
+ next_member empty set      | t
+ prev_member last           | t
+ prev_member penultimate    | t
+ prev_member past beginning | t
+ prev_member empty set      | t
+(8 rows)
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_c
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_a) = test_bms_hash_value(set_b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_a) != test_bms_hash_value(set_c) as result FROM test_sets;
+        test         | result 
+---------------------+--------
+ hash NULL           | t
+ hash consistency    | t
+ hash different sets | t
+(3 rows)
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+       test        | result 
+-------------------+--------
+ overlap existing  | t
+ overlap none      | t
+ overlap with NULL | t
+(3 rows)
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets;
+             test             | result 
+------------------------------+--------
+ subset NULL is subset of all | t
+ subset proper subset         | t
+ subset improper subset       | t
+ subset disjoint sets         | t
+(4 rows)
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+     test      | result 
+---------------+--------
+ copy NULL     | t
+ copy equality | t
+(2 rows)
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+         test          | result 
+-----------------------+--------
+ add_members operation | 
+(1 row)
+
+-- Test 20: Test hash consistency
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+             test              | result 
+-------------------------------+--------
+ bitmap_hash NULL              | t
+ bitmap_hash consistency       | t
+ bitmap_hash vs bms_hash_value | t
+ bitmap_hash different sets    | t
+(4 rows)
+
+SELECT 'bitmap_hash [1,3,5]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[1,3,5])) as hash_value;
+        test         | hash_value 
+---------------------+------------
+ bitmap_hash [1,3,5] |   49870778
+(1 row)
+
+SELECT 'bitmap_hash [2,4,6]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[2,4,6])) as hash_value;
+        test         | hash_value 
+---------------------+------------
+ bitmap_hash [2,4,6] | -303921606
+(1 row)
+
+-- Test 21: bitmap_match function
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match NULL NULL (should be 0)       | t
+ bitmap_match NULL set (should be 1)        | t
+ bitmap_match set NULL (should be 1)        | t
+ bitmap_match identical sets (should be 0)  | t
+ bitmap_match different sets (should be 1)  | t
+ bitmap_match subset/superset (should be 1) | t
+(6 rows)
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match vs bms_equal (equal sets)     | t
+ bitmap_match vs bms_equal (different sets) | t
+ bitmap_match vs bms_equal (NULL cases)     | t
+(3 rows)
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [1,3,5] |           0
+(1 row)
+
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [2,4,6] |           1
+(1 row)
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+           test            | result 
+---------------------------+--------
+ bitmap_match empty arrays | t
+(1 row)
+
+-- Test 22: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(12345, 1000) > 0 as result;
+       test        | result 
+-------------------+--------
+ random operations | t
+(1 row)
+
+-- ERROR CONDITION TESTS
+-- Test 23: Error conditions (these should produce ERRORs)
+-- Negative member tests
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_make_singleton(-1);
+	RAISE NOTICE 'ERROR: make_singleton(-1) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: make_singleton(-1) correctly errored: %', SQLERRM;
+    END;
+END $$;
+NOTICE:  SUCCESS: make_singleton(-1) correctly errored: negative bitmapset member not allowed
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_is_member(NULL, -5);
+	RAISE NOTICE 'ERROR: is_member(NULL, -5) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: is_member(NULL, -5) correctly errored: %', SQLERRM;
+    END;
+END $$;
+NOTICE:  SUCCESS: is_member(NULL, -5) correctly errored: negative bitmapset member not allowed
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_add_member(NULL, -10);
+	RAISE NOTICE 'ERROR: add_member(NULL, -10) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: add_member(NULL, -10) correctly errored: %', SQLERRM;
+    END;
+END $$;
+NOTICE:  SUCCESS: add_member(NULL, -10) correctly errored: negative bitmapset member not allowed
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_del_member(NULL, -20);
+	RAISE NOTICE 'ERROR: del_member(NULL, -20) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: del_member(NULL, -20) correctly errored: %', SQLERRM;
+    END;
+END $$;
+NOTICE:  SUCCESS: del_member(NULL, -20) correctly errored: negative bitmapset member not allowed
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_add_range(NULL, -5, 10);
+	RAISE NOTICE 'ERROR: add_range(NULL, -5, 10) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: add_range(NULL, -5, 10) correctly errored: %', SQLERRM;
+    END;
+END $$;
+NOTICE:  SUCCESS: add_range(NULL, -5, 10) correctly errored: negative bitmapset member not allowed
+-- Singleton member errors
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_singleton_member(NULL);
+	RAISE NOTICE 'ERROR: singleton_member(NULL) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: singleton_member(NULL) correctly errored: %', SQLERRM;
+    END;
+END $$;
+NOTICE:  ERROR: singleton_member(NULL) should have failed!
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+	RAISE NOTICE 'ERROR: singleton_member([1,2]) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: singleton_member([1,2]) correctly errored: %', SQLERRM;
+    END;
+END $$;
+NOTICE:  SUCCESS: singleton_member([1,2]) correctly errored: bitmapset has multiple members
+-- Look for "result | f" entries which indicate test failures.
+-- Error condition tests should show "SUCCESS:" messages.
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..8b0b0ca1b4a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,402 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+
+-- BASIC FUNCTIONALITY TESTS
+
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+SELECT 'add_member consistency' as test, test_bms_add_member(NULL, 10) = test_bms_make_singleton(10) as result;
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+SELECT 'add_member idempotent' as test, test_bms_add_member(test_bms_make_singleton(10), 10) = test_bms_make_singleton(10) as result;
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+SELECT 'del_member no change' as test, test_bms_del_member(test_bms_make_singleton(10), 5) = test_bms_make_singleton(10) as result;
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+
+-- SET OPERATIONS TESTS
+
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+
+-- MEMBERSHIP AND COMPARISON TESTS
+
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+
+-- ADVANCED OPERATIONS TESTS
+
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_c
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_a) = test_bms_hash_value(set_b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_a) != test_bms_hash_value(set_c) as result FROM test_sets;
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets;
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+
+-- Test 20: Test hash consistency
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+
+SELECT 'bitmap_hash [1,3,5]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[1,3,5])) as hash_value;
+SELECT 'bitmap_hash [2,4,6]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[2,4,6])) as hash_value;
+
+-- Test 21: bitmap_match function
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+
+-- Test 22: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(12345, 1000) > 0 as result;
+
+-- ERROR CONDITION TESTS
+
+-- Test 23: Error conditions (these should produce ERRORs)
+
+-- Negative member tests
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_make_singleton(-1);
+	RAISE NOTICE 'ERROR: make_singleton(-1) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: make_singleton(-1) correctly errored: %', SQLERRM;
+    END;
+END $$;
+
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_is_member(NULL, -5);
+	RAISE NOTICE 'ERROR: is_member(NULL, -5) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: is_member(NULL, -5) correctly errored: %', SQLERRM;
+    END;
+END $$;
+
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_add_member(NULL, -10);
+	RAISE NOTICE 'ERROR: add_member(NULL, -10) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: add_member(NULL, -10) correctly errored: %', SQLERRM;
+    END;
+END $$;
+
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_del_member(NULL, -20);
+	RAISE NOTICE 'ERROR: del_member(NULL, -20) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: del_member(NULL, -20) correctly errored: %', SQLERRM;
+    END;
+END $$;
+
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_add_range(NULL, -5, 10);
+	RAISE NOTICE 'ERROR: add_range(NULL, -5, 10) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: add_range(NULL, -5, 10) correctly errored: %', SQLERRM;
+    END;
+END $$;
+
+-- Singleton member errors
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_singleton_member(NULL);
+	RAISE NOTICE 'ERROR: singleton_member(NULL) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: singleton_member(NULL) correctly errored: %', SQLERRM;
+    END;
+END $$;
+
+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+	RAISE NOTICE 'ERROR: singleton_member([1,2]) should have failed!';
+    EXCEPTION
+	WHEN OTHERS THEN
+	    RAISE NOTICE 'SUCCESS: singleton_member([1,2]) correctly errored: %', SQLERRM;
+    END;
+END $$;
+
+-- Look for "result | f" entries which indicate test failures.
+-- Error condition tests should show "SUCCESS:" messages.
+
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..3818b0784fe
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,151 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+-- Utility functions
+CREATE FUNCTION test_bms_from_array(integer[])
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_to_array(bytea)
+RETURNS integer[]
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+-- Bitmapset API functions
+CREATE FUNCTION test_bms_make_singleton(integer)
+RETURNS bytea STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_member(bytea, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_del_member(bytea, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_member(bytea, integer)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_num_members(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_copy(bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_equal(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_compare(bytea, bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_subset(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_subset_compare(bytea, bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_union(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_intersect(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_difference(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_empty(bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_membership(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_singleton_member(bytea)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_get_singleton_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_next_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_prev_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_hash_value(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap_list(bytea, bytea[])
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_nonempty_difference(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_member_index(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_range(bytea, integer, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_members(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_replace_members(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_join(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_hash(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_match(bytea, bytea)
+RETURNS int
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+-- Test utility functions
+CREATE FUNCTION test_random_operations(integer, integer)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION create_test_bitmapset(members integer[])
+RETURNS bytea
+LANGUAGE SQL
+AS $$
+    SELECT CASE WHEN $1 IS NULL OR array_length($1, 1) = 0
+	   THEN NULL::bytea
+	   ELSE bitmapset_to_bytea($1)
+	   END;
+$$;
+
+COMMENT ON EXTENSION test_bitmapset IS 'Test code for Bitmapset';
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..a1dc15392d6
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,1204 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include <stddef.h>
+#include <string.h>
+
+#include "catalog/pg_type.h"
+#include "common/pg_prng.h"
+#include "utils/array.h"
+#include "fmgr.h"
+#include "nodes/pg_list.h"
+#include "nodes/bitmapset.h"
+#include "varatt.h"
+
+PG_MODULE_MAGIC;
+
+/* Utility functions */
+PG_FUNCTION_INFO_V1(test_bms_from_array);
+PG_FUNCTION_INFO_V1(test_bms_to_array);
+
+/* Bitmapset API functions in order of appearance in bitmapset.c */
+PG_FUNCTION_INFO_V1(test_bms_make_singleton);
+PG_FUNCTION_INFO_V1(test_bms_add_member);
+PG_FUNCTION_INFO_V1(test_bms_del_member);
+PG_FUNCTION_INFO_V1(test_bms_is_member);
+PG_FUNCTION_INFO_V1(test_bms_num_members);
+PG_FUNCTION_INFO_V1(test_bms_copy);
+PG_FUNCTION_INFO_V1(test_bms_equal);
+PG_FUNCTION_INFO_V1(test_bms_compare);
+PG_FUNCTION_INFO_V1(test_bms_is_subset);
+PG_FUNCTION_INFO_V1(test_bms_subset_compare);
+PG_FUNCTION_INFO_V1(test_bms_union);
+PG_FUNCTION_INFO_V1(test_bms_intersect);
+PG_FUNCTION_INFO_V1(test_bms_difference);
+PG_FUNCTION_INFO_V1(test_bms_is_empty);
+PG_FUNCTION_INFO_V1(test_bms_membership);
+PG_FUNCTION_INFO_V1(test_bms_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_get_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_next_member);
+PG_FUNCTION_INFO_V1(test_bms_prev_member);
+PG_FUNCTION_INFO_V1(test_bms_hash_value);
+PG_FUNCTION_INFO_V1(test_bms_overlap);
+PG_FUNCTION_INFO_V1(test_bms_overlap_list);
+PG_FUNCTION_INFO_V1(test_bms_nonempty_difference);
+PG_FUNCTION_INFO_V1(test_bms_member_index);
+PG_FUNCTION_INFO_V1(test_bms_add_range);
+PG_FUNCTION_INFO_V1(test_bms_add_members);
+PG_FUNCTION_INFO_V1(test_bms_replace_members);
+PG_FUNCTION_INFO_V1(test_bms_join);
+PG_FUNCTION_INFO_V1(test_bitmap_hash);
+PG_FUNCTION_INFO_V1(test_bitmap_match);
+
+/* Test utility functions */
+PG_FUNCTION_INFO_V1(test_random_operations);
+
+#ifdef DEBUG
+
+static void
+elog_bitmapset(int elevel, const char *label, const Bitmapset *bms)
+{
+	StringInfoData buf;
+	int			member;
+	bool		first = true;
+
+	initStringInfo(&buf);
+
+	if (label)
+		appendStringInfo(&buf, "%s: ", label);
+
+	if (!bms_is_empty(bms))
+	{
+		appendStringInfoChar(&buf, '{');
+		member = -1;
+		while ((member = bms_next_member(bms, member)) >= 0)
+		{
+			if (!first)
+				appendStringInfoString(&buf, ", ");
+			appendStringInfo(&buf, "%d", member);
+			first = false;
+		}
+		appendStringInfoChar(&buf, '}');
+	}
+	else
+		appendStringInfoString(&buf, "EMPTY");
+
+	elog(elevel, "%s", buf.data);
+	pfree(buf.data);
+}
+
+#endif
+
+/*
+ * Utility functions to convert between Bitmapset and bytea
+ * for passing data between SQL and C functions
+ */
+
+static bytea *
+encode_bms_to_bytea(Bitmapset *bms)
+{
+	bytea	   *result;
+	int			bms_size;
+
+	if (bms == NULL)
+		return NULL;
+
+#ifdef DEBUG
+	elog(NOTICE, "Serializing bitmapset: nwords=%d, sizeof(bitmapword)=%zu",
+		 bms->nwords, sizeof(bitmapword));
+#endif
+
+	bms_size = offsetof(Bitmapset, words) + bms->nwords * sizeof(bitmapword);
+
+#ifdef DEBUG
+	elog(NOTICE, "Calculated bms_size=%d, offsetof(Bitmapset,words)=%zu",
+		 bms_size, offsetof(Bitmapset, words));
+#endif
+
+	result = (bytea *) palloc0(VARHDRSZ + bms_size);
+	memcpy(VARDATA(result), bms, bms_size);
+	SET_VARSIZE(result, VARHDRSZ + bms_size);
+
+	return result;
+}
+
+static Bitmapset *
+decode_bytea_to_bms(bytea *data)
+{
+	Bitmapset  *bms;
+	int			bms_size;
+
+	if (data == NULL)
+		return NULL;
+
+	bms_size = VARSIZE_ANY_EXHDR(data);
+
+	if (bms_size < offsetof(Bitmapset, words))
+		return NULL;
+
+	bms = (Bitmapset *) palloc(bms_size);
+	memcpy(bms, VARDATA_ANY(data), bms_size);
+
+	if (bms->nwords < 0 ||
+		bms->nwords > (bms_size - offsetof(Bitmapset, words)) / sizeof(bitmapword))
+	{
+		pfree(bms);
+		return NULL;
+	}
+
+	return bms;
+}
+
+/*
+ * Individual test functions for each bitmapset API function
+ */
+
+Datum
+test_bms_add_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	int			member;
+	Bitmapset  *bms;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(0))
+		bms = NULL;
+	else
+	{
+		bms_data = PG_GETARG_BYTEA_PP(0);
+		bms = decode_bytea_to_bms(bms_data);
+	}
+
+	member = PG_GETARG_INT32(1);
+
+	result_bms = bms_add_member(bms, member);
+
+	result = encode_bms_to_bytea(result_bms);
+
+	if (bms && bms != result_bms)
+		bms_free(bms);
+	if (result_bms)
+		bms_free(result_bms);
+
+	if (result == NULL)
+		PG_RETURN_NULL();
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_add_members(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms1_data,
+			   *bms2_data;
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+	char	   *data;
+
+	if (!PG_ARGISNULL(0))
+	{
+		bms1_data = PG_GETARG_BYTEA_PP(0);
+		if (VARSIZE_ANY_EXHDR(bms1_data) > 0)
+		{
+			bms1 = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms1_data));
+			memcpy(bms1, VARDATA_ANY(bms1_data), VARSIZE_ANY_EXHDR(bms1_data));
+		}
+	}
+
+	if (!PG_ARGISNULL(1))
+	{
+		bms2_data = PG_GETARG_BYTEA_PP(1);
+		if (VARSIZE_ANY_EXHDR(bms2_data) > 0)
+		{
+			bms2 = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms2_data));
+			memcpy(bms2, VARDATA_ANY(bms2_data), VARSIZE_ANY_EXHDR(bms2_data));
+		}
+	}
+
+	/* IMPORTANT: bms_add_members modifies/frees the first argument */
+	result_bms = bms_add_members(bms1, bms2);
+	/* bms1 is now invalid! Don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = (bytea *) palloc(VARHDRSZ + sizeof(Bitmapset) +
+							  (result_bms->nwords - 1) * sizeof(bitmapword));
+	data = VARDATA(result);
+	memcpy(data, result_bms, sizeof(Bitmapset) +
+		   (result_bms->nwords - 1) * sizeof(bitmapword));
+	SET_VARSIZE(result, VARHDRSZ + sizeof(Bitmapset) +
+				(result_bms->nwords - 1) * sizeof(bitmapword));
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_del_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bytea	   *result;
+	char	   *data;
+
+	if (!PG_ARGISNULL(0))
+	{
+		bms_data = PG_GETARG_BYTEA_PP(0);
+		if (VARSIZE_ANY_EXHDR(bms_data) > 0)
+		{
+			bms = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms_data));
+			memcpy(bms, VARDATA_ANY(bms_data), VARSIZE_ANY_EXHDR(bms_data));
+		}
+	}
+
+	member = PG_GETARG_INT32(1);
+	bms = bms_del_member(bms, member);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	result = (bytea *) palloc(VARHDRSZ + sizeof(Bitmapset) +
+							  bms->nwords * sizeof(bitmapword));
+	data = VARDATA(result);
+	memcpy(data, bms, sizeof(Bitmapset) + bms->nwords * sizeof(bitmapword));
+	SET_VARSIZE(result, VARHDRSZ + sizeof(Bitmapset) +
+				bms->nwords * sizeof(bitmapword));
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_is_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+	{
+		bms_data = PG_GETARG_BYTEA_PP(0);
+		if (VARSIZE_ANY_EXHDR(bms_data) > 0)
+		{
+			bms = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms_data));
+			memcpy(bms, VARDATA_ANY(bms_data), VARSIZE_ANY_EXHDR(bms_data));
+		}
+	}
+
+	member = PG_GETARG_INT32(1);
+	result = bms_is_member(member, bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_num_members(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(0);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	if (VARSIZE_ANY_EXHDR(bms_data) > 0)
+	{
+		bms = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms_data));
+		memcpy(bms, VARDATA_ANY(bms_data), VARSIZE_ANY_EXHDR(bms_data));
+	}
+
+	result = bms_num_members(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_make_singleton(PG_FUNCTION_ARGS)
+{
+	int32		member;
+	Bitmapset  *bms;
+	bytea	   *result;
+
+	member = PG_GETARG_INT32(0);
+	bms = bms_make_singleton(member);
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_copy(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *copy_bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	bms = decode_bytea_to_bms(bms_data);
+
+	copy_bms = bms_copy(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	result = encode_bms_to_bytea(copy_bms);
+	if (copy_bms)
+		bms_free(copy_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_equal(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms1_data,
+			   *bms2_data;
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+	{
+		bms1_data = PG_GETARG_BYTEA_PP(0);
+		if (VARSIZE_ANY_EXHDR(bms1_data) > 0)
+		{
+			bms1 = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms1_data));
+			memcpy(bms1, VARDATA_ANY(bms1_data), VARSIZE_ANY_EXHDR(bms1_data));
+		}
+	}
+
+	if (!PG_ARGISNULL(1))
+	{
+		bms2_data = PG_GETARG_BYTEA_PP(1);
+		if (VARSIZE_ANY_EXHDR(bms2_data) > 0)
+		{
+			bms2 = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms2_data));
+			memcpy(bms2, VARDATA_ANY(bms2_data), VARSIZE_ANY_EXHDR(bms2_data));
+		}
+	}
+
+	result = bms_equal(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_union(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms1_data,
+			   *bms2_data;
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+	{
+		bms1_data = PG_GETARG_BYTEA_PP(0);
+		bms1 = decode_bytea_to_bms(bms1_data);
+	}
+
+	if (!PG_ARGISNULL(1))
+	{
+		bms2_data = PG_GETARG_BYTEA_PP(1);
+		bms2 = decode_bytea_to_bms(bms2_data);
+	}
+
+	result_bms = bms_union(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_membership(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	BMS_Membership result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(BMS_EMPTY_SET);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	if (VARSIZE_ANY_EXHDR(bms_data) > 0)
+	{
+		bms = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms_data));
+		memcpy(bms, VARDATA_ANY(bms_data), VARSIZE_ANY_EXHDR(bms_data));
+	}
+
+	result = bms_membership(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_next_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-2);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	prevmember = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) > 0)
+	{
+		bms = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms_data));
+		memcpy(bms, VARDATA_ANY(bms_data), VARSIZE_ANY_EXHDR(bms_data));
+	}
+
+	result = bms_next_member(bms, prevmember);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_from_array(PG_FUNCTION_ARGS)
+{
+	ArrayType  *array;
+	int		   *members;
+	int			nmembers;
+	Bitmapset  *bms = NULL;
+	bytea	   *result;
+	int			i;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	array = PG_GETARG_ARRAYTYPE_P(0);
+
+	/* Check element type first */
+	if (ARR_ELEMTYPE(array) != INT4OID)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	/* Handle empty arrays - ARR_NDIM can be 0 for empty arrays */
+	if (ARR_NDIM(array) == 0)
+		PG_RETURN_NULL();
+
+	/* Now check dimensions */
+	if (ARR_NDIM(array) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	nmembers = ARR_DIMS(array)[0];
+
+	/* Double-check for empty */
+	if (nmembers == 0)
+		PG_RETURN_NULL();
+
+	if (ARR_HASNULL(array))
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	members = (int *) ARR_DATA_PTR(array);
+
+	for (i = 0; i < nmembers; i++)
+		bms = bms_add_member(bms, members[i]);
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_to_array(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	ArrayType  *result;
+	Datum	   *datums;
+	int			nmembers;
+	int			member = -1;
+	int			i = 0;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	bms = decode_bytea_to_bms(bms_data);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	nmembers = bms_num_members(bms);
+	datums = (Datum *) palloc(nmembers * sizeof(Datum));
+
+	while ((member = bms_next_member(bms, member)) >= 0)
+		datums[i++] = Int32GetDatum(member);
+
+	bms_free(bms);
+
+	result = construct_array(datums, nmembers,
+							 INT4OID, sizeof(int32), true, 'i');
+
+	pfree(datums);
+	PG_RETURN_ARRAYTYPE_P(result);
+}
+
+Datum
+test_bms_intersect(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_intersect(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_is_empty(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	result = bms_is_empty(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_is_subset(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_is_subset(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_subset_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	BMS_Comparison result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_subset_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("bitmapset is empty")));
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (bms == NULL)
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("bitmapset is empty")));
+
+	result = bms_singleton_member(bms);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_get_singleton_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		default_member;
+	int			member;
+	bool		success;
+
+	if (PG_ARGISNULL(0))
+	{
+		default_member = PG_GETARG_INT32(1);
+		PG_RETURN_INT32(default_member);
+	}
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	default_member = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(default_member);
+
+	bms = decode_bytea_to_bms(bms_data);
+
+	/*
+	 * bms_get_singleton_member returns bool and stores result in member
+	 * pointer
+	 */
+	success = bms_get_singleton_member(bms, &member);
+	bms_free(bms);
+
+	if (success)
+		PG_RETURN_INT32(member);
+	else
+		PG_RETURN_INT32(default_member);
+}
+
+Datum
+test_bms_prev_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-2);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	prevmember = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-2);
+
+	bms = decode_bytea_to_bms(bms_data);
+
+	result = bms_prev_member(bms, prevmember);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_overlap(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_overlap(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_overlap_list(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	ArrayType  *array;
+	List	   *bitmapset_list = NIL;
+	ListCell   *lc;
+	bool		result;
+	Datum	   *elem_datums;
+	bool	   *elem_nulls;
+	int			elem_count;
+	int			i;
+
+	/* Handle first argument (the bitmapset) */
+	if (PG_ARGISNULL(0))
+		PG_RETURN_BOOL(false);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	/* Handle second argument (array of bitmapsets) */
+	if (PG_ARGISNULL(1))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_BOOL(false);
+	}
+
+	array = PG_GETARG_ARRAYTYPE_P(1);
+
+	/* Validate array */
+	if (ARR_NDIM(array) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("one-dimensional array expected")));
+
+	if (ARR_ELEMTYPE(array) != BYTEAOID)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATATYPE_MISMATCH),
+				 errmsg("bytea array expected")));
+
+	/* Deconstruct the array */
+	deconstruct_array(array,
+					  BYTEAOID, -1, false, 'i',
+					  &elem_datums, &elem_nulls, &elem_count);
+
+	/* Convert each bytea element to a Bitmapset and add to list */
+	for (i = 0; i < elem_count; i++)
+	{
+		Bitmapset  *list_bms = NULL;
+
+		if (!elem_nulls[i])
+		{
+			bytea	   *elem_bytea = DatumGetByteaP(elem_datums[i]);
+
+			list_bms = decode_bytea_to_bms(elem_bytea);
+		}
+
+		/* Add to list (even if NULL) */
+		bitmapset_list = lappend(bitmapset_list, list_bms);
+	}
+
+	/* Call the actual bms_overlap_list function */
+	result = bms_overlap_list(bms, bitmapset_list);
+
+	/* Clean up */
+	if (bms)
+		bms_free(bms);
+
+	/* Free all bitmapsets in the list */
+	foreach(lc, bitmapset_list)
+	{
+		Bitmapset  *list_bms = (Bitmapset *) lfirst(lc);
+
+		if (list_bms)
+			bms_free(list_bms);
+	}
+	list_free(bitmapset_list);
+
+	/* Free array deconstruction results */
+	pfree(elem_datums);
+	pfree(elem_nulls);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_nonempty_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_nonempty_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_member_index(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		member;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-1);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	member = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-1);
+
+	bms = decode_bytea_to_bms(bms_data);
+
+	result = bms_member_index(bms, member);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_add_range(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		lower,
+				upper;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	lower = PG_GETARG_INT32(1);
+	upper = PG_GETARG_INT32(2);
+
+	/* Check for invalid range */
+	if (upper < lower)
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	bms = bms_add_range(bms, lower, upper);
+
+	result = encode_bms_to_bytea(bms);
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_replace_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_replace_members modifies/frees the first argument */
+	result_bms = bms_replace_members(bms1, bms2);
+	/* bms1 is now invalid, don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_join(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_join modifies/frees the first argument */
+	result_bms = bms_join(bms1, bms2);
+	/* bms1 is now invalid! Don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_hash_value(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	hash_result = bms_hash_value(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_hash(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	Bitmapset  *bms_ptr;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	bms_ptr = bms;
+
+	/* Call bitmap_hash */
+	hash_result = bitmap_hash(&bms_ptr, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (!PG_ARGISNULL(0) && bms_ptr)
+		bms_free(bms_ptr);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_match(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *bms_ptr1,
+			   *bms_ptr2;
+	int			match_result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* Set up pointers to the Bitmapsets */
+	bms_ptr1 = bms1;
+	bms_ptr2 = bms2;
+
+	/* Call bitmap_match with addresses of the Bitmapset pointers */
+	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(match_result);
+}
+
+Datum
+test_random_operations(PG_FUNCTION_ARGS)
+{
+	pg_prng_state state;
+	int32		seed;
+	int32		num_ops;
+	Bitmapset  *bms = NULL;
+	int			op,
+				member;
+	int			total_ops = 0;
+
+	seed = PG_GETARG_INT32(0);
+	num_ops = PG_GETARG_INT32(1);
+
+	pg_prng_seed(&state, (uint64) seed);
+
+	for (int i = 0; i < num_ops; i++)
+	{
+		op = pg_prng_uint32(&state) % 3;	/* 0=add, 1=delete, 2=test */
+		member = pg_prng_uint32(&state) % 1000;
+
+		switch (op)
+		{
+			case 0:				/* add */
+				bms = bms_add_member(bms, member);
+				total_ops++;
+				break;
+			case 1:				/* delete */
+				if (bms != NULL)
+				{
+					bms = bms_del_member(bms, member);
+					total_ops++;
+				}
+				break;
+			case 2:				/* test membership */
+				if (bms != NULL)
+				{
+					bms_is_member(member, bms);
+					total_ops++;
+				}
+				break;
+		}
+	}
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(total_ops);
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#18Masahiko Sawada
sawada.mshk@gmail.com
In reply to: Greg Burd (#17)
Re: [PATCH] Add tests for Bitmapset

On Tue, Sep 16, 2025 at 12:04 PM Greg Burd <greg@burd.me> wrote:

I've re-written the set of tests as suggested (I hope!). I've not
re-run the coverage report (yet) to ensure we're at least as well
covered as v3, but attached is v4 for your inspection (amusement?).
I've tried to author the SQL tests such that failures clearly indicate
what's at gone wrong.

This exercise turned into a lot more LOC than I'd expected, I hope it
provides some value to the community for testing this important data
structure and helps to codify the API clearly.

Thank you for updating the patch. It seems cfbot caught a regression
test error[1]https://cirrus-ci.com/task/5290864655728640 in a 32-bit build.

Regards,

[1]: https://cirrus-ci.com/task/5290864655728640

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

#19Michael Paquier
michael@paquier.xyz
In reply to: Masahiko Sawada (#18)
Re: [PATCH] Add tests for Bitmapset

On Tue, Sep 16, 2025 at 03:00:40PM -0700, Masahiko Sawada wrote:

Thank you for updating the patch. It seems cfbot caught a regression
test error[1] in a 32-bit build.

- bitmap_hash [1,3,5] |   49870778
+ bitmap_hash [1,3,5] | 1509752520

This one is able the hash value computation being not portable across
architectures. I would just change these to be non-NULL, I guess.
--
Michael

#20Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#17)
Re: [PATCH] Add tests for Bitmapset

On Tue, Sep 16, 2025 at 03:04:39PM -0400, Greg Burd wrote:

I've re-written the set of tests as suggested (I hope!). I've not
re-run the coverage report (yet) to ensure we're at least as well
covered as v3, but attached is v4 for your inspection (amusement?).
I've tried to author the SQL tests such that failures clearly indicate
what's at gone wrong.

Thanks for the update, that's easier to follow, even if it's more
code overall. It looks like all the 29 APIs are present, plus the
extras for the array mapping routines required for the tests with the
list APIs.

+static void
+elog_bitmapset(int elevel, const char *label, const Bitmapset *bms)

This routine, that's able to translate a bytea into a readable form,
is also something that I would have added as an extra function, then
used it in some of the tests where I would care about the bitmap in
output generated after a given operation, removing the DEBUG parts
that I guess have also a risk of rotting over time. That would make
the tests for simple operations that generate a bms as a result in
easier to read, because we would call less SQL calls. For example,
take the "add_member idempotent" case, that calls twice
test_bms_make_singleton() to compare the output byteas, we could just
do a test_bms_add_member(test_bms_make_singleton(10), 10) and show the
output?

We could perhaps use the CTE style for the basic calls, to reduce the
test_bms_make_singleton() calls. What you are doing feels OK as well,
just a thought in passing.

FWIW, I tend to write the regression test queries so as these are
limited to 72-80 characters per line, to fit even in a small
terminals. That's just an old-school take, even if it means more
lines in the SQL input file..

Perhaps it would be worth documenting what's the value of
test_random_operations? It is a mean of testing add, del and
is_member with a modulo 1000 of the member number. With the other
functions that offer deterministic tests, I am not sure what's the
extra value gained in it.

+		bms1_data = PG_GETARG_BYTEA_PP(0);
+		if (VARSIZE_ANY_EXHDR(bms1_data) > 0)
+		{
+			bms1 = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms1_data));
+			memcpy(bms1, VARDATA_ANY(bms1_data), VARSIZE_ANY_EXHDR(bms1_data));
+		}

This pattern is repeated 9 times, if my fingers got it right. Perhaps
hide it in a macro, or invent an extra static inline routine that does
the translation?

+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+	RAISE NOTICE 'ERROR: singleton_member([1,2]) should have failed!';

Do we need all these DO blocks to catch failures? These cases bump on
elog(ERROR) in the internals of bitmapset.c, which are not something
the end-users would expect, but in a test module that's fine to
trigger. The function call would just fail, which is fine.

The queries with CTEs and UNION ALL are elegant, nice.

This exercise turned into a lot more LOC than I'd expected, I hope it
provides some value to the community for testing this important data
structure and helps to codify the API clearly.

It does, at least that's my opinion. So thanks for caring about this
level of testing.
--
Michael

#21Greg Burd
greg@burd.me
In reply to: Michael Paquier (#19)
Re: [PATCH] Add tests for Bitmapset

On Sep 16 2025, at 8:35 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Tue, Sep 16, 2025 at 03:00:40PM -0700, Masahiko Sawada wrote:

Thank you for updating the patch. It seems cfbot caught a regression
test error[1] in a 32-bit build.

- bitmap_hash [1,3,5] |   49870778
+ bitmap_hash [1,3,5] | 1509752520

This one is able the hash value computation being not portable across
architectures. I would just change these to be non-NULL, I guess.
--
Michael

Thanks Michael, Sawada-san, yep hashing is arch dependent (go figure!),
but thankfully it is deterministic. Rather that test for non-NULL I've
come up with this approach:

-- Architecture-aware hash testing
WITH arch_info AS (
SELECT
CASE
WHEN pg_column_size(1::bigint) = 8 THEN '64bit'
ELSE '32bit'
END as architecture
),
expected_values AS (
SELECT
architecture,
CASE architecture
WHEN '64bit' THEN 0
WHEN '32bit' THEN 0
END as hash_null,
CASE architecture
WHEN '64bit' THEN 49870778
WHEN '32bit' THEN 1509752520
END as hash_135,
CASE architecture
WHEN '64bit' THEN -303921606
WHEN '32bit' THEN 0 -- TBD
END as hash_246
FROM arch_info
)
SELECT 'expected hash NULL' as test,
test_bitmap_hash(NULL) = hash_null as result
FROM expected_values
UNION ALL
SELECT 'expected hash [1,3,5]' as test,
test_bitmap_hash(test_bms_from_array(ARRAY[1,3,5])) = hash_135 as result
FROM expected_values
UNION ALL
SELECT 'expected hash [2,4,6]' as test,
test_bitmap_hash(test_bms_from_array(ARRAY[2,4,6])) = hash_246 as result
FROM expected_values;

However I'm not sure what the value is for testing hash functions except
for coverage and I'm fairly certain that function is well exercised.
That said, I think that will work. I'll let cfbot tell me the 32bit
hash value on the next run.

thanks again for the helpful insights,

-greg

#22Greg Burd
greg@burd.me
In reply to: Michael Paquier (#20)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 16 2025, at 11:25 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Tue, Sep 16, 2025 at 03:04:39PM -0400, Greg Burd wrote:

I've re-written the set of tests as suggested (I hope!). I've not
re-run the coverage report (yet) to ensure we're at least as well
covered as v3, but attached is v4 for your inspection (amusement?).
I've tried to author the SQL tests such that failures clearly indicate
what's at gone wrong.

Thanks for the update, that's easier to follow, even if it's more
code overall. It looks like all the 29 APIs are present, plus the
extras for the array mapping routines required for the tests with the
list APIs.

Thank you for the continued detailed feedback, I think we're zeroing in
on a solid patch.

+static void
+elog_bitmapset(int elevel, const char *label, const Bitmapset *bms)

This routine, that's able to translate a bytea into a readable form,
is also something that I would have added as an extra function, then
used it in some of the tests where I would care about the bitmap in
output generated after a given operation, removing the DEBUG parts
that I guess have also a risk of rotting over time. That would make
the tests for simple operations that generate a bms as a result in
easier to read, because we would call less SQL calls. For example,
take the "add_member idempotent" case, that calls twice
test_bms_make_singleton() to compare the output byteas, we could just
do a test_bms_add_member(test_bms_make_singleton(10), 10) and show the
output?

I added a function bms_values() that prints out the values contained in
a bitmapset and changed a few tests to use it. I removed the
elog_bitmapset() as it isn't being used and now that it's easy to output
the set in SQL why keep it for debugging?

We could perhaps use the CTE style for the basic calls, to reduce the
test_bms_make_singleton() calls. What you are doing feels OK as well,
just a thought in passing.

I changed a few tests I saw with the pattern you mentioned. If you identify
additional tests you feel should be re-written please let me know.

FWIW, I tend to write the regression test queries so as these are
limited to 72-80 characters per line, to fit even in a small
terminals. That's just an old-school take, even if it means more
lines in the SQL input file.

I have a vt-100 sitting behind me, I get it. I tend to try to line-wrap
at 78. I tried a few times to re-format the SQL accordingly and I found
that it became harder to understand and less readable IMO. I'd prefer to
keep it as is, unless there is a hard requirement in which case I'll
reformat it.

Perhaps it would be worth documenting what's the value of
test_random_operations? It is a mean of testing add, del and
is_member with a modulo 1000 of the member number. With the other
functions that offer deterministic tests, I am not sure what's the
extra value gained in it.

That was my thinking and why I didn't have a test that used random data
to start with (v1). I'd rather just remove it, but I'm open to ideas.
I could replace it with the earlier version of the function.

+		bms1_data = PG_GETARG_BYTEA_PP(0);
+		if (VARSIZE_ANY_EXHDR(bms1_data) > 0)
+		{
+			bms1 = (Bitmapset *) palloc(VARSIZE_ANY_EXHDR(bms1_data));
+			memcpy(bms1, VARDATA_ANY(bms1_data), VARSIZE_ANY_EXHDR(bms1_data));
+		}

This pattern is repeated 9 times, if my fingers got it right. Perhaps
hide it in a macro, or invent an extra static inline routine that does
the translation?

That was an oversight on my part, all of those have been reduced to use
the same pattern with encode/decode bms() functions.

+DO $$
+BEGIN
+    BEGIN
+	PERFORM test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+	RAISE NOTICE 'ERROR: singleton_member([1,2]) should have failed!';

Do we need all these DO blocks to catch failures? These cases bump on
elog(ERROR) in the internals of bitmapset.c, which are not something
the end-users would expect, but in a test module that's fine to
trigger. The function call would just fail, which is fine.

Sure, that's easy enough.

The queries with CTEs and UNION ALL are elegant, nice.

Thanks.

This exercise turned into a lot more LOC than I'd expected, I hope it
provides some value to the community for testing this important data
structure and helps to codify the API clearly.

It does, at least that's my opinion. So thanks for caring about this
level of testing.

Again, thank YOU(!) for caring enough to review the work.

--
Michael

Don't forget, we expect the cfbot/CI to fail on 32bit systems and tell
us the hash value we need to record in the next version of the patch.
Or, if we don't think testing the hash functions is worth it (and I'm on
the fence on this one) then I can just remove it.

best.

-greg

Attachments:

v5-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From 9e92cdf21fcc3ff3b79c2b8ce3b1c65a79383797 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v5] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |    1 +
 src/test/modules/meson.build                  |    1 +
 src/test/modules/test_bitmapset/.gitignore    |    4 +
 src/test/modules/test_bitmapset/Makefile      |   23 +
 .../expected/test_bitmapset.out               |  634 ++++++++++
 src/test/modules/test_bitmapset/meson.build   |   33 +
 .../test_bitmapset/sql/test_bitmapset.sql     |  372 ++++++
 .../test_bitmapset/test_bitmapset--1.0.sql    |  155 +++
 .../modules/test_bitmapset/test_bitmapset.c   | 1102 +++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |    4 +
 10 files changed, 2329 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..47f74cb7520
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,634 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+-- BASIC FUNCTIONALITY TESTS
+-- Test bms_values function
+SELECT 'values NULL' as test, bms_values(NULL) as result;
+    test     | result 
+-------------+--------
+ values NULL | {}
+(1 row)
+
+SELECT 'values empty' as test, bms_values(test_bms_from_array(ARRAY[]::integer[])) as result;
+     test     | result 
+--------------+--------
+ values empty | {}
+(1 row)
+
+SELECT 'values singleton' as test, bms_values(test_bms_make_singleton(42)) as result;
+       test       | result 
+------------------+--------
+ values singleton | {42}
+(1 row)
+
+SELECT 'values small set' as test, bms_values(test_bms_from_array(ARRAY[1,3,5])) as result;
+       test       | result  
+------------------+---------
+ values small set | {1,3,5}
+(1 row)
+
+SELECT 'values larger set' as test, bms_values(test_bms_from_array(ARRAY[0,5,10,15,20])) as result;
+       test        |     result     
+-------------------+----------------
+ values larger set | {0,5,10,15,20}
+(1 row)
+
+SELECT 'values unsorted input' as test, bms_values(test_bms_from_array(ARRAY[20,5,15,0,10])) as result;
+         test          |     result     
+-----------------------+----------------
+ values unsorted input | {0,5,10,15,20}
+(1 row)
+
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+           test           | result 
+--------------------------+--------
+ NULL input to from_array | t
+(1 row)
+
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+           test            | result 
+---------------------------+--------
+ Empty array to from_array | t
+(1 row)
+
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+          test          | result 
+------------------------+--------
+ NULL input to to_array | t
+(1 row)
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+        test        | result 
+--------------------+--------
+ make_singleton(42) | t
+(1 row)
+
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+       test        | result 
+-------------------+--------
+ make_singleton(0) | t
+(1 row)
+
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+         test         | result 
+----------------------+--------
+ make_singleton(1000) | t
+(1 row)
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+         test         | result 
+----------------------+--------
+ add_member(NULL, 10) | t
+(1 row)
+
+SELECT 'add_member consistency' as test, bms_values(test_bms_add_member(NULL, 10)) as values;
+          test          | values 
+------------------------+--------
+ add_member consistency | {10}
+(1 row)
+
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+          test          | result 
+------------------------+--------
+ add_member to existing | t
+(1 row)
+
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+       test        | result 
+-------------------+--------
+ add_member sorted | t
+(1 row)
+
+SELECT 'add_member idempotent' as test, bms_values(test_bms_add_member(test_bms_make_singleton(10), 10)) as values;
+         test          | values 
+-----------------------+--------
+ add_member idempotent | {10}
+(1 row)
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+         test         | result 
+----------------------+--------
+ del_member from NULL | t
+(1 row)
+
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+                test                | result 
+------------------------------------+--------
+ del_member singleton becomes empty | t
+(1 row)
+
+SELECT 'del_member no change' as test, bms_values(test_bms_del_member(test_bms_make_singleton(10), 5)) as values;
+         test         | values 
+----------------------+--------
+ del_member no change | {10}
+(1 row)
+
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+          test          | result 
+------------------------+--------
+ del_member from middle | t
+(1 row)
+
+-- SET OPERATIONS TESTS
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+          test          | result 
+------------------------+--------
+ union overlapping sets | t
+ union with NULL        | t
+ union NULL with NULL   | t
+(3 rows)
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+            test            | result 
+----------------------------+--------
+ intersect overlapping sets | t
+ intersect disjoint sets    | t
+ intersect with NULL        | t
+(3 rows)
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+            test             | result 
+-----------------------------+--------
+ difference overlapping sets | t
+ difference disjoint sets    | t
+ difference identical sets   | t
+(3 rows)
+
+-- MEMBERSHIP AND COMPARISON TESTS
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+           test            | result 
+---------------------------+--------
+ is_member existing        | t
+ is_member missing         | t
+ is_member existing middle | t
+ is_member NULL set        | t
+(4 rows)
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ num_members NULL | t
+(1 row)
+
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+         test          | result 
+-----------------------+--------
+ num_members small set | t
+(1 row)
+
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+          test          | result 
+------------------------+--------
+ num_members larger set | t
+(1 row)
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+          test           | result 
+-------------------------+--------
+ equal NULL NULL         | t
+ equal NULL set          | t
+ equal set NULL          | t
+ equal identical sets    | t
+ equal different sets    | t
+ compare NULL NULL       | t
+ compare NULL set        | t
+ compare set NULL        | t
+ compare equal sets      | t
+ compare subset superset | t
+ compare superset subset | t
+(11 rows)
+
+-- ADVANCED OPERATIONS TESTS
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+      test       | result 
+-----------------+--------
+ add_range basic | t
+(1 row)
+
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+           test           | result 
+--------------------------+--------
+ add_range single element | t
+(1 row)
+
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+         test          | result 
+-----------------------+--------
+ add_range to existing | t
+(1 row)
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ membership empty | t
+(1 row)
+
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+         test         | result 
+----------------------+--------
+ membership singleton | t
+(1 row)
+
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+        test         | result 
+---------------------+--------
+ membership multiple | t
+(1 row)
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+          test          | result 
+------------------------+--------
+ singleton_member valid | t
+(1 row)
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+            test            | result 
+----------------------------+--------
+ next_member first          | t
+ next_member second         | t
+ next_member past end       | t
+ next_member empty set      | t
+ prev_member last           | t
+ prev_member penultimate    | t
+ prev_member past beginning | t
+ prev_member empty set      | t
+(8 rows)
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_135a) = test_bms_hash_value(set_135b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_135a) != test_bms_hash_value(set_246) as result FROM test_sets;
+        test         | result 
+---------------------+--------
+ hash NULL           | t
+ hash consistency    | t
+ hash different sets | t
+(3 rows)
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+       test        | result 
+-------------------+--------
+ overlap existing  | t
+ overlap none      | t
+ overlap with NULL | t
+(3 rows)
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets;
+             test             | result 
+------------------------------+--------
+ subset NULL is subset of all | t
+ subset proper subset         | t
+ subset improper subset       | t
+ subset disjoint sets         | t
+(4 rows)
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+     test      | result 
+---------------+--------
+ copy NULL     | t
+ copy equality | t
+(2 rows)
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+         test          | result 
+-----------------------+--------
+ add_members operation | t
+(1 row)
+
+-- Test 20: Test hash consistency
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+             test              | result 
+-------------------------------+--------
+ bitmap_hash NULL              | t
+ bitmap_hash consistency       | t
+ bitmap_hash vs bms_hash_value | t
+ bitmap_hash different sets    | t
+(4 rows)
+
+-- Architecture-aware hash testing
+WITH arch_info AS (
+    SELECT
+        CASE
+            WHEN pg_column_size(1::bigint) = 8 THEN '64bit'
+            ELSE '32bit'
+        END as architecture
+),
+expected_values AS (
+    SELECT
+        architecture,
+        CASE architecture
+            WHEN '64bit' THEN 0
+            WHEN '32bit' THEN 0
+        END as hash_null,
+        CASE architecture
+            WHEN '64bit' THEN 49870778
+            WHEN '32bit' THEN 1509752520
+        END as hash_135,
+        CASE architecture
+            WHEN '64bit' THEN -303921606
+            WHEN '32bit' THEN 0  -- TBD
+        END as hash_246
+    FROM arch_info
+)
+SELECT 'expected hash NULL' as test,
+       test_bitmap_hash(NULL) = hash_null as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [1,3,5]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[1,3,5])) = hash_135 as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [2,4,6]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[2,4,6])) = hash_246 as result
+FROM expected_values;
+         test          | result 
+-----------------------+--------
+ expected hash NULL    | t
+ expected hash [1,3,5] | t
+ expected hash [2,4,6] | t
+(3 rows)
+
+-- Test 21: bitmap_match function
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match NULL NULL (should be 0)       | t
+ bitmap_match NULL set (should be 1)        | t
+ bitmap_match set NULL (should be 1)        | t
+ bitmap_match identical sets (should be 0)  | t
+ bitmap_match different sets (should be 1)  | t
+ bitmap_match subset/superset (should be 1) | t
+(6 rows)
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match vs bms_equal (equal sets)     | t
+ bitmap_match vs bms_equal (different sets) | t
+ bitmap_match vs bms_equal (NULL cases)     | t
+(3 rows)
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [1,3,5] |           0
+(1 row)
+
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [2,4,6] |           1
+(1 row)
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+           test            | result 
+---------------------------+--------
+ bitmap_match empty arrays | t
+(1 row)
+
+-- Test 22: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(12345, 1000) > 0 as result;
+       test        | result 
+-------------------+--------
+ random operations | t
+(1 row)
+
+-- ERROR CONDITION TESTS
+-- Test 23: Error conditions (these should produce ERRORs)
+-- Negative member tests
+SELECT test_bms_make_singleton(-1);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_is_member(NULL, -5);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_member(NULL, -10);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_del_member(NULL, -20);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_range(NULL, -5, 10);
+ERROR:  negative bitmapset member not allowed
+-- Singleton member errors
+SELECT test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+ERROR:  bitmapset has multiple members
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..603efb0e255
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,372 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+
+-- BASIC FUNCTIONALITY TESTS
+
+-- Test bms_values function
+
+SELECT 'values NULL' as test, bms_values(NULL) as result;
+SELECT 'values empty' as test, bms_values(test_bms_from_array(ARRAY[]::integer[])) as result;
+SELECT 'values singleton' as test, bms_values(test_bms_make_singleton(42)) as result;
+SELECT 'values small set' as test, bms_values(test_bms_from_array(ARRAY[1,3,5])) as result;
+SELECT 'values larger set' as test, bms_values(test_bms_from_array(ARRAY[0,5,10,15,20])) as result;
+SELECT 'values unsorted input' as test, bms_values(test_bms_from_array(ARRAY[20,5,15,0,10])) as result;
+
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+SELECT 'add_member consistency' as test, bms_values(test_bms_add_member(NULL, 10)) as values;
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+SELECT 'add_member idempotent' as test, bms_values(test_bms_add_member(test_bms_make_singleton(10), 10)) as values;
+
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+SELECT 'del_member no change' as test, bms_values(test_bms_del_member(test_bms_make_singleton(10), 5)) as values;
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+
+-- SET OPERATIONS TESTS
+
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+
+-- MEMBERSHIP AND COMPARISON TESTS
+
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+
+-- ADVANCED OPERATIONS TESTS
+
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_135a) = test_bms_hash_value(set_135b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_135a) != test_bms_hash_value(set_246) as result FROM test_sets;
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets;
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+
+-- Test 20: Test hash consistency
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+
+-- Architecture-aware hash testing
+WITH arch_info AS (
+    SELECT
+        CASE
+            WHEN pg_column_size(1::bigint) = 8 THEN '64bit'
+            ELSE '32bit'
+        END as architecture
+),
+expected_values AS (
+    SELECT
+        architecture,
+        CASE architecture
+            WHEN '64bit' THEN 0
+            WHEN '32bit' THEN 0
+        END as hash_null,
+        CASE architecture
+            WHEN '64bit' THEN 49870778
+            WHEN '32bit' THEN 1509752520
+        END as hash_135,
+        CASE architecture
+            WHEN '64bit' THEN -303921606
+            WHEN '32bit' THEN 0  -- TBD
+        END as hash_246
+    FROM arch_info
+)
+SELECT 'expected hash NULL' as test,
+       test_bitmap_hash(NULL) = hash_null as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [1,3,5]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[1,3,5])) = hash_135 as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [2,4,6]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[2,4,6])) = hash_246 as result
+FROM expected_values;
+
+-- Test 21: bitmap_match function
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+
+-- Test 22: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(12345, 1000) > 0 as result;
+
+-- ERROR CONDITION TESTS
+
+-- Test 23: Error conditions (these should produce ERRORs)
+
+-- Negative member tests
+SELECT test_bms_make_singleton(-1);
+SELECT test_bms_is_member(NULL, -5);
+SELECT test_bms_add_member(NULL, -10);
+SELECT test_bms_del_member(NULL, -20);
+SELECT test_bms_add_range(NULL, -5, 10);
+
+-- Singleton member errors
+SELECT test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..bcac98e2d85
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,155 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+-- Utility functions
+CREATE FUNCTION test_bms_from_array(integer[])
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_to_array(bytea)
+RETURNS integer[]
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION bms_values(bytea)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C STABLE;
+
+-- Bitmapset API functions
+CREATE FUNCTION test_bms_make_singleton(integer)
+RETURNS bytea STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_member(bytea, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_del_member(bytea, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_member(bytea, integer)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_num_members(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_copy(bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_equal(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_compare(bytea, bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_subset(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_subset_compare(bytea, bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_union(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_intersect(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_difference(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_empty(bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_membership(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_singleton_member(bytea)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_get_singleton_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_next_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_prev_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_hash_value(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap_list(bytea, bytea[])
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_nonempty_difference(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_member_index(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_range(bytea, integer, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_members(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_replace_members(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_join(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_hash(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_match(bytea, bytea)
+RETURNS int
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+-- Test utility functions
+CREATE FUNCTION test_random_operations(integer, integer)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION create_test_bitmapset(members integer[])
+RETURNS bytea
+LANGUAGE SQL
+AS $$
+    SELECT CASE WHEN $1 IS NULL OR array_length($1, 1) = 0
+	   THEN NULL::bytea
+	   ELSE bitmapset_to_bytea($1)
+	   END;
+$$;
+
+COMMENT ON EXTENSION test_bitmapset IS 'Test code for Bitmapset';
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..af3af470348
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,1102 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include <stddef.h>
+#include <string.h>
+
+#include "catalog/pg_type.h"
+#include "common/pg_prng.h"
+#include "lib/stringinfo.h"
+#include "utils/array.h"
+#include "fmgr.h"
+#include "nodes/pg_list.h"
+#include "nodes/bitmapset.h"
+#include "utils/builtins.h"
+#include "varatt.h"
+
+PG_MODULE_MAGIC;
+
+/* Utility functions */
+PG_FUNCTION_INFO_V1(bms_values);
+PG_FUNCTION_INFO_V1(test_bms_from_array);
+PG_FUNCTION_INFO_V1(test_bms_to_array);
+
+/* Bitmapset API functions in order of appearance in bitmapset.c */
+PG_FUNCTION_INFO_V1(test_bms_make_singleton);
+PG_FUNCTION_INFO_V1(test_bms_add_member);
+PG_FUNCTION_INFO_V1(test_bms_del_member);
+PG_FUNCTION_INFO_V1(test_bms_is_member);
+PG_FUNCTION_INFO_V1(test_bms_num_members);
+PG_FUNCTION_INFO_V1(test_bms_copy);
+PG_FUNCTION_INFO_V1(test_bms_equal);
+PG_FUNCTION_INFO_V1(test_bms_compare);
+PG_FUNCTION_INFO_V1(test_bms_is_subset);
+PG_FUNCTION_INFO_V1(test_bms_subset_compare);
+PG_FUNCTION_INFO_V1(test_bms_union);
+PG_FUNCTION_INFO_V1(test_bms_intersect);
+PG_FUNCTION_INFO_V1(test_bms_difference);
+PG_FUNCTION_INFO_V1(test_bms_is_empty);
+PG_FUNCTION_INFO_V1(test_bms_membership);
+PG_FUNCTION_INFO_V1(test_bms_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_get_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_next_member);
+PG_FUNCTION_INFO_V1(test_bms_prev_member);
+PG_FUNCTION_INFO_V1(test_bms_hash_value);
+PG_FUNCTION_INFO_V1(test_bms_overlap);
+PG_FUNCTION_INFO_V1(test_bms_overlap_list);
+PG_FUNCTION_INFO_V1(test_bms_nonempty_difference);
+PG_FUNCTION_INFO_V1(test_bms_member_index);
+PG_FUNCTION_INFO_V1(test_bms_add_range);
+PG_FUNCTION_INFO_V1(test_bms_add_members);
+PG_FUNCTION_INFO_V1(test_bms_replace_members);
+PG_FUNCTION_INFO_V1(test_bms_join);
+PG_FUNCTION_INFO_V1(test_bitmap_hash);
+PG_FUNCTION_INFO_V1(test_bitmap_match);
+
+/* Test utility functions */
+PG_FUNCTION_INFO_V1(test_random_operations);
+
+/*
+ * Utility functions to convert between Bitmapset and bytea
+ * for passing data between SQL and C functions
+ */
+
+static bytea *
+encode_bms_to_bytea(Bitmapset *bms)
+{
+	bytea	   *result;
+	int			bms_size;
+
+	if (bms == NULL)
+		return NULL;
+
+	bms_size = offsetof(Bitmapset, words) + bms->nwords * sizeof(bitmapword);
+	result = (bytea *) palloc0(VARHDRSZ + bms_size);
+	memcpy(VARDATA(result), bms, bms_size);
+	SET_VARSIZE(result, VARHDRSZ + bms_size);
+
+	return result;
+}
+
+static Bitmapset *
+decode_bytea_to_bms(bytea *data)
+{
+	Bitmapset  *bms;
+	int			bms_size;
+
+	if (data == NULL)
+		return NULL;
+
+	bms_size = VARSIZE_ANY_EXHDR(data);
+
+	if (bms_size < offsetof(Bitmapset, words))
+		return NULL;
+
+	bms = (Bitmapset *) palloc(bms_size);
+	memcpy(bms, VARDATA_ANY(data), bms_size);
+
+	if (bms->nwords < 0 ||
+		bms->nwords > (bms_size - offsetof(Bitmapset, words)) / sizeof(bitmapword))
+	{
+		pfree(bms);
+		return NULL;
+	}
+
+	return bms;
+}
+
+Datum
+bms_values(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms;
+	StringInfoData buf;
+	int			member;
+	bool		first = true;
+	text	   *result;
+
+	if (PG_ARGISNULL(0))
+	{
+		result = cstring_to_text("{}");
+		PG_RETURN_TEXT_P(result);
+	}
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+	initStringInfo(&buf);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		appendStringInfoString(&buf, "{}");
+	}
+	else
+	{
+		appendStringInfoChar(&buf, '{');
+
+		member = -1;
+		while ((member = bms_next_member(bms, member)) >= 0)
+		{
+			if (!first)
+				appendStringInfoChar(&buf, ',');
+			appendStringInfo(&buf, "%d", member);
+			first = false;
+		}
+
+		appendStringInfoChar(&buf, '}');
+	}
+
+	if (bms)
+		bms_free(bms);
+
+	result = cstring_to_text(buf.data);
+	pfree(buf.data);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+/*
+ * Individual test functions for each bitmapset API function
+ */
+
+Datum
+test_bms_add_member(PG_FUNCTION_ARGS)
+{
+	int			member;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	result_bms = bms_add_member(bms, member);
+	result = encode_bms_to_bytea(result_bms);
+
+	if (bms && bms != result_bms)
+		bms_free(bms);
+	if (result_bms)
+		bms_free(result_bms);
+
+	if (result == NULL)
+		PG_RETURN_NULL();
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_add_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_add_members modifies/frees the first argument */
+	result_bms = bms_add_members(bms1, bms2);
+	/* bms1 is now invalid, don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_del_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	bms = bms_del_member(bms, member);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_is_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bool		result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_BOOL(false);
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	result = bms_is_member(member, bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_num_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result = 0;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	result = bms_num_members(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_make_singleton(PG_FUNCTION_ARGS)
+{
+	int32		member;
+	Bitmapset  *bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	member = PG_GETARG_INT32(0);
+	bms = bms_make_singleton(member);
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_copy(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *copy_bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	bms = decode_bytea_to_bms(bms_data);
+	copy_bms = bms_copy(bms);
+	result = encode_bms_to_bytea(copy_bms);
+
+	if (bms)
+		bms_free(bms);
+	if (copy_bms)
+		bms_free(copy_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_equal(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_equal(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_union(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_union(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_membership(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	BMS_Membership result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(BMS_EMPTY_SET);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+	result = bms_membership(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_next_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
+		PG_RETURN_INT32(-2);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+	prevmember = PG_GETARG_INT32(1);
+	result = bms_next_member(bms, prevmember);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_from_array(PG_FUNCTION_ARGS)
+{
+	ArrayType  *array;
+	int		   *members;
+	int			nmembers;
+	Bitmapset  *bms = NULL;
+	bytea	   *result;
+	int			i;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	array = PG_GETARG_ARRAYTYPE_P(0);
+
+	/* Check element type first */
+	if (ARR_ELEMTYPE(array) != INT4OID)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	/* Handle empty arrays - ARR_NDIM can be 0 for empty arrays */
+	if (ARR_NDIM(array) == 0)
+		PG_RETURN_NULL();
+
+	/* Now check dimensions */
+	if (ARR_NDIM(array) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	nmembers = ARR_DIMS(array)[0];
+
+	/* Double-check for empty */
+	if (nmembers == 0)
+		PG_RETURN_NULL();
+
+	if (ARR_HASNULL(array))
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	members = (int *) ARR_DATA_PTR(array);
+
+	for (i = 0; i < nmembers; i++)
+		bms = bms_add_member(bms, members[i]);
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_to_array(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	ArrayType  *result;
+	Datum	   *datums;
+	int			nmembers;
+	int			member = -1;
+	int			i = 0;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	bms = decode_bytea_to_bms(bms_data);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	nmembers = bms_num_members(bms);
+	datums = (Datum *) palloc(nmembers * sizeof(Datum));
+
+	while ((member = bms_next_member(bms, member)) >= 0)
+		datums[i++] = Int32GetDatum(member);
+
+	bms_free(bms);
+
+	result = construct_array(datums, nmembers,
+							 INT4OID, sizeof(int32), true, 'i');
+
+	pfree(datums);
+	PG_RETURN_ARRAYTYPE_P(result);
+}
+
+Datum
+test_bms_intersect(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_intersect(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_is_empty(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	result = bms_is_empty(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_is_subset(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_is_subset(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_subset_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	BMS_Comparison result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_subset_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	result = bms_singleton_member(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_get_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		default_member = PG_GETARG_INT32(1);
+	int			member;
+	bool		success;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(default_member);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	/*
+	 * bms_get_singleton_member returns bool and stores result in member
+	 * pointer
+	 */
+	success = bms_get_singleton_member(bms, &member);
+	bms_free(bms);
+
+	if (success)
+		PG_RETURN_INT32(member);
+	else
+		PG_RETURN_INT32(default_member);
+}
+
+Datum
+test_bms_prev_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-2);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	prevmember = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-2);
+
+	bms = decode_bytea_to_bms(bms_data);
+	result = bms_prev_member(bms, prevmember);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_overlap(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_overlap(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_overlap_list(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	ArrayType  *array;
+	List	   *bitmapset_list = NIL;
+	ListCell   *lc;
+	bool		result;
+	Datum	   *elem_datums;
+	bool	   *elem_nulls;
+	int			elem_count;
+	int			i;
+
+	/* Handle first argument (the bitmapset) */
+	if (PG_ARGISNULL(0))
+		PG_RETURN_BOOL(false);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	/* Handle second argument (array of bitmapsets) */
+	if (PG_ARGISNULL(1))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_BOOL(false);
+	}
+
+	array = PG_GETARG_ARRAYTYPE_P(1);
+
+	/* Validate array */
+	if (ARR_NDIM(array) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("one-dimensional array expected")));
+
+	if (ARR_ELEMTYPE(array) != BYTEAOID)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATATYPE_MISMATCH),
+				 errmsg("bytea array expected")));
+
+	/* Deconstruct the array */
+	deconstruct_array(array,
+					  BYTEAOID, -1, false, 'i',
+					  &elem_datums, &elem_nulls, &elem_count);
+
+	/* Convert each bytea element to a Bitmapset and add to list */
+	for (i = 0; i < elem_count; i++)
+	{
+		Bitmapset  *list_bms = NULL;
+
+		if (!elem_nulls[i])
+		{
+			bytea	   *elem_bytea = DatumGetByteaP(elem_datums[i]);
+
+			list_bms = decode_bytea_to_bms(elem_bytea);
+		}
+
+		/* Add to list (even if NULL) */
+		bitmapset_list = lappend(bitmapset_list, list_bms);
+	}
+
+	/* Call the actual bms_overlap_list function */
+	result = bms_overlap_list(bms, bitmapset_list);
+
+	/* Clean up */
+	if (bms)
+		bms_free(bms);
+
+	/* Free all bitmapsets in the list */
+	foreach(lc, bitmapset_list)
+	{
+		Bitmapset  *list_bms = (Bitmapset *) lfirst(lc);
+
+		if (list_bms)
+			bms_free(list_bms);
+	}
+	list_free(bitmapset_list);
+
+	/* Free array deconstruction results */
+	pfree(elem_datums);
+	pfree(elem_nulls);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_nonempty_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_nonempty_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_member_index(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		member;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-1);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	member = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-1);
+
+	bms = decode_bytea_to_bms(bms_data);
+
+	result = bms_member_index(bms, member);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_add_range(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		lower,
+				upper;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	lower = PG_GETARG_INT32(1);
+	upper = PG_GETARG_INT32(2);
+
+	/* Check for invalid range */
+	if (upper < lower)
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	bms = bms_add_range(bms, lower, upper);
+
+	result = encode_bms_to_bytea(bms);
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_replace_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_replace_members modifies/frees the first argument */
+	result_bms = bms_replace_members(bms1, bms2);
+	/* bms1 is now invalid, don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_join(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_join modifies/frees the first argument */
+	result_bms = bms_join(bms1, bms2);
+	/* bms1 is now invalid! Don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_hash_value(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	hash_result = bms_hash_value(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_hash(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	Bitmapset  *bms_ptr;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	bms_ptr = bms;
+
+	/* Call bitmap_hash */
+	hash_result = bitmap_hash(&bms_ptr, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (!PG_ARGISNULL(0) && bms_ptr)
+		bms_free(bms_ptr);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_match(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *bms_ptr1,
+			   *bms_ptr2;
+	int			match_result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* Set up pointers to the Bitmapsets */
+	bms_ptr1 = bms1;
+	bms_ptr2 = bms2;
+
+	/* Call bitmap_match with addresses of the Bitmapset pointers */
+	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(match_result);
+}
+
+Datum
+test_random_operations(PG_FUNCTION_ARGS)
+{
+	pg_prng_state state;
+	int32		seed;
+	int32		num_ops;
+	Bitmapset  *bms = NULL;
+	int			op,
+				member;
+	int			total_ops = 0;
+
+	seed = PG_GETARG_INT32(0);
+	num_ops = PG_GETARG_INT32(1);
+
+	pg_prng_seed(&state, (uint64) seed);
+
+	for (int i = 0; i < num_ops; i++)
+	{
+		op = pg_prng_uint32(&state) % 3;	/* 0=add, 1=delete, 2=test */
+		member = pg_prng_uint32(&state) % 1000;
+
+		switch (op)
+		{
+			case 0:				/* add */
+				bms = bms_add_member(bms, member);
+				total_ops++;
+				break;
+			case 1:				/* delete */
+				if (bms != NULL)
+				{
+					bms = bms_del_member(bms, member);
+					total_ops++;
+				}
+				break;
+			case 2:				/* test membership */
+				if (bms != NULL)
+				{
+					bms_is_member(member, bms);
+					total_ops++;
+				}
+				break;
+		}
+	}
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(total_ops);
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#23Robert Haas
robertmhaas@gmail.com
In reply to: Greg Burd (#22)
Re: [PATCH] Add tests for Bitmapset

On Wed, Sep 17, 2025 at 9:18 AM Greg Burd <greg@burd.me> wrote:

+static void
+elog_bitmapset(int elevel, const char *label, const Bitmapset *bms)

I added a function bms_values() that prints out the values contained in
a bitmapset and changed a few tests to use it. I removed the
elog_bitmapset() as it isn't being used and now that it's easy to output
the set in SQL why keep it for debugging?

How about using outBitmapset() which already exists?

--
Robert Haas
EDB: http://www.enterprisedb.com

#24Greg Burd
greg@burd.me
In reply to: Robert Haas (#23)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 17 2025, at 9:55 am, Robert Haas <robertmhaas@gmail.com> wrote:

On Wed, Sep 17, 2025 at 9:18 AM Greg Burd <greg@burd.me> wrote:

+static void
+elog_bitmapset(int elevel, const char *label, const Bitmapset *bms)

I added a function bms_values() that prints out the values contained in
a bitmapset and changed a few tests to use it. I removed the
elog_bitmapset() as it isn't being used and now that it's easy to output
the set in SQL why keep it for debugging?

How about using outBitmapset() which already exists?

Robert,

Thanks for chiming in, not sure how I missed that one. :)

--
Robert Haas
EDB: http://www.enterprisedb.com

I've updated the hash value for 32bit systems and changed the
bms_values() function to use outBitmapset() via bmsToString().

best.

-greg

Attachments:

v6-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From 2ba16fa314b01931a7fe20bec0e2917237df88ea Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v6] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |    1 +
 src/test/modules/meson.build                  |    1 +
 src/test/modules/test_bitmapset/.gitignore    |    4 +
 src/test/modules/test_bitmapset/Makefile      |   23 +
 .../expected/test_bitmapset.out               |  634 ++++++++++
 src/test/modules/test_bitmapset/meson.build   |   33 +
 .../test_bitmapset/sql/test_bitmapset.sql     |  372 ++++++
 .../test_bitmapset/test_bitmapset--1.0.sql    |  155 +++
 .../modules/test_bitmapset/test_bitmapset.c   | 1079 +++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |    4 +
 10 files changed, 2306 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..e609ec1c5e6
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,634 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+-- BASIC FUNCTIONALITY TESTS
+-- Test bms_values function
+SELECT 'values NULL' as test, bms_values(NULL) as result;
+    test     | result 
+-------------+--------
+ values NULL | (b)
+(1 row)
+
+SELECT 'values empty' as test, bms_values(test_bms_from_array(ARRAY[]::integer[])) as result;
+     test     | result 
+--------------+--------
+ values empty | (b)
+(1 row)
+
+SELECT 'values singleton' as test, bms_values(test_bms_make_singleton(42)) as result;
+       test       | result 
+------------------+--------
+ values singleton | (b 42)
+(1 row)
+
+SELECT 'values small set' as test, bms_values(test_bms_from_array(ARRAY[1,3,5])) as result;
+       test       |  result   
+------------------+-----------
+ values small set | (b 1 3 5)
+(1 row)
+
+SELECT 'values larger set' as test, bms_values(test_bms_from_array(ARRAY[0,5,10,15,20])) as result;
+       test        |      result      
+-------------------+------------------
+ values larger set | (b 0 5 10 15 20)
+(1 row)
+
+SELECT 'values unsorted input' as test, bms_values(test_bms_from_array(ARRAY[20,5,15,0,10])) as result;
+         test          |      result      
+-----------------------+------------------
+ values unsorted input | (b 0 5 10 15 20)
+(1 row)
+
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+           test           | result 
+--------------------------+--------
+ NULL input to from_array | t
+(1 row)
+
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+           test            | result 
+---------------------------+--------
+ Empty array to from_array | t
+(1 row)
+
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+          test          | result 
+------------------------+--------
+ NULL input to to_array | t
+(1 row)
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+        test        | result 
+--------------------+--------
+ make_singleton(42) | t
+(1 row)
+
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+       test        | result 
+-------------------+--------
+ make_singleton(0) | t
+(1 row)
+
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+         test         | result 
+----------------------+--------
+ make_singleton(1000) | t
+(1 row)
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+         test         | result 
+----------------------+--------
+ add_member(NULL, 10) | t
+(1 row)
+
+SELECT 'add_member consistency' as test, bms_values(test_bms_add_member(NULL, 10)) as values;
+          test          | values 
+------------------------+--------
+ add_member consistency | (b 10)
+(1 row)
+
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+          test          | result 
+------------------------+--------
+ add_member to existing | t
+(1 row)
+
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+       test        | result 
+-------------------+--------
+ add_member sorted | t
+(1 row)
+
+SELECT 'add_member idempotent' as test, bms_values(test_bms_add_member(test_bms_make_singleton(10), 10)) as values;
+         test          | values 
+-----------------------+--------
+ add_member idempotent | (b 10)
+(1 row)
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+         test         | result 
+----------------------+--------
+ del_member from NULL | t
+(1 row)
+
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+                test                | result 
+------------------------------------+--------
+ del_member singleton becomes empty | t
+(1 row)
+
+SELECT 'del_member no change' as test, bms_values(test_bms_del_member(test_bms_make_singleton(10), 5)) as values;
+         test         | values 
+----------------------+--------
+ del_member no change | (b 10)
+(1 row)
+
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+          test          | result 
+------------------------+--------
+ del_member from middle | t
+(1 row)
+
+-- SET OPERATIONS TESTS
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+          test          | result 
+------------------------+--------
+ union overlapping sets | t
+ union with NULL        | t
+ union NULL with NULL   | t
+(3 rows)
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+            test            | result 
+----------------------------+--------
+ intersect overlapping sets | t
+ intersect disjoint sets    | t
+ intersect with NULL        | t
+(3 rows)
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+            test             | result 
+-----------------------------+--------
+ difference overlapping sets | t
+ difference disjoint sets    | t
+ difference identical sets   | t
+(3 rows)
+
+-- MEMBERSHIP AND COMPARISON TESTS
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+           test            | result 
+---------------------------+--------
+ is_member existing        | t
+ is_member missing         | t
+ is_member existing middle | t
+ is_member NULL set        | t
+(4 rows)
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ num_members NULL | t
+(1 row)
+
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+         test          | result 
+-----------------------+--------
+ num_members small set | t
+(1 row)
+
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+          test          | result 
+------------------------+--------
+ num_members larger set | t
+(1 row)
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+          test           | result 
+-------------------------+--------
+ equal NULL NULL         | t
+ equal NULL set          | t
+ equal set NULL          | t
+ equal identical sets    | t
+ equal different sets    | t
+ compare NULL NULL       | t
+ compare NULL set        | t
+ compare set NULL        | t
+ compare equal sets      | t
+ compare subset superset | t
+ compare superset subset | t
+(11 rows)
+
+-- ADVANCED OPERATIONS TESTS
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+      test       | result 
+-----------------+--------
+ add_range basic | t
+(1 row)
+
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+           test           | result 
+--------------------------+--------
+ add_range single element | t
+(1 row)
+
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+         test          | result 
+-----------------------+--------
+ add_range to existing | t
+(1 row)
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ membership empty | t
+(1 row)
+
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+         test         | result 
+----------------------+--------
+ membership singleton | t
+(1 row)
+
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+        test         | result 
+---------------------+--------
+ membership multiple | t
+(1 row)
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+          test          | result 
+------------------------+--------
+ singleton_member valid | t
+(1 row)
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+            test            | result 
+----------------------------+--------
+ next_member first          | t
+ next_member second         | t
+ next_member past end       | t
+ next_member empty set      | t
+ prev_member last           | t
+ prev_member penultimate    | t
+ prev_member past beginning | t
+ prev_member empty set      | t
+(8 rows)
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_135a) = test_bms_hash_value(set_135b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_135a) != test_bms_hash_value(set_246) as result FROM test_sets;
+        test         | result 
+---------------------+--------
+ hash NULL           | t
+ hash consistency    | t
+ hash different sets | t
+(3 rows)
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+       test        | result 
+-------------------+--------
+ overlap existing  | t
+ overlap none      | t
+ overlap with NULL | t
+(3 rows)
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets;
+             test             | result 
+------------------------------+--------
+ subset NULL is subset of all | t
+ subset proper subset         | t
+ subset improper subset       | t
+ subset disjoint sets         | t
+(4 rows)
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+     test      | result 
+---------------+--------
+ copy NULL     | t
+ copy equality | t
+(2 rows)
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+         test          | result 
+-----------------------+--------
+ add_members operation | t
+(1 row)
+
+-- Test 20: Test hash consistency
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+             test              | result 
+-------------------------------+--------
+ bitmap_hash NULL              | t
+ bitmap_hash consistency       | t
+ bitmap_hash vs bms_hash_value | t
+ bitmap_hash different sets    | t
+(4 rows)
+
+-- Architecture-aware hash testing
+WITH arch_info AS (
+    SELECT
+        CASE
+            WHEN pg_column_size(1::bigint) = 8 THEN '64bit'
+            ELSE '32bit'
+        END as architecture
+),
+expected_values AS (
+    SELECT
+        architecture,
+        CASE architecture
+            WHEN '64bit' THEN 0
+            WHEN '32bit' THEN 0
+        END as hash_null,
+        CASE architecture
+            WHEN '64bit' THEN 49870778
+            WHEN '32bit' THEN 1509752520
+        END as hash_135,
+        CASE architecture
+            WHEN '64bit' THEN -303921606
+            WHEN '32bit' THEN -507280666
+        END as hash_246
+    FROM arch_info
+)
+SELECT 'expected hash NULL' as test,
+       test_bitmap_hash(NULL) = hash_null as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [1,3,5]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[1,3,5])) = hash_135 as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [2,4,6]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[2,4,6])) = hash_246 as result
+FROM expected_values;
+         test          | result 
+-----------------------+--------
+ expected hash NULL    | t
+ expected hash [1,3,5] | t
+ expected hash [2,4,6] | t
+(3 rows)
+
+-- Test 21: bitmap_match function
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match NULL NULL (should be 0)       | t
+ bitmap_match NULL set (should be 1)        | t
+ bitmap_match set NULL (should be 1)        | t
+ bitmap_match identical sets (should be 0)  | t
+ bitmap_match different sets (should be 1)  | t
+ bitmap_match subset/superset (should be 1) | t
+(6 rows)
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match vs bms_equal (equal sets)     | t
+ bitmap_match vs bms_equal (different sets) | t
+ bitmap_match vs bms_equal (NULL cases)     | t
+(3 rows)
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [1,3,5] |           0
+(1 row)
+
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [2,4,6] |           1
+(1 row)
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+           test            | result 
+---------------------------+--------
+ bitmap_match empty arrays | t
+(1 row)
+
+-- Test 22: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(12345, 1000) > 0 as result;
+       test        | result 
+-------------------+--------
+ random operations | t
+(1 row)
+
+-- ERROR CONDITION TESTS
+-- Test 23: Error conditions (these should produce ERRORs)
+-- Negative member tests
+SELECT test_bms_make_singleton(-1);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_is_member(NULL, -5);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_member(NULL, -10);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_del_member(NULL, -20);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_range(NULL, -5, 10);
+ERROR:  negative bitmapset member not allowed
+-- Singleton member errors
+SELECT test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+ERROR:  bitmapset has multiple members
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..cb3496f45f5
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,372 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+
+-- BASIC FUNCTIONALITY TESTS
+
+-- Test bms_values function
+
+SELECT 'values NULL' as test, bms_values(NULL) as result;
+SELECT 'values empty' as test, bms_values(test_bms_from_array(ARRAY[]::integer[])) as result;
+SELECT 'values singleton' as test, bms_values(test_bms_make_singleton(42)) as result;
+SELECT 'values small set' as test, bms_values(test_bms_from_array(ARRAY[1,3,5])) as result;
+SELECT 'values larger set' as test, bms_values(test_bms_from_array(ARRAY[0,5,10,15,20])) as result;
+SELECT 'values unsorted input' as test, bms_values(test_bms_from_array(ARRAY[20,5,15,0,10])) as result;
+
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+SELECT 'add_member consistency' as test, bms_values(test_bms_add_member(NULL, 10)) as values;
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+SELECT 'add_member idempotent' as test, bms_values(test_bms_add_member(test_bms_make_singleton(10), 10)) as values;
+
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+SELECT 'del_member no change' as test, bms_values(test_bms_del_member(test_bms_make_singleton(10), 5)) as values;
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+
+-- SET OPERATIONS TESTS
+
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+
+-- MEMBERSHIP AND COMPARISON TESTS
+
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+
+-- ADVANCED OPERATIONS TESTS
+
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_135a) = test_bms_hash_value(set_135b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_135a) != test_bms_hash_value(set_246) as result FROM test_sets;
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets;
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+
+-- Test 20: Test hash consistency
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+
+-- Architecture-aware hash testing
+WITH arch_info AS (
+    SELECT
+        CASE
+            WHEN pg_column_size(1::bigint) = 8 THEN '64bit'
+            ELSE '32bit'
+        END as architecture
+),
+expected_values AS (
+    SELECT
+        architecture,
+        CASE architecture
+            WHEN '64bit' THEN 0
+            WHEN '32bit' THEN 0
+        END as hash_null,
+        CASE architecture
+            WHEN '64bit' THEN 49870778
+            WHEN '32bit' THEN 1509752520
+        END as hash_135,
+        CASE architecture
+            WHEN '64bit' THEN -303921606
+            WHEN '32bit' THEN -507280666
+        END as hash_246
+    FROM arch_info
+)
+SELECT 'expected hash NULL' as test,
+       test_bitmap_hash(NULL) = hash_null as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [1,3,5]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[1,3,5])) = hash_135 as result
+FROM expected_values
+UNION ALL
+SELECT 'expected hash [2,4,6]' as test,
+       test_bitmap_hash(test_bms_from_array(ARRAY[2,4,6])) = hash_246 as result
+FROM expected_values;
+
+-- Test 21: bitmap_match function
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+
+-- Test 22: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(12345, 1000) > 0 as result;
+
+-- ERROR CONDITION TESTS
+
+-- Test 23: Error conditions (these should produce ERRORs)
+
+-- Negative member tests
+SELECT test_bms_make_singleton(-1);
+SELECT test_bms_is_member(NULL, -5);
+SELECT test_bms_add_member(NULL, -10);
+SELECT test_bms_del_member(NULL, -20);
+SELECT test_bms_add_range(NULL, -5, 10);
+
+-- Singleton member errors
+SELECT test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..bcac98e2d85
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,155 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+-- Utility functions
+CREATE FUNCTION test_bms_from_array(integer[])
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_to_array(bytea)
+RETURNS integer[]
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION bms_values(bytea)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C STABLE;
+
+-- Bitmapset API functions
+CREATE FUNCTION test_bms_make_singleton(integer)
+RETURNS bytea STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_member(bytea, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_del_member(bytea, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_member(bytea, integer)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_num_members(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_copy(bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_equal(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_compare(bytea, bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_subset(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_subset_compare(bytea, bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_union(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_intersect(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_difference(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_empty(bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_membership(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_singleton_member(bytea)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_get_singleton_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_next_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_prev_member(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_hash_value(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap_list(bytea, bytea[])
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_nonempty_difference(bytea, bytea)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_member_index(bytea, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_range(bytea, integer, integer)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_members(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_replace_members(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_join(bytea, bytea)
+RETURNS bytea
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_hash(bytea)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_match(bytea, bytea)
+RETURNS int
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+-- Test utility functions
+CREATE FUNCTION test_random_operations(integer, integer)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION create_test_bitmapset(members integer[])
+RETURNS bytea
+LANGUAGE SQL
+AS $$
+    SELECT CASE WHEN $1 IS NULL OR array_length($1, 1) = 0
+	   THEN NULL::bytea
+	   ELSE bitmapset_to_bytea($1)
+	   END;
+$$;
+
+COMMENT ON EXTENSION test_bitmapset IS 'Test code for Bitmapset';
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..6dddd22b170
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,1079 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include <stddef.h>
+#include <string.h>
+
+#include "catalog/pg_type.h"
+#include "common/pg_prng.h"
+#include "utils/array.h"
+#include "fmgr.h"
+#include "nodes/bitmapset.h"
+#include "nodes/nodes.h"
+#include "nodes/pg_list.h"
+#include "utils/builtins.h"
+#include "varatt.h"
+
+PG_MODULE_MAGIC;
+
+/* Utility functions */
+PG_FUNCTION_INFO_V1(bms_values);
+PG_FUNCTION_INFO_V1(test_bms_from_array);
+PG_FUNCTION_INFO_V1(test_bms_to_array);
+
+/* Bitmapset API functions in order of appearance in bitmapset.c */
+PG_FUNCTION_INFO_V1(test_bms_make_singleton);
+PG_FUNCTION_INFO_V1(test_bms_add_member);
+PG_FUNCTION_INFO_V1(test_bms_del_member);
+PG_FUNCTION_INFO_V1(test_bms_is_member);
+PG_FUNCTION_INFO_V1(test_bms_num_members);
+PG_FUNCTION_INFO_V1(test_bms_copy);
+PG_FUNCTION_INFO_V1(test_bms_equal);
+PG_FUNCTION_INFO_V1(test_bms_compare);
+PG_FUNCTION_INFO_V1(test_bms_is_subset);
+PG_FUNCTION_INFO_V1(test_bms_subset_compare);
+PG_FUNCTION_INFO_V1(test_bms_union);
+PG_FUNCTION_INFO_V1(test_bms_intersect);
+PG_FUNCTION_INFO_V1(test_bms_difference);
+PG_FUNCTION_INFO_V1(test_bms_is_empty);
+PG_FUNCTION_INFO_V1(test_bms_membership);
+PG_FUNCTION_INFO_V1(test_bms_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_get_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_next_member);
+PG_FUNCTION_INFO_V1(test_bms_prev_member);
+PG_FUNCTION_INFO_V1(test_bms_hash_value);
+PG_FUNCTION_INFO_V1(test_bms_overlap);
+PG_FUNCTION_INFO_V1(test_bms_overlap_list);
+PG_FUNCTION_INFO_V1(test_bms_nonempty_difference);
+PG_FUNCTION_INFO_V1(test_bms_member_index);
+PG_FUNCTION_INFO_V1(test_bms_add_range);
+PG_FUNCTION_INFO_V1(test_bms_add_members);
+PG_FUNCTION_INFO_V1(test_bms_replace_members);
+PG_FUNCTION_INFO_V1(test_bms_join);
+PG_FUNCTION_INFO_V1(test_bitmap_hash);
+PG_FUNCTION_INFO_V1(test_bitmap_match);
+
+/* Test utility functions */
+PG_FUNCTION_INFO_V1(test_random_operations);
+
+/*
+ * Utility functions to convert between Bitmapset and bytea
+ * for passing data between SQL and C functions
+ */
+
+static bytea *
+encode_bms_to_bytea(Bitmapset *bms)
+{
+	bytea	   *result;
+	int			bms_size;
+
+	if (bms == NULL)
+		return NULL;
+
+	bms_size = offsetof(Bitmapset, words) + bms->nwords * sizeof(bitmapword);
+	result = (bytea *) palloc0(VARHDRSZ + bms_size);
+	memcpy(VARDATA(result), bms, bms_size);
+	SET_VARSIZE(result, VARHDRSZ + bms_size);
+
+	return result;
+}
+
+static Bitmapset *
+decode_bytea_to_bms(bytea *data)
+{
+	Bitmapset  *bms;
+	int			bms_size;
+
+	if (data == NULL)
+		return NULL;
+
+	bms_size = VARSIZE_ANY_EXHDR(data);
+
+	if (bms_size < offsetof(Bitmapset, words))
+		return NULL;
+
+	bms = (Bitmapset *) palloc(bms_size);
+	memcpy(bms, VARDATA_ANY(data), bms_size);
+
+	if (bms->nwords < 0 ||
+		bms->nwords > (bms_size - offsetof(Bitmapset, words)) / sizeof(bitmapword))
+	{
+		pfree(bms);
+		return NULL;
+	}
+
+	return bms;
+}
+
+Datum
+bms_values(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms;
+	char	   *str;
+	text	   *result;
+
+	if (PG_ARGISNULL(0))
+	{
+		result = cstring_to_text("(b)");
+		PG_RETURN_TEXT_P(result);
+	}
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+	str = bmsToString(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	result = cstring_to_text(str);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+/*
+ * Individual test functions for each bitmapset API function
+ */
+
+Datum
+test_bms_add_member(PG_FUNCTION_ARGS)
+{
+	int			member;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	result_bms = bms_add_member(bms, member);
+	result = encode_bms_to_bytea(result_bms);
+
+	if (bms && bms != result_bms)
+		bms_free(bms);
+	if (result_bms)
+		bms_free(result_bms);
+
+	if (result == NULL)
+		PG_RETURN_NULL();
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_add_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_add_members modifies/frees the first argument */
+	result_bms = bms_add_members(bms1, bms2);
+	/* bms1 is now invalid, don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_del_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	bms = bms_del_member(bms, member);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_is_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bool		result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_BOOL(false);
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	result = bms_is_member(member, bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_num_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result = 0;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	result = bms_num_members(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_make_singleton(PG_FUNCTION_ARGS)
+{
+	int32		member;
+	Bitmapset  *bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	member = PG_GETARG_INT32(0);
+	bms = bms_make_singleton(member);
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_copy(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *copy_bms;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	bms = decode_bytea_to_bms(bms_data);
+	copy_bms = bms_copy(bms);
+	result = encode_bms_to_bytea(copy_bms);
+
+	if (bms)
+		bms_free(bms);
+	if (copy_bms)
+		bms_free(copy_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_equal(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_equal(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_union(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_union(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_membership(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	BMS_Membership result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(BMS_EMPTY_SET);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+	result = bms_membership(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_next_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
+		PG_RETURN_INT32(-2);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+	prevmember = PG_GETARG_INT32(1);
+	result = bms_next_member(bms, prevmember);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_from_array(PG_FUNCTION_ARGS)
+{
+	ArrayType  *array;
+	int		   *members;
+	int			nmembers;
+	Bitmapset  *bms = NULL;
+	bytea	   *result;
+	int			i;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	array = PG_GETARG_ARRAYTYPE_P(0);
+
+	/* Check element type first */
+	if (ARR_ELEMTYPE(array) != INT4OID)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	/* Handle empty arrays - ARR_NDIM can be 0 for empty arrays */
+	if (ARR_NDIM(array) == 0)
+		PG_RETURN_NULL();
+
+	/* Now check dimensions */
+	if (ARR_NDIM(array) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	nmembers = ARR_DIMS(array)[0];
+
+	/* Double-check for empty */
+	if (nmembers == 0)
+		PG_RETURN_NULL();
+
+	if (ARR_HASNULL(array))
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	members = (int *) ARR_DATA_PTR(array);
+
+	for (i = 0; i < nmembers; i++)
+		bms = bms_add_member(bms, members[i]);
+
+	result = encode_bms_to_bytea(bms);
+	bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_to_array(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	ArrayType  *result;
+	Datum	   *datums;
+	int			nmembers;
+	int			member = -1;
+	int			i = 0;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	bms = decode_bytea_to_bms(bms_data);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	nmembers = bms_num_members(bms);
+	datums = (Datum *) palloc(nmembers * sizeof(Datum));
+
+	while ((member = bms_next_member(bms, member)) >= 0)
+		datums[i++] = Int32GetDatum(member);
+
+	bms_free(bms);
+
+	result = construct_array(datums, nmembers,
+							 INT4OID, sizeof(int32), true, 'i');
+
+	pfree(datums);
+	PG_RETURN_ARRAYTYPE_P(result);
+}
+
+Datum
+test_bms_intersect(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_intersect(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result_bms = bms_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_is_empty(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	result = bms_is_empty(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_is_subset(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_is_subset(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_subset_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	BMS_Comparison result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_subset_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	result = bms_singleton_member(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_get_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		default_member = PG_GETARG_INT32(1);
+	int			member;
+	bool		success;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(default_member);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	/*
+	 * bms_get_singleton_member returns bool and stores result in member
+	 * pointer
+	 */
+	success = bms_get_singleton_member(bms, &member);
+	bms_free(bms);
+
+	if (success)
+		PG_RETURN_INT32(member);
+	else
+		PG_RETURN_INT32(default_member);
+}
+
+Datum
+test_bms_prev_member(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-2);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	prevmember = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-2);
+
+	bms = decode_bytea_to_bms(bms_data);
+	result = bms_prev_member(bms, prevmember);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_overlap(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_overlap(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_overlap_list(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	ArrayType  *array;
+	List	   *bitmapset_list = NIL;
+	ListCell   *lc;
+	bool		result;
+	Datum	   *elem_datums;
+	bool	   *elem_nulls;
+	int			elem_count;
+	int			i;
+
+	/* Handle first argument (the bitmapset) */
+	if (PG_ARGISNULL(0))
+		PG_RETURN_BOOL(false);
+
+	bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	/* Handle second argument (array of bitmapsets) */
+	if (PG_ARGISNULL(1))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_BOOL(false);
+	}
+
+	array = PG_GETARG_ARRAYTYPE_P(1);
+
+	/* Validate array */
+	if (ARR_NDIM(array) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("one-dimensional array expected")));
+
+	if (ARR_ELEMTYPE(array) != BYTEAOID)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATATYPE_MISMATCH),
+				 errmsg("bytea array expected")));
+
+	/* Deconstruct the array */
+	deconstruct_array(array,
+					  BYTEAOID, -1, false, 'i',
+					  &elem_datums, &elem_nulls, &elem_count);
+
+	/* Convert each bytea element to a Bitmapset and add to list */
+	for (i = 0; i < elem_count; i++)
+	{
+		Bitmapset  *list_bms = NULL;
+
+		if (!elem_nulls[i])
+		{
+			bytea	   *elem_bytea = DatumGetByteaP(elem_datums[i]);
+
+			list_bms = decode_bytea_to_bms(elem_bytea);
+		}
+
+		/* Add to list (even if NULL) */
+		bitmapset_list = lappend(bitmapset_list, list_bms);
+	}
+
+	/* Call the actual bms_overlap_list function */
+	result = bms_overlap_list(bms, bitmapset_list);
+
+	/* Clean up */
+	if (bms)
+		bms_free(bms);
+
+	/* Free all bitmapsets in the list */
+	foreach(lc, bitmapset_list)
+	{
+		Bitmapset  *list_bms = (Bitmapset *) lfirst(lc);
+
+		if (list_bms)
+			bms_free(list_bms);
+	}
+	list_free(bitmapset_list);
+
+	/* Free array deconstruction results */
+	pfree(elem_datums);
+	pfree(elem_nulls);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_nonempty_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	result = bms_nonempty_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_member_index(PG_FUNCTION_ARGS)
+{
+	bytea	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		member;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-1);
+
+	bms_data = PG_GETARG_BYTEA_PP(0);
+	member = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-1);
+
+	bms = decode_bytea_to_bms(bms_data);
+
+	result = bms_member_index(bms, member);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_add_range(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		lower,
+				upper;
+	bytea	   *result;
+
+	if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	lower = PG_GETARG_INT32(1);
+	upper = PG_GETARG_INT32(2);
+
+	/* Check for invalid range */
+	if (upper < lower)
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	bms = bms_add_range(bms, lower, upper);
+
+	result = encode_bms_to_bytea(bms);
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_replace_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_replace_members modifies/frees the first argument */
+	result_bms = bms_replace_members(bms1, bms2);
+	/* bms1 is now invalid, don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_join(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	bytea	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* IMPORTANT: bms_join modifies/frees the first argument */
+	result_bms = bms_join(bms1, bms2);
+	/* bms1 is now invalid! Don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_bytea(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_BYTEA_P(result);
+}
+
+Datum
+test_bms_hash_value(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	hash_result = bms_hash_value(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_hash(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	Bitmapset  *bms_ptr;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	bms_ptr = bms;
+
+	/* Call bitmap_hash */
+	hash_result = bitmap_hash(&bms_ptr, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (!PG_ARGISNULL(0) && bms_ptr)
+		bms_free(bms_ptr);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_match(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *bms_ptr1,
+			   *bms_ptr2;
+	int			match_result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_bytea_to_bms(PG_GETARG_BYTEA_PP(1));
+
+	/* Set up pointers to the Bitmapsets */
+	bms_ptr1 = bms1;
+	bms_ptr2 = bms2;
+
+	/* Call bitmap_match with addresses of the Bitmapset pointers */
+	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(match_result);
+}
+
+Datum
+test_random_operations(PG_FUNCTION_ARGS)
+{
+	pg_prng_state state;
+	int32		seed;
+	int32		num_ops;
+	Bitmapset  *bms = NULL;
+	int			op,
+				member;
+	int			total_ops = 0;
+
+	seed = PG_GETARG_INT32(0);
+	num_ops = PG_GETARG_INT32(1);
+
+	pg_prng_seed(&state, (uint64) seed);
+
+	for (int i = 0; i < num_ops; i++)
+	{
+		op = pg_prng_uint32(&state) % 3;	/* 0=add, 1=delete, 2=test */
+		member = pg_prng_uint32(&state) % 1000;
+
+		switch (op)
+		{
+			case 0:				/* add */
+				bms = bms_add_member(bms, member);
+				total_ops++;
+				break;
+			case 1:				/* delete */
+				if (bms != NULL)
+				{
+					bms = bms_del_member(bms, member);
+					total_ops++;
+				}
+				break;
+			case 2:				/* test membership */
+				if (bms != NULL)
+				{
+					bms_is_member(member, bms);
+					total_ops++;
+				}
+				break;
+		}
+	}
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(total_ops);
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#25Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#24)
Re: [PATCH] Add tests for Bitmapset

On Wed, Sep 17, 2025 at 10:53:26AM -0400, Greg Burd wrote:

I've updated the hash value for 32bit systems and changed the
bms_values() function to use outBitmapset() via bmsToString().

Oh, right, I also forgot that we have node functions for that.

And actually, could it be better to use nodeRead() to translate the
inputs? I've just remembered that we have some custom code in there
with other lists, which is documented for the purpose of extensions
with extensible nodes.
--
Michael

#26Greg Burd
greg@burd.me
In reply to: Michael Paquier (#25)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

Hello hackers, :)

Thanks for all the feedback and time spent reviewing this patch. I
switched out the encode/decode functions to use the nodeToString() and
stringToNode() functions and change all the SQL testing function
signatures to TEXT from BYTEA. This exercises more code and that's good
for testing purposes. I took out the code that checks the hash values,
I can't think of a reason that should cause a future failure should that
change and output different values. I re-integrated the earlier random
testing function along with the newer code. I'm not sure this buys us
much if anything.

coverage: HEAD v7
lines......: 87.1 90.5 +3.4%
functions..: 100.0 100.0 +0.0%
branches...: 63.5 75.9 +12.4%

best.

-greg

Attachments:

v7-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From 01614da5dcf5746324ede84f6c58e6240ae7f1a4 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v7] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |    1 +
 src/test/modules/meson.build                  |    1 +
 src/test/modules/test_bitmapset/.gitignore    |    4 +
 src/test/modules/test_bitmapset/Makefile      |   23 +
 .../expected/test_bitmapset.out               |  757 +++++++++++
 src/test/modules/test_bitmapset/meson.build   |   33 +
 .../test_bitmapset/sql/test_bitmapset.sql     |  413 ++++++
 .../test_bitmapset/test_bitmapset--1.0.sql    |  149 +++
 .../modules/test_bitmapset/test_bitmapset.c   | 1179 +++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |    4 +
 10 files changed, 2564 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..ecae584bd45
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,757 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+-- BASIC FUNCTIONALITY TESTS
+-- Test bms_values function
+SELECT 'values NULL' as test, bms_values(NULL) as result;
+    test     | result 
+-------------+--------
+ values NULL | (b)
+(1 row)
+
+SELECT 'values empty' as test, bms_values(test_bms_from_array(ARRAY[]::integer[])) as result;
+     test     | result 
+--------------+--------
+ values empty | (b)
+(1 row)
+
+SELECT 'values singleton' as test, bms_values(test_bms_make_singleton(42)) as result;
+       test       | result 
+------------------+--------
+ values singleton | (b 42)
+(1 row)
+
+SELECT 'values small set' as test, bms_values(test_bms_from_array(ARRAY[1,3,5])) as result;
+       test       |  result   
+------------------+-----------
+ values small set | (b 1 3 5)
+(1 row)
+
+SELECT 'values larger set' as test, bms_values(test_bms_from_array(ARRAY[0,5,10,15,20])) as result;
+       test        |      result      
+-------------------+------------------
+ values larger set | (b 0 5 10 15 20)
+(1 row)
+
+SELECT 'values unsorted input' as test, bms_values(test_bms_from_array(ARRAY[20,5,15,0,10])) as result;
+         test          |      result      
+-----------------------+------------------
+ values unsorted input | (b 0 5 10 15 20)
+(1 row)
+
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+           test           | result 
+--------------------------+--------
+ NULL input to from_array | t
+(1 row)
+
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+           test            | result 
+---------------------------+--------
+ Empty array to from_array | t
+(1 row)
+
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+          test          | result 
+------------------------+--------
+ NULL input to to_array | t
+(1 row)
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+        test        | result 
+--------------------+--------
+ make_singleton(42) | t
+(1 row)
+
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+       test        | result 
+-------------------+--------
+ make_singleton(0) | t
+(1 row)
+
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+         test         | result 
+----------------------+--------
+ make_singleton(1000) | t
+(1 row)
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+         test         | result 
+----------------------+--------
+ add_member(NULL, 10) | t
+(1 row)
+
+SELECT 'add_member consistency' as test, bms_values(test_bms_add_member(NULL, 10)) as values;
+          test          | values 
+------------------------+--------
+ add_member consistency | (b 10)
+(1 row)
+
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+          test          | result 
+------------------------+--------
+ add_member to existing | t
+(1 row)
+
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+       test        | result 
+-------------------+--------
+ add_member sorted | t
+(1 row)
+
+SELECT 'add_member idempotent' as test, bms_values(test_bms_add_member(test_bms_make_singleton(10), 10)) as values;
+         test          | values 
+-----------------------+--------
+ add_member idempotent | (b 10)
+(1 row)
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+         test         | result 
+----------------------+--------
+ del_member from NULL | t
+(1 row)
+
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+                test                | result 
+------------------------------------+--------
+ del_member singleton becomes empty | t
+(1 row)
+
+SELECT 'del_member no change' as test, bms_values(test_bms_del_member(test_bms_make_singleton(10), 5)) as values;
+         test         | values 
+----------------------+--------
+ del_member no change | (b 10)
+(1 row)
+
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+          test          | result 
+------------------------+--------
+ del_member from middle | t
+(1 row)
+
+SELECT 'del_member triggers realloc' as test, test_bms_del_member(test_bms_del_member(test_bms_from_array(ARRAY[0,31,32,63,64]), 32), 63) as result;
+            test             |   result    
+-----------------------------+-------------
+ del_member triggers realloc | (b 0 31 64)
+(1 row)
+
+SELECT 'del_member word boundary' as test,
+       bms_values(test_bms_del_member(
+           test_bms_add_range(NULL, 30, 34),
+           32
+       )) as result;
+           test           |     result      
+--------------------------+-----------------
+ del_member word boundary | (b 30 31 33 34)
+(1 row)
+
+-- SET OPERATIONS TESTS
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+          test          | result 
+------------------------+--------
+ union overlapping sets | t
+ union with NULL        | t
+ union NULL with NULL   | t
+(3 rows)
+
+SELECT 'overlapping ranges' as test,
+       bms_values(test_bms_union(
+           test_bms_add_range(NULL, 50, 150),
+           test_bms_add_range(NULL, 100, 200)
+       )) as result;
+        test        |                                                                                                                                                                                                                                                                                    result                                                                                                                                                                                                                                                                                     
+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ overlapping ranges | (b 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)
+(1 row)
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+            test            | result 
+----------------------------+--------
+ intersect overlapping sets | t
+ intersect disjoint sets    | t
+ intersect with NULL        | t
+(3 rows)
+
+-- Test bms_int_members
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'int(ersect) overlapping sets' as test,
+       test_bms_to_array(test_bms_int_members(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'int(ersect) disjoint sets' as test,
+       test_bms_int_members(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'int(ersect) with NULL' as test,
+       test_bms_int_members(set_135, NULL) IS NULL as result
+FROM test_sets;
+             test             | result 
+------------------------------+--------
+ int(ersect) overlapping sets | t
+ int(ersect) disjoint sets    | t
+ int(ersect) with NULL        | t
+(3 rows)
+
+SELECT 'int(ersect) members' as test,
+       bms_values(test_bms_int_members(
+           test_bms_from_array(ARRAY[0,31,32,63,64]),
+           test_bms_from_array(ARRAY[31,32,64,65])
+       )) as result;
+        test         |    result    
+---------------------+--------------
+ int(ersect) members | (b 31 32 64)
+(1 row)
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+            test             | result 
+-----------------------------+--------
+ difference overlapping sets | t
+ difference disjoint sets    | t
+ difference identical sets   | t
+(3 rows)
+
+SELECT 'difference subtraction edge case' as test,
+       bms_values(test_bms_difference(
+           test_bms_add_range(NULL, 0, 100),
+           test_bms_add_range(NULL, 50, 150)
+       )) as result;
+               test               |                                                                     result                                                                      
+----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------
+ difference subtraction edge case | (b 0 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)
+(1 row)
+
+SELECT 'difference subtract to empty' as test,
+       bms_values(test_bms_difference(
+           test_bms_make_singleton(42),
+           test_bms_make_singleton(42)
+       )) as result;
+             test             | result 
+------------------------------+--------
+ difference subtract to empty | (b)
+(1 row)
+
+-- MEMBERSHIP AND COMPARISON TESTS
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+           test            | result 
+---------------------------+--------
+ is_member existing        | t
+ is_member missing         | t
+ is_member existing middle | t
+ is_member NULL set        | t
+(4 rows)
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ num_members NULL | t
+(1 row)
+
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+         test          | result 
+-----------------------+--------
+ num_members small set | t
+(1 row)
+
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+          test          | result 
+------------------------+--------
+ num_members larger set | t
+(1 row)
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+          test           | result 
+-------------------------+--------
+ equal NULL NULL         | t
+ equal NULL set          | t
+ equal set NULL          | t
+ equal identical sets    | t
+ equal different sets    | t
+ compare NULL NULL       | t
+ compare NULL set        | t
+ compare set NULL        | t
+ compare equal sets      | t
+ compare subset superset | t
+ compare superset subset | t
+(11 rows)
+
+SELECT 'compare edge case' as test,
+       test_bms_compare(
+           test_bms_add_range(NULL, 0, 63),
+           test_bms_add_range(NULL, 0, 64)
+       ) as result;
+       test        | result 
+-------------------+--------
+ compare edge case |     -1
+(1 row)
+
+-- ADVANCED OPERATIONS TESTS
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+      test       | result 
+-----------------+--------
+ add_range basic | t
+(1 row)
+
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+           test           | result 
+--------------------------+--------
+ add_range single element | t
+(1 row)
+
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+         test          | result 
+-----------------------+--------
+ add_range to existing | t
+(1 row)
+
+SELECT 'add_range at word boundary 31' as test, bms_values(test_bms_add_range(NULL, 30, 34)) as result;
+             test              |       result       
+-------------------------------+--------------------
+ add_range at word boundary 31 | (b 30 31 32 33 34)
+(1 row)
+
+SELECT 'add_range at word boundary 63' as test, bms_values(test_bms_add_range(NULL, 62, 66)) as result;
+             test              |       result       
+-------------------------------+--------------------
+ add_range at word boundary 63 | (b 62 63 64 65 66)
+(1 row)
+
+SELECT 'add_range large range' as test, bms_values(test_bms_add_range(NULL, 0, 1000)) as result;
+         test          |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           result                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ add_range large range | (b 0 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000)
+(1 row)
+
+SELECT 'add_range force realloc test 1' as test, bms_values(test_bms_add_range(NULL, 0, 200)) as result;
+              test              |                                                                                                                                                                                                                                                                                                                                                          result                                                                                                                                                                                                                                                                                                                                                           
+--------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ add_range force realloc test 1 | (b 0 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)
+(1 row)
+
+SELECT 'add_range foce realloc test 2' as test, bms_values(test_bms_add_range(NULL, 1000, 1100)) as result;
+             test              |                                                                                                                                                                                                                                                            result                                                                                                                                                                                                                                                            
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ add_range foce realloc test 2 | (b 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100)
+(1 row)
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+       test       | result 
+------------------+--------
+ membership empty | t
+(1 row)
+
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+         test         | result 
+----------------------+--------
+ membership singleton | t
+(1 row)
+
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+        test         | result 
+---------------------+--------
+ membership multiple | t
+(1 row)
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+          test          | result 
+------------------------+--------
+ singleton_member valid | t
+(1 row)
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+            test            | result 
+----------------------------+--------
+ next_member first          | t
+ next_member second         | t
+ next_member past end       | t
+ next_member empty set      | t
+ prev_member last           | t
+ prev_member penultimate    | t
+ prev_member past beginning | t
+ prev_member empty set      | t
+(8 rows)
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_135a) = test_bms_hash_value(set_135b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_135a) != test_bms_hash_value(set_246) as result FROM test_sets;
+        test         | result 
+---------------------+--------
+ hash NULL           | t
+ hash consistency    | t
+ hash different sets | t
+(3 rows)
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+       test        | result 
+-------------------+--------
+ overlap existing  | t
+ overlap none      | t
+ overlap with NULL | t
+(3 rows)
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24,
+	test_bms_add_range(NULL, 0, 31) AS rng_0_31, -- 1 word
+	test_bms_add_range(NULL, 0, 63) as rng_0_63  -- 2 words
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset comparison edge' as test, test_bms_is_subset(rng_0_31, rng_0_63) = true as result FROM test_sets;
+             test             | result 
+------------------------------+--------
+ subset NULL is subset of all | t
+ subset proper subset         | t
+ subset improper subset       | t
+ subset disjoint sets         | t
+ subset comparison edge       | t
+(5 rows)
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+     test      | result 
+---------------+--------
+ copy NULL     | t
+ copy equality | t
+(2 rows)
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+         test          | result 
+-----------------------+--------
+ add_members operation | t
+(1 row)
+
+SELECT 'add members complex' as test,
+       bms_values(test_bms_add_members(
+           test_bms_from_array(ARRAY[1,3,5]),
+           test_bms_from_array(ARRAY[100,200,300])
+       )) as result;
+        test         |        result         
+---------------------+-----------------------
+ add members complex | (b 1 3 5 100 200 300)
+(1 row)
+
+-- Test 20: Test hash consistency
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+             test              | result 
+-------------------------------+--------
+ bitmap_hash NULL              | t
+ bitmap_hash consistency       | t
+ bitmap_hash vs bms_hash_value | t
+ bitmap_hash different sets    | t
+(4 rows)
+
+-- Test 21: bitmap_match function
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match NULL NULL (should be 0)       | t
+ bitmap_match NULL set (should be 1)        | t
+ bitmap_match set NULL (should be 1)        | t
+ bitmap_match identical sets (should be 0)  | t
+ bitmap_match different sets (should be 1)  | t
+ bitmap_match subset/superset (should be 1) | t
+(6 rows)
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match vs bms_equal (equal sets)     | t
+ bitmap_match vs bms_equal (different sets) | t
+ bitmap_match vs bms_equal (NULL cases)     | t
+(3 rows)
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [1,3,5] |           0
+(1 row)
+
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+              test               | match_value 
+---------------------------------+-------------
+ bitmap_match [1,3,5] vs [2,4,6] |           1
+(1 row)
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+           test            | result 
+---------------------------+--------
+ bitmap_match empty arrays | t
+(1 row)
+
+-- Test 22: Overlap lists with various scenarios
+WITH test_lists AS (
+    SELECT ARRAY[
+        test_bms_from_array(ARRAY[1,2,3]),
+        test_bms_from_array(ARRAY[4,5,6]),
+        test_bms_from_array(ARRAY[7,8,9]),
+        test_bms_make_singleton(2)  -- This should overlap with first set
+    ] as bms_list
+)
+SELECT 'overlap list complex' as test,
+       test_bms_overlap_list(test_bms_from_array(ARRAY[2,10]), bms_list) as result
+FROM test_lists;
+         test         | result 
+----------------------+--------
+ overlap list complex | f
+(1 row)
+
+SELECT 'overlap empty list' as test,
+       test_bms_overlap_list(test_bms_make_singleton(1), ARRAY[]::text[]) as result;
+        test        | result 
+--------------------+--------
+ overlap empty list | f
+(1 row)
+
+-- Test 23: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(-1, 10000, 81920, 0) > 0 as result;
+       test        | result 
+-------------------+--------
+ random operations | t
+(1 row)
+
+-- ERROR CONDITION TESTS
+-- Test 24: Error conditions (these should produce ERRORs)
+SELECT test_bms_make_singleton(-1);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_member(test_bms_make_singleton(1), -1);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_is_member(NULL, -5);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_member(NULL, -10);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_del_member(NULL, -20);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_range(NULL, -5, 10);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+ERROR:  bitmapset has multiple members
+SELECT bms_values(test_bms_add_member(NULL, 1000));
+ bms_values 
+------------
+ (b 1000)
+(1 row)
+
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..2ec5fda9fb1
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,413 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+
+-- BASIC FUNCTIONALITY TESTS
+
+-- Test bms_values function
+
+SELECT 'values NULL' as test, bms_values(NULL) as result;
+SELECT 'values empty' as test, bms_values(test_bms_from_array(ARRAY[]::integer[])) as result;
+SELECT 'values singleton' as test, bms_values(test_bms_make_singleton(42)) as result;
+SELECT 'values small set' as test, bms_values(test_bms_from_array(ARRAY[1,3,5])) as result;
+SELECT 'values larger set' as test, bms_values(test_bms_from_array(ARRAY[0,5,10,15,20])) as result;
+SELECT 'values unsorted input' as test, bms_values(test_bms_from_array(ARRAY[20,5,15,0,10])) as result;
+
+-- Test 1: Basic utility functions
+SELECT 'NULL input to from_array' as test, test_bms_from_array(NULL) IS NULL as result;
+SELECT 'Empty array to from_array' as test, test_bms_from_array(ARRAY[]::integer[]) IS NULL as result;
+SELECT 'NULL input to to_array' as test, test_bms_to_array(NULL) IS NULL as result;
+
+-- Test 2: Singleton operations
+SELECT 'make_singleton(42)' as test, test_bms_to_array(test_bms_make_singleton(42)) = ARRAY[42] as result;
+SELECT 'make_singleton(0)' as test, test_bms_to_array(test_bms_make_singleton(0)) = ARRAY[0] as result;
+SELECT 'make_singleton(1000)' as test, test_bms_to_array(test_bms_make_singleton(1000)) = ARRAY[1000] as result;
+
+-- Test 3: Add member operations
+SELECT 'add_member(NULL, 10)' as test, test_bms_to_array(test_bms_add_member(NULL, 10)) = ARRAY[10] as result;
+SELECT 'add_member consistency' as test, bms_values(test_bms_add_member(NULL, 10)) as values;
+SELECT 'add_member to existing' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(5), 10)) = ARRAY[5,10] as result;
+SELECT 'add_member sorted' as test, test_bms_to_array(test_bms_add_member(test_bms_make_singleton(10), 5)) = ARRAY[5,10] as result;
+SELECT 'add_member idempotent' as test, bms_values(test_bms_add_member(test_bms_make_singleton(10), 10)) as values;
+
+
+-- Test 4: Delete member operations
+SELECT 'del_member from NULL' as test, test_bms_del_member(NULL, 10) IS NULL as result;
+SELECT 'del_member singleton becomes empty' as test, test_bms_del_member(test_bms_make_singleton(10), 10) IS NULL as result;
+SELECT 'del_member no change' as test, bms_values(test_bms_del_member(test_bms_make_singleton(10), 5)) as values;
+SELECT 'del_member from middle' as test, test_bms_to_array(test_bms_del_member(test_bms_from_array(ARRAY[1,2,3]), 2)) = ARRAY[1,3] as result;
+SELECT 'del_member triggers realloc' as test, test_bms_del_member(test_bms_del_member(test_bms_from_array(ARRAY[0,31,32,63,64]), 32), 63) as result;
+SELECT 'del_member word boundary' as test,
+       bms_values(test_bms_del_member(
+           test_bms_add_range(NULL, 30, 34),
+           32
+       )) as result;
+
+-- SET OPERATIONS TESTS
+
+-- Test 5: Union operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'union overlapping sets' as test,
+       test_bms_to_array(test_bms_union(set_135, set_357)) = ARRAY[1,3,5,7] as result
+FROM test_sets
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_to_array(test_bms_union(set_135, NULL)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union(NULL, NULL) IS NULL as result
+FROM test_sets;
+SELECT 'overlapping ranges' as test,
+       bms_values(test_bms_union(
+           test_bms_add_range(NULL, 50, 150),
+           test_bms_add_range(NULL, 100, 200)
+       )) as result;
+
+-- Test 6: Intersection operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'intersect overlapping sets' as test,
+       test_bms_to_array(test_bms_intersect(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect(set_135, NULL) IS NULL as result
+FROM test_sets;
+
+-- Test bms_int_members
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'int(ersect) overlapping sets' as test,
+       test_bms_to_array(test_bms_int_members(set_135, set_357)) = ARRAY[3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'int(ersect) disjoint sets' as test,
+       test_bms_int_members(set_135, set_246) IS NULL as result
+FROM test_sets
+UNION ALL
+SELECT 'int(ersect) with NULL' as test,
+       test_bms_int_members(set_135, NULL) IS NULL as result
+FROM test_sets;
+SELECT 'int(ersect) members' as test,
+       bms_values(test_bms_int_members(
+           test_bms_from_array(ARRAY[0,31,32,63,64]),
+           test_bms_from_array(ARRAY[31,32,64,65])
+       )) as result;
+
+-- Test 7: Difference operations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'difference overlapping sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_357)) = ARRAY[1] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_to_array(test_bms_difference(set_135, set_246)) = ARRAY[1,3,5] as result
+FROM test_sets
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference(set_135, set_135) IS NULL as result
+FROM test_sets;
+SELECT 'difference subtraction edge case' as test,
+       bms_values(test_bms_difference(
+           test_bms_add_range(NULL, 0, 100),
+           test_bms_add_range(NULL, 50, 150)
+       )) as result;
+SELECT 'difference subtract to empty' as test,
+       bms_values(test_bms_difference(
+           test_bms_make_singleton(42),
+           test_bms_make_singleton(42)
+       )) as result;
+
+-- MEMBERSHIP AND COMPARISON TESTS
+
+-- Test 8: Membership tests
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5]) AS set_135)
+SELECT 'is_member existing' as test, test_bms_is_member(set_135, 1) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member(set_135, 2) = false as result FROM test_set
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member(set_135, 3) = true as result FROM test_set
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member(NULL, 1) = false as result FROM test_set;
+
+-- Test 9: Set cardinality
+SELECT 'num_members NULL' as test, test_bms_num_members(NULL) = 0 as result;
+SELECT 'num_members small set' as test, test_bms_num_members(test_bms_from_array(ARRAY[1,3,5])) = 3 as result;
+SELECT 'num_members larger set' as test, test_bms_num_members(test_bms_from_array(ARRAY[2,4,6,8,10])) = 5 as result;
+
+-- Test 10: Set equality and comparison
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'equal NULL NULL' as test, test_bms_equal(NULL, NULL) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal(NULL, set_135_a) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal(set_135_a, NULL) = false as result FROM test_sets
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal(set_135_a, set_135_b) = true as result FROM test_sets
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal(set_135_a, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare(NULL, NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare(NULL, set_13) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare(set_13, NULL) = 1 as result FROM test_sets
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare(set_13, set_13) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare(set_13, set_135_a) = -1 as result FROM test_sets
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare(set_135_a, set_13) = 1 as result FROM test_sets;
+SELECT 'compare edge case' as test,
+       test_bms_compare(
+           test_bms_add_range(NULL, 0, 63),
+           test_bms_add_range(NULL, 0, 64)
+       ) as result;
+
+-- ADVANCED OPERATIONS TESTS
+
+-- Test 11: Range operations
+SELECT 'add_range basic' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 7)) = ARRAY[5,6,7] as result;
+SELECT 'add_range single element' as test, test_bms_to_array(test_bms_add_range(NULL, 5, 5)) = ARRAY[5] as result;
+SELECT 'add_range to existing' as test, test_bms_to_array(test_bms_add_range(test_bms_from_array(ARRAY[1,10]), 5, 7)) = ARRAY[1,5,6,7,10] as result;
+SELECT 'add_range at word boundary 31' as test, bms_values(test_bms_add_range(NULL, 30, 34)) as result;
+SELECT 'add_range at word boundary 63' as test, bms_values(test_bms_add_range(NULL, 62, 66)) as result;
+SELECT 'add_range large range' as test, bms_values(test_bms_add_range(NULL, 0, 1000)) as result;
+SELECT 'add_range force realloc test 1' as test, bms_values(test_bms_add_range(NULL, 0, 200)) as result;
+SELECT 'add_range foce realloc test 2' as test, bms_values(test_bms_add_range(NULL, 1000, 1100)) as result;
+
+-- Test 12: Membership types
+SELECT 'membership empty' as test, test_bms_membership(NULL) = 0 as result;
+SELECT 'membership singleton' as test, test_bms_membership(test_bms_from_array(ARRAY[42])) = 1 as result;
+SELECT 'membership multiple' as test, test_bms_membership(test_bms_from_array(ARRAY[1,2,3])) = 2 as result;
+
+-- Test 13: Singleton member extraction
+SELECT 'singleton_member valid' as test, test_bms_singleton_member(test_bms_from_array(ARRAY[42])) = 42 as result;
+
+-- Test 14: Set iteration
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[5,10,15,20]) AS set_numbers)
+SELECT 'next_member first' as test, test_bms_next_member(set_numbers, -1) = 5 as result FROM test_set
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member(set_numbers, 5) = 10 as result FROM test_set
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member(set_numbers, 20) = -2 as result FROM test_set
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member(NULL, -1) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member(set_numbers, 21) = 20 as result FROM test_set
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member(set_numbers, 20) = 15 as result FROM test_set
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member(set_numbers, 5) = -2 as result FROM test_set
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member(NULL, 100) = -2 as result FROM test_set;
+
+-- Test 15: Hash functions
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'hash NULL' as test, test_bms_hash_value(NULL) = 0 as result FROM test_sets
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value(set_135a) = test_bms_hash_value(set_135b) as result FROM test_sets
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value(set_135a) != test_bms_hash_value(set_246) as result FROM test_sets;
+
+-- Test 16: Set overlap
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[3,5,7]) AS set_357,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'overlap existing' as test, test_bms_overlap(set_135, set_357) = true as result FROM test_sets
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap(set_135, set_246) = false as result FROM test_sets
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap(NULL, set_135) = false as result FROM test_sets;
+
+-- Test 17: Subset relations
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135,
+	test_bms_from_array(ARRAY[2,4]) AS set_24,
+	test_bms_add_range(NULL, 0, 31) AS rng_0_31, -- 1 word
+	test_bms_add_range(NULL, 0, 63) as rng_0_63  -- 2 words
+)
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset(NULL, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset(set_13, set_135) = true as result FROM test_sets
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset(set_135, set_13) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset(set_13, set_24) = false as result FROM test_sets
+UNION ALL
+SELECT 'subset comparison edge' as test, test_bms_is_subset(rng_0_31, rng_0_63) = true as result FROM test_sets;
+
+-- Test 18: Copy operations
+WITH test_set AS (SELECT test_bms_from_array(ARRAY[1,3,5,7]) AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result FROM test_set
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+
+-- Test 19: Add members operation
+WITH base_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3]) AS set_13,
+	test_bms_from_array(ARRAY[5,7]) AS set_57
+)
+SELECT 'add_members operation' as test,
+       test_bms_to_array(test_bms_add_members(set_13, set_57)) = ARRAY[1,3,5,7] as result
+FROM base_sets;
+SELECT 'add members complex' as test,
+       bms_values(test_bms_add_members(
+           test_bms_from_array(ARRAY[1,3,5]),
+           test_bms_from_array(ARRAY[100,200,300])
+       )) as result;
+
+-- Test 20: Test hash consistency
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash(NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash(set_135_a) = test_bitmap_hash(set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash(set_135_a) = test_bms_hash_value(set_135_a) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash(set_135_a) != test_bitmap_hash(set_246) as result
+FROM test_sets;
+
+-- Test 21: bitmap_match function
+
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246,
+	test_bms_from_array(ARRAY[1,3]) AS set_13
+)
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match(NULL, NULL) = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match(NULL, set_135_a) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match(set_135_a, NULL) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match(set_135_a, set_135_b) = 0 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match(set_135_a, set_246) = 1 as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match(set_13, set_135_a) = 1 as result
+FROM test_sets;
+
+-- Test relationship with bms_equal
+WITH test_sets AS (
+    SELECT
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_a,
+	test_bms_from_array(ARRAY[1,3,5]) AS set_135_b,
+	test_bms_from_array(ARRAY[2,4,6]) AS set_246
+)
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match(set_135_a, set_135_b) = 0) = test_bms_equal(set_135_a, set_135_b) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match(set_135_a, set_246) = 0) = test_bms_equal(set_135_a, set_246) as result
+FROM test_sets
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match(NULL, NULL) = 0) = test_bms_equal(NULL, NULL) as result
+FROM test_sets;
+
+-- Test specific match values for debugging
+SELECT 'bitmap_match [1,3,5] vs [1,3,5]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[1,3,5])) as match_value;
+SELECT 'bitmap_match [1,3,5] vs [2,4,6]' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[1,3,5]), test_bms_from_array(ARRAY[2,4,6])) as match_value;
+
+-- Test edge cases
+SELECT 'bitmap_match empty arrays' as test,
+       test_bitmap_match(test_bms_from_array(ARRAY[]::integer[]), test_bms_from_array(ARRAY[]::integer[])) = 0 as result;
+
+-- Test 22: Overlap lists with various scenarios
+WITH test_lists AS (
+    SELECT ARRAY[
+        test_bms_from_array(ARRAY[1,2,3]),
+        test_bms_from_array(ARRAY[4,5,6]),
+        test_bms_from_array(ARRAY[7,8,9]),
+        test_bms_make_singleton(2)  -- This should overlap with first set
+    ] as bms_list
+)
+SELECT 'overlap list complex' as test,
+       test_bms_overlap_list(test_bms_from_array(ARRAY[2,10]), bms_list) as result
+FROM test_lists;
+
+SELECT 'overlap empty list' as test,
+       test_bms_overlap_list(test_bms_make_singleton(1), ARRAY[]::text[]) as result;
+
+-- Test 23: Random operations stress test
+SELECT 'random operations' as test, test_random_operations(-1, 10000, 81920, 0) > 0 as result;
+
+-- ERROR CONDITION TESTS
+
+-- Test 24: Error conditions (these should produce ERRORs)
+SELECT test_bms_make_singleton(-1);
+SELECT test_bms_add_member(test_bms_make_singleton(1), -1);
+SELECT test_bms_is_member(NULL, -5);
+SELECT test_bms_add_member(NULL, -10);
+SELECT test_bms_del_member(NULL, -20);
+SELECT test_bms_add_range(NULL, -5, 10);
+SELECT test_bms_singleton_member(test_bms_from_array(ARRAY[1,2]));
+SELECT bms_values(test_bms_add_member(NULL, 1000));
+
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..89ac65c789b
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,149 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+-- Utility functions
+CREATE FUNCTION test_bms_from_array(integer[])
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_to_array(text)
+RETURNS integer[]
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION bms_values(text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C STABLE;
+
+-- Bitmapset API functions
+CREATE FUNCTION test_bms_make_singleton(integer)
+RETURNS text STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_member(text, integer)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_del_member(text, integer)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_member(text, integer)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_num_members(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_copy(text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_equal(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_compare(text, text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_subset(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_subset_compare(text, text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_union(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_intersect(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_difference(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_empty(text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_membership(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_singleton_member(text)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_get_singleton_member(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_next_member(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_prev_member(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_hash_value(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap_list(text, text[])
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_nonempty_difference(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_member_index(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_range(text, integer, integer)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_members(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_int_members(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_replace_members(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_join(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_hash(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_match(text, text)
+RETURNS int
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+-- Test utility functions
+CREATE FUNCTION test_random_operations(integer, integer, integer, integer)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+COMMENT ON EXTENSION test_bitmapset IS 'Test code for Bitmapset';
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..0d5a0806695
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,1179 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include <stddef.h>
+#include "catalog/pg_type.h"
+#include "common/pg_prng.h"
+#include "utils/array.h"
+#include "fmgr.h"
+#include "nodes/bitmapset.h"
+#include "nodes/nodes.h"
+#include "nodes/pg_list.h"
+#include "utils/builtins.h"
+#include "utils/timestamp.h"
+#include "varatt.h"
+
+PG_MODULE_MAGIC;
+
+/* Utility functions */
+PG_FUNCTION_INFO_V1(bms_values);
+PG_FUNCTION_INFO_V1(test_bms_from_array);
+PG_FUNCTION_INFO_V1(test_bms_to_array);
+
+/* Bitmapset API functions in order of appearance in bitmapset.c */
+PG_FUNCTION_INFO_V1(test_bms_make_singleton);
+PG_FUNCTION_INFO_V1(test_bms_add_member);
+PG_FUNCTION_INFO_V1(test_bms_del_member);
+PG_FUNCTION_INFO_V1(test_bms_is_member);
+PG_FUNCTION_INFO_V1(test_bms_num_members);
+PG_FUNCTION_INFO_V1(test_bms_copy);
+PG_FUNCTION_INFO_V1(test_bms_equal);
+PG_FUNCTION_INFO_V1(test_bms_compare);
+PG_FUNCTION_INFO_V1(test_bms_is_subset);
+PG_FUNCTION_INFO_V1(test_bms_subset_compare);
+PG_FUNCTION_INFO_V1(test_bms_union);
+PG_FUNCTION_INFO_V1(test_bms_intersect);
+PG_FUNCTION_INFO_V1(test_bms_difference);
+PG_FUNCTION_INFO_V1(test_bms_is_empty);
+PG_FUNCTION_INFO_V1(test_bms_membership);
+PG_FUNCTION_INFO_V1(test_bms_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_get_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_next_member);
+PG_FUNCTION_INFO_V1(test_bms_prev_member);
+PG_FUNCTION_INFO_V1(test_bms_hash_value);
+PG_FUNCTION_INFO_V1(test_bms_overlap);
+PG_FUNCTION_INFO_V1(test_bms_overlap_list);
+PG_FUNCTION_INFO_V1(test_bms_nonempty_difference);
+PG_FUNCTION_INFO_V1(test_bms_member_index);
+PG_FUNCTION_INFO_V1(test_bms_add_range);
+PG_FUNCTION_INFO_V1(test_bms_add_members);
+PG_FUNCTION_INFO_V1(test_bms_int_members);
+PG_FUNCTION_INFO_V1(test_bms_replace_members);
+PG_FUNCTION_INFO_V1(test_bms_join);
+PG_FUNCTION_INFO_V1(test_bitmap_hash);
+PG_FUNCTION_INFO_V1(test_bitmap_match);
+
+/* Test utility functions */
+PG_FUNCTION_INFO_V1(test_random_operations);
+
+/* Convenient macros to test results */
+#define EXPECT_TRUE(expr)	\
+	do { \
+		if (!(expr)) \
+			elog(ERROR, \
+				 "%s was unexpectedly false in file \"%s\" line %u", \
+				 #expr, __FILE__, __LINE__); \
+	} while (0)
+
+#define EXPECT_NOT_NULL(expr)	\
+	do { \
+		if ((expr) == NULL) \
+			elog(ERROR, \
+				 "%s was unexpectedly true in file \"%s\" line %u", \
+				 #expr, __FILE__, __LINE__); \
+	} while (0)
+
+
+/*
+ * Utility functions to convert between Bitmapset and text
+ * for passing data between SQL and C functions
+ */
+
+static text *
+encode_bms_to_text(Bitmapset *bms)
+{
+	char	   *str;
+	text	   *result;
+
+	if (bms == NULL)
+		return NULL;
+
+	str = nodeToString(bms);
+	result = cstring_to_text(str);
+	pfree(str);
+
+	return result;
+}
+
+static Bitmapset *
+decode_text_to_bms(text *data)
+{
+	char	   *str;
+	Bitmapset  *bms;
+
+	if (data == NULL)
+		return NULL;
+
+	str = text_to_cstring(data);
+	bms = (Bitmapset *) stringToNode(str);
+	pfree(str);
+
+	return bms;
+}
+
+Datum
+bms_values(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms;
+	char	   *str;
+	text	   *result;
+
+	if (PG_ARGISNULL(0))
+	{
+		result = cstring_to_text("(b)");
+		PG_RETURN_TEXT_P(result);
+	}
+
+	bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+	str = bmsToString(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	result = cstring_to_text(str);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+/*
+ * Individual test functions for each bitmapset API function
+ */
+
+Datum
+test_bms_add_member(PG_FUNCTION_ARGS)
+{
+	int			member;
+	Bitmapset  *bms = NULL;
+	text	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	bms = bms_add_member(bms, member);
+	result = encode_bms_to_text(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	if (result == NULL)
+		PG_RETURN_NULL();
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_add_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	/* IMPORTANT: bms_add_members modifies/frees the first argument */
+	bms1 = bms_add_members(bms1, bms2);
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (bms1 == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_text(bms1);
+	bms_free(bms1);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_del_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	text	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	bms = bms_del_member(bms, member);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	result = encode_bms_to_text(bms);
+	bms_free(bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_is_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bool		result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_BOOL(false);
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	result = bms_is_member(member, bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_num_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result = 0;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	result = bms_num_members(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_make_singleton(PG_FUNCTION_ARGS)
+{
+	int32		member;
+	Bitmapset  *bms;
+	text	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	member = PG_GETARG_INT32(0);
+	bms = bms_make_singleton(member);
+
+	result = encode_bms_to_text(bms);
+	bms_free(bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_copy(PG_FUNCTION_ARGS)
+{
+	text	   *bms_data;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *copy_bms;
+	text	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_TEXT_PP(0);
+	bms = decode_text_to_bms(bms_data);
+	copy_bms = bms_copy(bms);
+	result = encode_bms_to_text(copy_bms);
+
+	if (bms)
+		bms_free(bms);
+	if (copy_bms)
+		bms_free(copy_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_equal(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result = bms_equal(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_union(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result_bms = bms_union(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_text(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_membership(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	BMS_Membership result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(BMS_EMPTY_SET);
+
+	bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+	result = bms_membership(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_next_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
+		PG_RETURN_INT32(-2);
+
+	bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+	prevmember = PG_GETARG_INT32(1);
+	result = bms_next_member(bms, prevmember);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_from_array(PG_FUNCTION_ARGS)
+{
+	ArrayType  *array;
+	int		   *members;
+	int			nmembers;
+	Bitmapset  *bms = NULL;
+	text	   *result;
+	int			i;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	array = PG_GETARG_ARRAYTYPE_P(0);
+
+	/* Check element type first */
+	if (ARR_ELEMTYPE(array) != INT4OID)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	/* Handle empty arrays - ARR_NDIM can be 0 for empty arrays */
+	if (ARR_NDIM(array) == 0)
+		PG_RETURN_NULL();
+
+	/* Now check dimensions */
+	if (ARR_NDIM(array) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	nmembers = ARR_DIMS(array)[0];
+
+	/* Double-check for empty */
+	if (nmembers == 0)
+		PG_RETURN_NULL();
+
+	if (ARR_HASNULL(array))
+		ereport(ERROR,
+				(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+				 errmsg("integer array expected")));
+
+	members = (int *) ARR_DATA_PTR(array);
+
+	for (i = 0; i < nmembers; i++)
+		bms = bms_add_member(bms, members[i]);
+
+	result = encode_bms_to_text(bms);
+	bms_free(bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_to_array(PG_FUNCTION_ARGS)
+{
+	text	   *bms_data;
+	Bitmapset  *bms = NULL;
+	ArrayType  *result;
+	Datum	   *datums;
+	int			nmembers;
+	int			member = -1;
+	int			i = 0;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_TEXT_PP(0);
+	bms = decode_text_to_bms(bms_data);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	nmembers = bms_num_members(bms);
+	datums = (Datum *) palloc(nmembers * sizeof(Datum));
+
+	while ((member = bms_next_member(bms, member)) >= 0)
+		datums[i++] = Int32GetDatum(member);
+
+	bms_free(bms);
+
+	result = construct_array(datums, nmembers,
+							 INT4OID, sizeof(int32), true, 'i');
+
+	pfree(datums);
+	PG_RETURN_ARRAYTYPE_P(result);
+}
+
+Datum
+test_bms_intersect(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result_bms = bms_intersect(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_text(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result_bms = bms_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_text(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result = bms_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_is_empty(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	result = bms_is_empty(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_is_subset(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result = bms_is_subset(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_subset_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	BMS_Comparison result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result = bms_subset_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	result = bms_singleton_member(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_get_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		default_member = PG_GETARG_INT32(1);
+	int			member;
+	bool		success;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(default_member);
+
+	bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	/*
+	 * bms_get_singleton_member returns bool and stores result in member
+	 * pointer
+	 */
+	success = bms_get_singleton_member(bms, &member);
+	bms_free(bms);
+
+	if (success)
+		PG_RETURN_INT32(member);
+	else
+		PG_RETURN_INT32(default_member);
+}
+
+Datum
+test_bms_prev_member(PG_FUNCTION_ARGS)
+{
+	text	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-2);
+
+	bms_data = PG_GETARG_TEXT_PP(0);
+	prevmember = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-2);
+
+	bms = decode_text_to_bms(bms_data);
+	result = bms_prev_member(bms, prevmember);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_overlap(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result = bms_overlap(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_overlap_list(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	ArrayType  *array;
+	List	   *bitmapset_list = NIL;
+	ListCell   *lc;
+	bool		result;
+	Datum	   *elem_datums;
+	bool	   *elem_nulls;
+	int			elem_count;
+	int			i;
+
+	/* Handle first argument (the bitmapset) */
+	if (PG_ARGISNULL(0))
+		PG_RETURN_BOOL(false);
+
+	bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	/* Handle second argument (array of bitmapsets) */
+	if (PG_ARGISNULL(1))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_BOOL(false);
+	}
+
+	array = PG_GETARG_ARRAYTYPE_P(1);
+
+	if (ARR_ELEMTYPE(array) != TEXTOID)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATATYPE_MISMATCH),
+				 errmsg("text array expected")));
+
+	deconstruct_array(array,
+					  TEXTOID, -1, false, 'i',
+					  &elem_datums, &elem_nulls, &elem_count);
+
+	/* Convert each text element to a Bitmapset and add to list */
+	for (i = 0; i < elem_count; i++)
+	{
+		Bitmapset  *list_bms = NULL;
+
+		if (!elem_nulls[i])
+		{
+			text	   *elem = DatumGetTextP(elem_datums[i]);
+
+			list_bms = decode_text_to_bms(elem);
+		}
+
+		/* Add to list (even if NULL) */
+		bitmapset_list = lappend(bitmapset_list, list_bms);
+	}
+
+	/* Call the actual bms_overlap_list function */
+	result = bms_overlap_list(bms, bitmapset_list);
+
+	/* Clean up */
+	if (bms)
+		bms_free(bms);
+
+	/* Free all bitmapsets in the list */
+	foreach(lc, bitmapset_list)
+	{
+		Bitmapset  *list_bms = (Bitmapset *) lfirst(lc);
+
+		if (list_bms)
+			bms_free(list_bms);
+	}
+	list_free(bitmapset_list);
+
+	/* Free array deconstruction results */
+	pfree(elem_datums);
+	pfree(elem_nulls);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_nonempty_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	result = bms_nonempty_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_member_index(PG_FUNCTION_ARGS)
+{
+	text	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		member;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-1);
+
+	bms_data = PG_GETARG_TEXT_PP(0);
+	member = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-1);
+
+	bms = decode_text_to_bms(bms_data);
+
+	result = bms_member_index(bms, member);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_add_range(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		lower,
+				upper;
+	text	   *result;
+
+	if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	lower = PG_GETARG_INT32(1);
+	upper = PG_GETARG_INT32(2);
+
+	/* Check for invalid range */
+	if (upper < lower)
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	bms = bms_add_range(bms, lower, upper);
+
+	result = encode_bms_to_text(bms);
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_int_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	bms1 = bms_int_members(bms1, bms2);
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (bms1 == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_text(bms1);
+
+	if (bms1)
+		bms_free(bms1);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_replace_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	/* IMPORTANT: bms_replace_members modifies/frees the first argument */
+	result_bms = bms_replace_members(bms1, bms2);
+	/* bms1 is now invalid, don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_text(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_join(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	/* IMPORTANT: bms_join modifies/frees the first argument */
+	result_bms = bms_join(bms1, bms2);
+	/* bms1 is now invalid! Don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = encode_bms_to_text(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_hash_value(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	hash_result = bms_hash_value(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_hash(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	Bitmapset  *bms_ptr;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	bms_ptr = bms;
+
+	/* Call bitmap_hash */
+	hash_result = bitmap_hash(&bms_ptr, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (!PG_ARGISNULL(0) && bms_ptr)
+		bms_free(bms_ptr);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_match(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *bms_ptr1,
+			   *bms_ptr2;
+	int			match_result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = decode_text_to_bms(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = decode_text_to_bms(PG_GETARG_TEXT_PP(1));
+
+	/* Set up pointers to the Bitmapsets */
+	bms_ptr1 = bms1;
+	bms_ptr2 = bms2;
+
+	/* Call bitmap_match with addresses of the Bitmapset pointers */
+	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(match_result);
+}
+
+Datum
+test_random_operations(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *result = NULL;
+	pg_prng_state state;
+	uint64		seed = GetCurrentTimestamp();
+	int			num_ops = 5000;
+	int			total_ops = 0;
+	int			max_range = 2000;
+	int			min_value = 0;
+	int			member;
+	int		   *members;
+	int			num_members = 0;
+
+	if (!PG_ARGISNULL(0) && PG_GETARG_INT32(0) > 0)
+		seed = PG_GETARG_INT32(0);
+
+	if (!PG_ARGISNULL(1))
+		num_ops = PG_GETARG_INT32(1);
+
+	if (!PG_ARGISNULL(2))
+		max_range = PG_GETARG_INT32(2);
+
+	if (!PG_ARGISNULL(3))
+		min_value = PG_GETARG_INT32(3);
+
+	pg_prng_seed(&state, seed);
+	members = palloc(sizeof(int) * num_ops);
+
+	/* Phase 1: Random insertions */
+	for (int i = 0; i < num_ops / 2; i++)
+	{
+		member = pg_prng_uint32(&state) % max_range + min_value;
+
+		if (!bms_is_member(member, bms1))
+		{
+			members[num_members++] = member;
+			bms1 = bms_add_member(bms1, member);
+		}
+	}
+
+	/* Phase 2: Random set operations */
+	for (int i = 0; i < num_ops / 4; i++)
+	{
+		member = pg_prng_uint32(&state) % max_range + min_value;
+
+		bms2 = bms_add_member(bms2, member);
+	}
+
+	/* Test union */
+	result = bms_union(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+
+	/* Verify union contains all members from first set */
+	for (int i = 0; i < num_members; i++)
+	{
+		if (!bms_is_member(members[i], result))
+			elog(ERROR, "union missing member %d", members[i]);
+	}
+	bms_free(result);
+
+	/* Test intersection */
+	result = bms_intersect(bms1, bms2);
+	if (result != NULL)
+	{
+		member = -1;
+
+		while ((member = bms_next_member(result, member)) >= 0)
+		{
+			if (!bms_is_member(member, bms1) || !bms_is_member(member, bms2))
+				elog(ERROR, "intersection contains invalid member %d", member);
+		}
+		bms_free(result);
+	}
+
+	/* Phase 3: Test range operations */
+	result = NULL;
+	for (int i = 0; i < 10; i++)
+	{
+		int			lower = pg_prng_uint32(&state) % 100;
+		int			upper = lower + (pg_prng_uint32(&state) % 20);
+
+		result = bms_add_range(result, lower, upper);
+	}
+	if (result != NULL)
+	{
+		EXPECT_TRUE(bms_num_members(result) > 0);
+		bms_free(result);
+	}
+
+	pfree(members);
+	bms_free(bms1);
+	bms_free(bms2);
+
+	for (int i = 0; i < num_ops; i++)
+	{
+		member = pg_prng_uint32(&state) % max_range + min_value;
+		switch (pg_prng_uint32(&state) % 3)
+		{
+			case 0:				/* add */
+				bms = bms_add_member(bms, member);
+				break;
+			case 1:				/* delete */
+				if (bms != NULL)
+				{
+					bms = bms_del_member(bms, member);
+				}
+				break;
+			case 2:				/* test membership */
+				if (bms != NULL)
+				{
+					bms_is_member(member, bms);
+				}
+				break;
+		}
+		total_ops++;
+	}
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(total_ops);
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#27Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#26)
Re: [PATCH] Add tests for Bitmapset

On Thu, Sep 18, 2025 at 02:50:45PM -0400, Greg Burd wrote:

Thanks for all the feedback and time spent reviewing this patch. I
switched out the encode/decode functions to use the nodeToString() and
stringToNode() functions and change all the SQL testing function
signatures to TEXT from BYTEA. This exercises more code and that's good
for testing purposes. I took out the code that checks the hash values,
I can't think of a reason that should cause a future failure should that
change and output different values. I re-integrated the earlier random
testing function along with the newer code. I'm not sure this buys us
much if anything.

coverage: HEAD v7
lines......: 87.1 90.5 +3.4%
functions..: 100.0 100.0 +0.0%
branches...: 63.5 75.9 +12.4%

Nathan has given me his blessing, so as I could look at this patch and
put my hands on it. I have spotted one bug, and things that could be
done a bit better. Please see below.

As far as I am concerned there is a mistake with bms_overlap_list().
This API checks a Bitmapset with a list of integers, but you have
coded things so as it checks for a list of Bitmapset. I think that
test_bms_overlap_list() should take in input a int4 array, then the
code in charge of the conversion from the array to the list needs to
be tweaked a little bit. With the current code, we could get random
failures with negative members included in a Bitmapset, depending on
what's on the stack.

I am not really convinced about the value brought by bms_values() now
that the output is generated for all the SQL functions using the
"decode" and "encode" routines (which may be actually less confusing
if renamed as "bms_to_text" and "text_to_bms", but that's a personal
take), because this results in doing an extra round-trip between text
and Bitmapset. The tests don't rely much on NULL as input to
translate that as "(b)". bmsToString() is just a direct call to what
the decode and encode routines do.

Same remark about test_bms_from_array(), that mimicks nodeRead(), in
charge of doing a int4[] -> Bitmapset conversion. Wouldn't it be
simpler to just use "(b 1 2 3)" in input and let the decode/encode
routines do the job?

Let's replace the test descriptions in the queries that we know have
an individual result by comments. For example all the "Range
operations". These descriptions are useful in the UNION queries,
where we want to rely on a set of Bitmapsets for multiple operations,
to be able to know the description of the result. For individual
queries, this bloats the output.

The numbering in the tests are not that useful to have. If the test
suite is updated, that would mean more updates required if we add a
new block in the middle.

+SELECT 'overlapping ranges' as test,
+       bms_values(test_bms_union(
+           test_bms_add_range(NULL, 50, 150),
+           test_bms_add_range(NULL, 100, 200)

The output generated by this query leads to a bitmapset with 200
members. It would be simpler and more readable to reduce these
ranges, or is there a reason for these to be large? Same remark for
"difference subtraction edge case" with its 50 members.

+SELECT 'add_range large range' as test, bms_values(test_bms_add_range(NULL, 0, 1000)) as result;

This one also is funky with its output of 1000 elements. Any reason
this is justified in terms of coverage? If yes, we could use some
substr() calls to get the end and the beginning of the output
generated, perhaps to reduce the output of the whole, or the length,
or something like that relevant enough to validate the output. There
is a second test a bit down that uses a range of [1000,1100], as well.
--
Michael

#28Greg Burd
greg@burd.me
In reply to: Michael Paquier (#27)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 19 2025, at 2:36 am, Michael Paquier <michael@paquier.xyz> wrote:

On Thu, Sep 18, 2025 at 02:50:45PM -0400, Greg Burd wrote:

Thanks for all the feedback and time spent reviewing this patch. I
switched out the encode/decode functions to use the nodeToString() and
stringToNode() functions and change all the SQL testing function
signatures to TEXT from BYTEA. This exercises more code and that's good
for testing purposes. I took out the code that checks the hash values,
I can't think of a reason that should cause a future failure should that
change and output different values. I re-integrated the earlier random
testing function along with the newer code. I'm not sure this buys us
much if anything.

coverage: HEAD v7
lines......: 87.1 90.5 +3.4%
functions..: 100.0 100.0 +0.0%
branches...: 63.5 75.9 +12.4%

Nathan has given me his blessing, so as I could look at this patch and
put my hands on it. I have spotted one bug, and things that could be
done a bit better. Please see below.

Hey Michael,

Thank you for taking the initiative and reviewing the code.

As far as I am concerned there is a mistake with bms_overlap_list().
This API checks a Bitmapset with a list of integers, but you have
coded things so as it checks for a list of Bitmapset. I think that
test_bms_overlap_list() should take in input a int4 array, then the
code in charge of the conversion from the array to the list needs to
be tweaked a little bit. With the current code, we could get random
failures with negative members included in a Bitmapset, depending on
what's on the stack.

Apologies, you're right. I'm not sure how I went astray on that, but
it's fixed now.

I am not really convinced about the value brought by bms_values() now
that the output is generated for all the SQL functions using the
"decode" and "encode" routines (which may be actually less confusing
if renamed as "bms_to_text" and "text_to_bms", but that's a personal
take), because this results in doing an extra round-trip between text
and Bitmapset.

Agreed, renamed and removed. New macros are:

/* Encode/Decode to/from TEXT and Bitmapset */
#define BITMAPSET_TO_TEXT(bms) (text *) CStringGetTextDatum(nodeToString((bms)))
#define TEXT_TO_BITMAPSET(str) (Bitmapset *)
stringToNode(TextDatumGetCString((Datum) (str)))

The tests don't rely much on NULL as input to
translate that as "(b)". bmsToString() is just a direct call to what
the decode and encode routines do.

Yes, agreed.

Same remark about test_bms_from_array(), that mimicks nodeRead(), in
charge of doing a int4[] -> Bitmapset conversion. Wouldn't it be
simpler to just use "(b 1 2 3)" in input and let the decode/encode
routines do the job?

That makes a lot of sense now that things are all string to/from the
Bitmapset node representation. Done.

Let's replace the test descriptions in the queries that we know have
an individual result by comments. For example all the "Range
operations". These descriptions are useful in the UNION queries,
where we want to rely on a set of Bitmapsets for multiple operations,
to be able to know the description of the result. For individual
queries, this bloats the output.

Okay, done.

The numbering in the tests are not that useful to have. If the test
suite is updated, that would mean more updates required if we add a
new block in the middle.

Agreed, removed.

+SELECT 'overlapping ranges' as test,
+       bms_values(test_bms_union(
+           test_bms_add_range(NULL, 50, 150),
+           test_bms_add_range(NULL, 100, 200)

The output generated by this query leads to a bitmapset with 200
members. It would be simpler and more readable to reduce these
ranges, or is there a reason for these to be large? Same remark for
"difference subtraction edge case" with its 50 members.

Some of these were targeted at corner cases to increase coverage. I'll
review and consider ways to either a) eliminate them, or b) shorten the output.

+SELECT 'add_range large range' as test,
bms_values(test_bms_add_range(NULL, 0, 1000)) as result;

This one also is funky with its output of 1000 elements. Any reason
this is justified in terms of coverage? If yes, we could use some
substr() calls to get the end and the beginning of the output
generated, perhaps to reduce the output of the whole, or the length,
or something like that relevant enough to validate the output. There
is a second test a bit down that uses a range of [1000,1100], as well.

I used length() and recorded the expected output in the test. That
seems to a) reduce noise in the output and b) remain deterministic(-ish).

--
Michael

I think I've incorporated your feedback which did indeed make the patch
more readable/crisp and maintainable, thank you.

coverage: HEAD v7 v8
lines......: 87.1 90.5 92.2
functions..: 100.0 100.0 100.0
branches...: 63.5 75.9 76.2

best.

-greg

Attachments:

v8-0001-Add-a-module-that-tests-Bitmapset.patchapplication/octet-streamDownload
From ca4983e99f17e58553177fa419752182e657be4a Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 15:40:31 -0400
Subject: [PATCH v8] Add a module that tests Bitmapset

Basic tests for Bitmapset to ensure functionality and help prevent
unintentional breaking changes in the future.
---
 src/test/modules/Makefile                     |    1 +
 src/test/modules/meson.build                  |    1 +
 src/test/modules/test_bitmapset/.gitignore    |    4 +
 src/test/modules/test_bitmapset/Makefile      |   23 +
 .../expected/test_bitmapset.out               |  621 ++++++++++
 src/test/modules/test_bitmapset/meson.build   |   33 +
 .../test_bitmapset/sql/test_bitmapset.sql     |  312 +++++
 .../test_bitmapset/test_bitmapset--1.0.sql    |  136 +++
 .../modules/test_bitmapset/test_bitmapset.c   | 1008 +++++++++++++++++
 .../test_bitmapset/test_bitmapset.control     |    4 +
 10 files changed, 2143 insertions(+)
 create mode 100644 src/test/modules/test_bitmapset/.gitignore
 create mode 100644 src/test/modules/test_bitmapset/Makefile
 create mode 100644 src/test/modules/test_bitmapset/expected/test_bitmapset.out
 create mode 100644 src/test/modules/test_bitmapset/meson.build
 create mode 100644 src/test/modules/test_bitmapset/sql/test_bitmapset.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.c
 create mode 100644 src/test/modules/test_bitmapset/test_bitmapset.control

diff --git a/src/test/modules/Makefile b/src/test/modules/Makefile
index 903a8ac151a..94071ec0e16 100644
--- a/src/test/modules/Makefile
+++ b/src/test/modules/Makefile
@@ -16,6 +16,7 @@ SUBDIRS = \
 		  spgist_name_ops \
 		  test_aio \
 		  test_binaryheap \
+		  test_bitmapset \
 		  test_bloomfilter \
 		  test_copy_callbacks \
 		  test_custom_rmgrs \
diff --git a/src/test/modules/meson.build b/src/test/modules/meson.build
index 93be0f57289..d8f5c9c7494 100644
--- a/src/test/modules/meson.build
+++ b/src/test/modules/meson.build
@@ -15,6 +15,7 @@ subdir('spgist_name_ops')
 subdir('ssl_passphrase_callback')
 subdir('test_aio')
 subdir('test_binaryheap')
+subdir('test_bitmapset')
 subdir('test_bloomfilter')
 subdir('test_copy_callbacks')
 subdir('test_custom_rmgrs')
diff --git a/src/test/modules/test_bitmapset/.gitignore b/src/test/modules/test_bitmapset/.gitignore
new file mode 100644
index 00000000000..5dcb3ff9723
--- /dev/null
+++ b/src/test/modules/test_bitmapset/.gitignore
@@ -0,0 +1,4 @@
+# Generated subdirectories
+/log/
+/results/
+/tmp_check/
diff --git a/src/test/modules/test_bitmapset/Makefile b/src/test/modules/test_bitmapset/Makefile
new file mode 100644
index 00000000000..67199d40d73
--- /dev/null
+++ b/src/test/modules/test_bitmapset/Makefile
@@ -0,0 +1,23 @@
+# src/test/modules/test_bitmapset/Makefile
+
+MODULE_big = test_bitmapset
+OBJS = \
+	$(WIN32RES) \
+	test_bitmapset.o
+PGFILEDESC = "test_bitmapset - test code for src/include/nodes/bitmapset.h"
+
+EXTENSION = test_bitmapset
+DATA = test_bitmapset--1.0.sql
+
+REGRESS = test_bitmapset
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = src/test/modules/test_bitmapset
+top_builddir = ../../../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
new file mode 100644
index 00000000000..ab255087416
--- /dev/null
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -0,0 +1,621 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+-- make_singleton(42)
+SELECT test_bms_make_singleton(42) = '(b 42)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- make_singleton(0)
+SELECT test_bms_make_singleton(0) = '(b 0)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- make_singleton(1000)
+SELECT test_bms_make_singleton(1000) = '(b 1000)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_member(NULL, 10)
+SELECT test_bms_add_member('(b)', 10) = '(b 10)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_member consistency
+SELECT test_bms_add_member('(b)', 10) as result;
+ result 
+--------
+ (b 10)
+(1 row)
+
+-- add_member to existing
+SELECT test_bms_add_member('(b 5)', 10) = '(b 5 10)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_member sorted
+SELECT test_bms_add_member('(b 10)', 5) = '(b 5 10)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_member idempotent
+SELECT test_bms_add_member('(b 10)', 10) as result;
+ result 
+--------
+ (b 10)
+(1 row)
+
+-- del_member from NULL
+SELECT test_bms_del_member('(b)', 10) IS NULL as result;
+ result 
+--------
+ t
+(1 row)
+
+-- del_member singleton becomes empty
+SELECT test_bms_del_member('(b 10)', 10) IS NULL as result;
+ result 
+--------
+ t
+(1 row)
+
+-- del_member no change
+SELECT test_bms_del_member('(b 10)', 5) as result;
+ result 
+--------
+ (b 10)
+(1 row)
+
+-- del_member from middle
+SELECT test_bms_del_member('(b 1 2 3)', 2) = '(b 1 3)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- del_member triggers realloc
+SELECT test_bms_del_member(test_bms_del_member('(b 0 31 32 63 64)', 32), 63) as result;
+   result    
+-------------
+ (b 0 31 64)
+(1 row)
+
+-- del_member word boundary
+SELECT test_bms_del_member(test_bms_add_range('(b)', 30, 34), 32) as result;
+     result      
+-----------------
+ (b 30 31 33 34)
+(1 row)
+
+-- union operations
+SELECT 'union overlapping sets' as test,
+       test_bms_union('(b 1 3 5)', '(b 3 5 7)') = '(b 1 3 5 7)' as result
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_union('(b 1 3 5)', '(b)') = '(b 1 3 5)' as result
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union('(b)', '(b)') IS NULL as result;
+          test          | result 
+------------------------+--------
+ union overlapping sets | t
+ union with NULL        | t
+ union NULL with NULL   | t
+(3 rows)
+
+SELECT 'overlapping ranges' as test,
+       test_bms_union(
+           test_bms_add_range('(b)', 0, 15),
+           test_bms_add_range('(b)', 10, 20)
+       ) as result;
+        test        |                          result                          
+--------------------+----------------------------------------------------------
+ overlapping ranges | (b 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)
+(1 row)
+
+-- intersection operations
+SELECT 'intersect overlapping sets' as test,
+       test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') = '(b 3 5)' as result
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') IS NULL as result
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect('(b 1 3 5)', '(b)') IS NULL as result;
+            test            | result 
+----------------------------+--------
+ intersect overlapping sets | t
+ intersect disjoint sets    | t
+ intersect with NULL        | t
+(3 rows)
+
+-- bms_int_members
+SELECT 'int(ersect) overlapping sets' as test,
+       test_bms_int_members('(b 1 3 5)', '(b 3 5 7)') = '(b 3 5)' as result
+UNION ALL
+SELECT 'int(ersect) disjoint sets' as test,
+       test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') IS NULL as result
+UNION ALL
+SELECT 'int(ersect) with NULL' as test,
+       test_bms_int_members('(b 1 3 5)', '(b)') IS NULL as result
+UNION ALL
+SELECT 'int(ersect) members' as test,
+	test_bms_int_members('(b 0 31 32 63 64)', '(b 31 32 64 65)') = '(b 31 32 64)' as result;
+             test             | result 
+------------------------------+--------
+ int(ersect) overlapping sets | t
+ int(ersect) disjoint sets    | t
+ int(ersect) with NULL        | t
+ int(ersect) members          | t
+(4 rows)
+
+-- difference operations
+SELECT 'difference overlapping sets' as test,
+       test_bms_difference('(b 1 3 5)', '(b 3 5 7)') = '(b 1)' as result
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_difference('(b 1 3 5)', '(b 2 4 6)') = '(b 1 3 5)' as result
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference('(b 1 3 5)', '(b 1 3 5)') IS NULL as result;
+            test             | result 
+-----------------------------+--------
+ difference overlapping sets | t
+ difference disjoint sets    | t
+ difference identical sets   | t
+(3 rows)
+
+SELECT 'difference subtraction edge case' as test,
+       test_bms_difference(
+           test_bms_add_range('(b)', 0, 100),
+           test_bms_add_range('(b)', 50, 150)
+       ) as result;
+               test               |                                                                     result                                                                      
+----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------
+ difference subtraction edge case | (b 0 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)
+(1 row)
+
+SELECT 'difference subtract to empty' as test,
+       test_bms_difference('(b 42)', '(b 42)') as result;
+             test             | result 
+------------------------------+--------
+ difference subtract to empty | 
+(1 row)
+
+-- membership tests
+SELECT 'is_member existing' as test, test_bms_is_member('(b 1 3 5)', 1) = true as result
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member('(b 1 3 5)', 2) = false as result
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member('(b 1 3 5)', 3) = true as result
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member('(b)', 1) = false as result;
+           test            | result 
+---------------------------+--------
+ is_member existing        | t
+ is_member missing         | t
+ is_member existing middle | t
+ is_member NULL set        | t
+(4 rows)
+
+-- num_members NULL
+SELECT test_bms_num_members('(b)') = 0 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- num_members small set
+SELECT test_bms_num_members('(b 1 3 5)') = 3 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- num_members larger set
+SELECT test_bms_num_members('(b 2 4 6 8 10)') = 5 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- set equality and comparison
+SELECT 'equal NULL NULL' as test, test_bms_equal('(b)', '(b)') = true as result
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal('(b)', '(b 1 3 5)') = false as result
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal('(b 1 3 5)', '(b)') = false as result
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal('(b 1 3 5)', '(b 1 3 5)') = true as result
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal('(b 1 3 5)', '(b 2 4 6)') = false as result
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare('(b)', '(b)') = 0 as result
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare('(b)', '(b 1 3)') = -1 as result
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare('(b 1 3)', '(b)') = 1 as result
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare('(b 1 3)', '(b 1 3)') = 0 as result
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare('(b 1 3)', '(b 1 3 5)') = -1 as result
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare('(b 1 3 5)', '(b 1 3)') = 1 as result;
+          test           | result 
+-------------------------+--------
+ equal NULL NULL         | t
+ equal NULL set          | t
+ equal set NULL          | t
+ equal identical sets    | t
+ equal different sets    | t
+ compare NULL NULL       | t
+ compare NULL set        | t
+ compare set NULL        | t
+ compare equal sets      | t
+ compare subset superset | t
+ compare superset subset | t
+(11 rows)
+
+SELECT 'compare edge case' as test,
+       test_bms_compare(
+           test_bms_add_range('(b)', 0, 63),
+           test_bms_add_range('(b)', 0, 64)
+       ) as result;
+       test        | result 
+-------------------+--------
+ compare edge case |     -1
+(1 row)
+
+-- add_range basic
+SELECT test_bms_add_range('(b)', 5, 7) = '(b 5 6 7)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_range single element
+SELECT test_bms_add_range('(b)', 5, 5) = '(b 5)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_range to existing
+SELECT test_bms_add_range('(b 1 10)', 5, 7) = '(b 1 5 6 7 10)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_range at word boundary 31
+SELECT test_bms_add_range('(b)', 30, 34) as result;
+       result       
+--------------------
+ (b 30 31 32 33 34)
+(1 row)
+
+-- add_range at word boundary 63
+SELECT test_bms_add_range('(b)', 62, 66) as result;
+       result       
+--------------------
+ (b 62 63 64 65 66)
+(1 row)
+
+-- add_range large range
+SELECT length(test_bms_add_range('(b)', 0, 1000)) = 3898 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_range force realloc test 1
+SELECT length(test_bms_add_range('(b)', 0, 200)) = 697 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add_range foce realloc test 2
+SELECT length(test_bms_add_range('(b)', 1000, 1100)) = 508 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- membership empty
+SELECT test_bms_membership('(b)') = 0 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- membership singleton
+SELECT test_bms_membership('(b 42)') = 1 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- membership multiple
+SELECT test_bms_membership('(b 1 2)') = 2 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- singleton_member valid
+SELECT test_bms_singleton_member('(b 42)') = 42 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- set iteration
+SELECT 'next_member first' as test, test_bms_next_member('(b 5 10 15 20)', -1) = 5 as result
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member('(b 5 10 15 20)', 5) = 10 as result
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member('(b 5 10 15 20)', 20) = -2 as result
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member('(b)', -1) = -2 as result
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member('(b 5 10 15 20)', 21) = 20 as result
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member('(b 5 10 15 20)', 20) = 15 as result
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member('(b 5 10 15 20)', 5) = -2 as result
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member('(b)', 100) = -2 as result;
+            test            | result 
+----------------------------+--------
+ next_member first          | t
+ next_member second         | t
+ next_member past end       | t
+ next_member empty set      | t
+ prev_member last           | t
+ prev_member penultimate    | t
+ prev_member past beginning | t
+ prev_member empty set      | t
+(8 rows)
+
+-- hash functions
+SELECT 'hash NULL' as test, test_bms_hash_value('(b)') = 0 as result
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value('(b 1 3 5)') = test_bms_hash_value('(b 1 3 5)')
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value('(b 1 3 5)') != test_bms_hash_value('(b 2 4 6)');
+        test         | result 
+---------------------+--------
+ hash NULL           | t
+ hash consistency    | t
+ hash different sets | t
+(3 rows)
+
+-- set overlap
+SELECT 'overlap existing' as test, test_bms_overlap('(b 1 3 5)', '(b 3 5 7)') = true as result
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap('(b 1 3 5)', '(b 2 4 6)') = false as result
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap('(b)', '(b 1 3 5)') = false as result;
+       test        | result 
+-------------------+--------
+ overlap existing  | t
+ overlap none      | t
+ overlap with NULL | t
+(3 rows)
+
+-- subset relations
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset('(b)', '(b 1 3 5)') = true as result
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset('(b 1 3)', '(b 1 3 5)') = true as result
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset('(b 1 3 5)', '(b 1 3)') = false as result
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset('(b 1 3)', '(b 2 4)') = false as result
+UNION ALL
+SELECT 'subset comparison edge' as test,
+	test_bms_is_subset(
+		test_bms_add_range(NULL, 0, 31),
+		test_bms_add_range(NULL, 0, 63))
+	= true as result;
+             test             | result 
+------------------------------+--------
+ subset NULL is subset of all | t
+ subset proper subset         | t
+ subset improper subset       | t
+ subset disjoint sets         | t
+ subset comparison edge       | t
+(5 rows)
+
+-- copy operations
+WITH test_set AS (SELECT '(b 1 3 5 7)' AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+     test      | result 
+---------------+--------
+ copy NULL     | t
+ copy equality | t
+(2 rows)
+
+-- add members operation
+SELECT test_bms_add_members('(b 1 3)', '(b 5 7)') = '(b 1 3 5 7)' as result;
+ result 
+--------
+ t
+(1 row)
+
+-- add members complex
+SELECT test_bms_add_members('(b 1 3 5)', '(b 100 200 300)') as result;
+        result         
+-----------------------
+ (b 1 3 5 100 200 300)
+(1 row)
+
+-- hash consistency
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash('(b)') = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash('(b 1 3 5)') = test_bitmap_hash('(b 1 3 5)') as result
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash('(b 1 3 5)') = test_bms_hash_value('(b 1 3 5)') as result
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash('(b 1 3 5)') != test_bitmap_hash('(b 2 4 6)') as result;
+             test              | result 
+-------------------------------+--------
+ bitmap_hash NULL              | t
+ bitmap_hash consistency       | t
+ bitmap_hash vs bms_hash_value | t
+ bitmap_hash different sets    | t
+(4 rows)
+
+-- match function
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match('(b)', '(b)') = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match('(b)', '(b 1 3 5)') = 1 as result
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match('(b 1 3 5)', '(b)') = 1 as result
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match('(b 1 3 5)', '(b 1 3 5)') = 0 as result
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match('(b 1 3 5)', '(b 2 4 6)') = 1 as result
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match('(b 1 3)', '(b 1 3 5)') = 1 as result;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match NULL NULL (should be 0)       | t
+ bitmap_match NULL set (should be 1)        | t
+ bitmap_match set NULL (should be 1)        | t
+ bitmap_match identical sets (should be 0)  | t
+ bitmap_match different sets (should be 1)  | t
+ bitmap_match subset/superset (should be 1) | t
+(6 rows)
+
+-- match relationship with bms_equal
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match('(b 1 3 5)', '(b 1 3 5)') = 0) = test_bms_equal('(b 1 3 5)', '(b 1 3 5)') as result
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match('(b 1 3 5)', '(b 2 4 6)') = 0) = test_bms_equal('(b 1 3 5)', '(b 2 4 6)') as result
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match('(b)', '(b)') = 0) = test_bms_equal('(b)', '(b)') as result;
+                    test                    | result 
+--------------------------------------------+--------
+ bitmap_match vs bms_equal (equal sets)     | t
+ bitmap_match vs bms_equal (different sets) | t
+ bitmap_match vs bms_equal (NULL cases)     | t
+(3 rows)
+
+-- bitmap_match [1,3,5] vs [1,3,5]
+SELECT test_bitmap_match('(b 1 3 5)', '(b 1 3 5)') as match_value;
+ match_value 
+-------------
+           0
+(1 row)
+
+-- bitmap_match [1,3,5] vs [2,4,6]
+SELECT test_bitmap_match('(b 1 3 5)', '(b 2 4 6)') as match_value;
+ match_value 
+-------------
+           1
+(1 row)
+
+-- bitmap_match empty arrays
+SELECT test_bitmap_match('(b)', '(b)') = 0 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- overlap with lists
+WITH test_lists AS (
+    SELECT
+        ARRAY[0] AS a0,
+        ARRAY[1,2] AS a12,
+        ARRAY[3,4,5] AS a345,
+        ARRAY[6,7,8,9] AS a6789
+)
+SELECT 'overlap list 0' as test,
+       test_bms_overlap_list('(b 0)', a0) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 12' as test,
+       test_bms_overlap_list('(b 2 3)', a12) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 345' as test,
+       test_bms_overlap_list('(b 3 4)', a345) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 6789' as test,
+       test_bms_overlap_list('(b 7 10)', a6789) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 6789 no overlap' as test,
+       test_bms_overlap_list('(b 1 5)', a6789) as result
+FROM test_lists;
+             test             | result 
+------------------------------+--------
+ overlap list 0               | t
+ overlap list 12              | t
+ overlap list 345             | t
+ overlap list 6789            | t
+ overlap list 6789 no overlap | f
+(5 rows)
+
+-- overlap empty list
+SELECT test_bms_overlap_list('(b 1)', ARRAY[]::integer[]) as result;
+ result 
+--------
+ f
+(1 row)
+
+-- random operations
+SELECT test_random_operations(-1, 10000, 81920, 0) > 0 as result;
+ result 
+--------
+ t
+(1 row)
+
+-- these should produce ERRORs
+SELECT test_bms_make_singleton(-1);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_member('(b 1)', -1);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_is_member('(b)', -5);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_member('(b)', -10);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_del_member('(b)', -20);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_add_range('(b)', -5, 10);
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_singleton_member('(b 1 2)');
+ERROR:  bitmapset has multiple members
+SELECT test_bms_add_member('(b)', 1000);
+ test_bms_add_member 
+---------------------
+ (b 1000)
+(1 row)
+
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/meson.build b/src/test/modules/test_bitmapset/meson.build
new file mode 100644
index 00000000000..848f7a44eb9
--- /dev/null
+++ b/src/test/modules/test_bitmapset/meson.build
@@ -0,0 +1,33 @@
+# Copyright (c) 2024-2025, PostgreSQL Global Development Group
+
+test_bitmapset_sources = files(
+  'test_bitmapset.c',
+)
+
+if host_system == 'windows'
+  test_bitmapset_sources += rc_lib_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'test_bitmapset',
+    '--FILEDESC', 'test_bitmapset - test code for src/include/nodes/bitmapset.h',])
+endif
+
+test_bitmapset = shared_module('test_bitmapset',
+  test_bitmapset_sources,
+  kwargs: pg_test_mod_args,
+)
+test_install_libs += test_bitmapset
+
+test_install_data += files(
+  'test_bitmapset.control',
+  'test_bitmapset--1.0.sql',
+)
+
+tests += {
+  'name': 'test_bitmapset',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'regress': {
+    'sql': [
+      'test_bitmapset',
+    ],
+  },
+}
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
new file mode 100644
index 00000000000..c80e6193219
--- /dev/null
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -0,0 +1,312 @@
+CREATE EXTENSION IF NOT EXISTS test_bitmapset;
+
+-- make_singleton(42)
+SELECT test_bms_make_singleton(42) = '(b 42)' as result;
+-- make_singleton(0)
+SELECT test_bms_make_singleton(0) = '(b 0)' as result;
+-- make_singleton(1000)
+SELECT test_bms_make_singleton(1000) = '(b 1000)' as result;
+
+-- add_member(NULL, 10)
+SELECT test_bms_add_member('(b)', 10) = '(b 10)' as result;
+-- add_member consistency
+SELECT test_bms_add_member('(b)', 10) as result;
+-- add_member to existing
+SELECT test_bms_add_member('(b 5)', 10) = '(b 5 10)' as result;
+-- add_member sorted
+SELECT test_bms_add_member('(b 10)', 5) = '(b 5 10)' as result;
+-- add_member idempotent
+SELECT test_bms_add_member('(b 10)', 10) as result;
+
+
+-- del_member from NULL
+SELECT test_bms_del_member('(b)', 10) IS NULL as result;
+-- del_member singleton becomes empty
+SELECT test_bms_del_member('(b 10)', 10) IS NULL as result;
+-- del_member no change
+SELECT test_bms_del_member('(b 10)', 5) as result;
+-- del_member from middle
+SELECT test_bms_del_member('(b 1 2 3)', 2) = '(b 1 3)' as result;
+-- del_member triggers realloc
+SELECT test_bms_del_member(test_bms_del_member('(b 0 31 32 63 64)', 32), 63) as result;
+-- del_member word boundary
+SELECT test_bms_del_member(test_bms_add_range('(b)', 30, 34), 32) as result;
+
+-- union operations
+SELECT 'union overlapping sets' as test,
+       test_bms_union('(b 1 3 5)', '(b 3 5 7)') = '(b 1 3 5 7)' as result
+UNION ALL
+SELECT 'union with NULL' as test,
+       test_bms_union('(b 1 3 5)', '(b)') = '(b 1 3 5)' as result
+UNION ALL
+SELECT 'union NULL with NULL' as test,
+       test_bms_union('(b)', '(b)') IS NULL as result;
+SELECT 'overlapping ranges' as test,
+       test_bms_union(
+           test_bms_add_range('(b)', 0, 15),
+           test_bms_add_range('(b)', 10, 20)
+       ) as result;
+
+-- intersection operations
+SELECT 'intersect overlapping sets' as test,
+       test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') = '(b 3 5)' as result
+UNION ALL
+SELECT 'intersect disjoint sets' as test,
+       test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') IS NULL as result
+UNION ALL
+SELECT 'intersect with NULL' as test,
+       test_bms_intersect('(b 1 3 5)', '(b)') IS NULL as result;
+
+-- bms_int_members
+SELECT 'int(ersect) overlapping sets' as test,
+       test_bms_int_members('(b 1 3 5)', '(b 3 5 7)') = '(b 3 5)' as result
+UNION ALL
+SELECT 'int(ersect) disjoint sets' as test,
+       test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') IS NULL as result
+UNION ALL
+SELECT 'int(ersect) with NULL' as test,
+       test_bms_int_members('(b 1 3 5)', '(b)') IS NULL as result
+UNION ALL
+SELECT 'int(ersect) members' as test,
+	test_bms_int_members('(b 0 31 32 63 64)', '(b 31 32 64 65)') = '(b 31 32 64)' as result;
+
+-- difference operations
+SELECT 'difference overlapping sets' as test,
+       test_bms_difference('(b 1 3 5)', '(b 3 5 7)') = '(b 1)' as result
+UNION ALL
+SELECT 'difference disjoint sets' as test,
+       test_bms_difference('(b 1 3 5)', '(b 2 4 6)') = '(b 1 3 5)' as result
+UNION ALL
+SELECT 'difference identical sets' as test,
+       test_bms_difference('(b 1 3 5)', '(b 1 3 5)') IS NULL as result;
+SELECT 'difference subtraction edge case' as test,
+       test_bms_difference(
+           test_bms_add_range('(b)', 0, 100),
+           test_bms_add_range('(b)', 50, 150)
+       ) as result;
+SELECT 'difference subtract to empty' as test,
+       test_bms_difference('(b 42)', '(b 42)') as result;
+
+-- membership tests
+SELECT 'is_member existing' as test, test_bms_is_member('(b 1 3 5)', 1) = true as result
+UNION ALL
+SELECT 'is_member missing' as test, test_bms_is_member('(b 1 3 5)', 2) = false as result
+UNION ALL
+SELECT 'is_member existing middle' as test, test_bms_is_member('(b 1 3 5)', 3) = true as result
+UNION ALL
+SELECT 'is_member NULL set' as test, test_bms_is_member('(b)', 1) = false as result;
+
+-- num_members NULL
+SELECT test_bms_num_members('(b)') = 0 as result;
+-- num_members small set
+SELECT test_bms_num_members('(b 1 3 5)') = 3 as result;
+-- num_members larger set
+SELECT test_bms_num_members('(b 2 4 6 8 10)') = 5 as result;
+
+-- set equality and comparison
+SELECT 'equal NULL NULL' as test, test_bms_equal('(b)', '(b)') = true as result
+UNION ALL
+SELECT 'equal NULL set' as test, test_bms_equal('(b)', '(b 1 3 5)') = false as result
+UNION ALL
+SELECT 'equal set NULL' as test, test_bms_equal('(b 1 3 5)', '(b)') = false as result
+UNION ALL
+SELECT 'equal identical sets' as test, test_bms_equal('(b 1 3 5)', '(b 1 3 5)') = true as result
+UNION ALL
+SELECT 'equal different sets' as test, test_bms_equal('(b 1 3 5)', '(b 2 4 6)') = false as result
+UNION ALL
+SELECT 'compare NULL NULL' as test, test_bms_compare('(b)', '(b)') = 0 as result
+UNION ALL
+SELECT 'compare NULL set' as test, test_bms_compare('(b)', '(b 1 3)') = -1 as result
+UNION ALL
+SELECT 'compare set NULL' as test, test_bms_compare('(b 1 3)', '(b)') = 1 as result
+UNION ALL
+SELECT 'compare equal sets' as test, test_bms_compare('(b 1 3)', '(b 1 3)') = 0 as result
+UNION ALL
+SELECT 'compare subset superset' as test, test_bms_compare('(b 1 3)', '(b 1 3 5)') = -1 as result
+UNION ALL
+SELECT 'compare superset subset' as test, test_bms_compare('(b 1 3 5)', '(b 1 3)') = 1 as result;
+SELECT 'compare edge case' as test,
+       test_bms_compare(
+           test_bms_add_range('(b)', 0, 63),
+           test_bms_add_range('(b)', 0, 64)
+       ) as result;
+
+-- add_range basic
+SELECT test_bms_add_range('(b)', 5, 7) = '(b 5 6 7)' as result;
+-- add_range single element
+SELECT test_bms_add_range('(b)', 5, 5) = '(b 5)' as result;
+-- add_range to existing
+SELECT test_bms_add_range('(b 1 10)', 5, 7) = '(b 1 5 6 7 10)' as result;
+-- add_range at word boundary 31
+SELECT test_bms_add_range('(b)', 30, 34) as result;
+-- add_range at word boundary 63
+SELECT test_bms_add_range('(b)', 62, 66) as result;
+-- add_range large range
+SELECT length(test_bms_add_range('(b)', 0, 1000)) = 3898 as result;
+-- add_range force realloc test 1
+SELECT length(test_bms_add_range('(b)', 0, 200)) = 697 as result;
+-- add_range foce realloc test 2
+SELECT length(test_bms_add_range('(b)', 1000, 1100)) = 508 as result;
+
+-- membership empty
+SELECT test_bms_membership('(b)') = 0 as result;
+-- membership singleton
+SELECT test_bms_membership('(b 42)') = 1 as result;
+-- membership multiple
+SELECT test_bms_membership('(b 1 2)') = 2 as result;
+
+-- singleton_member valid
+SELECT test_bms_singleton_member('(b 42)') = 42 as result;
+
+-- set iteration
+SELECT 'next_member first' as test, test_bms_next_member('(b 5 10 15 20)', -1) = 5 as result
+UNION ALL
+SELECT 'next_member second' as test, test_bms_next_member('(b 5 10 15 20)', 5) = 10 as result
+UNION ALL
+SELECT 'next_member past end' as test, test_bms_next_member('(b 5 10 15 20)', 20) = -2 as result
+UNION ALL
+SELECT 'next_member empty set' as test, test_bms_next_member('(b)', -1) = -2 as result
+UNION ALL
+SELECT 'prev_member last' as test, test_bms_prev_member('(b 5 10 15 20)', 21) = 20 as result
+UNION ALL
+SELECT 'prev_member penultimate' as test, test_bms_prev_member('(b 5 10 15 20)', 20) = 15 as result
+UNION ALL
+SELECT 'prev_member past beginning' as test, test_bms_prev_member('(b 5 10 15 20)', 5) = -2 as result
+UNION ALL
+SELECT 'prev_member empty set' as test, test_bms_prev_member('(b)', 100) = -2 as result;
+
+-- hash functions
+SELECT 'hash NULL' as test, test_bms_hash_value('(b)') = 0 as result
+UNION ALL
+SELECT 'hash consistency' as test, test_bms_hash_value('(b 1 3 5)') = test_bms_hash_value('(b 1 3 5)')
+UNION ALL
+SELECT 'hash different sets' as test, test_bms_hash_value('(b 1 3 5)') != test_bms_hash_value('(b 2 4 6)');
+
+-- set overlap
+SELECT 'overlap existing' as test, test_bms_overlap('(b 1 3 5)', '(b 3 5 7)') = true as result
+UNION ALL
+SELECT 'overlap none' as test, test_bms_overlap('(b 1 3 5)', '(b 2 4 6)') = false as result
+UNION ALL
+SELECT 'overlap with NULL' as test, test_bms_overlap('(b)', '(b 1 3 5)') = false as result;
+
+-- subset relations
+SELECT 'subset NULL is subset of all' as test, test_bms_is_subset('(b)', '(b 1 3 5)') = true as result
+UNION ALL
+SELECT 'subset proper subset' as test, test_bms_is_subset('(b 1 3)', '(b 1 3 5)') = true as result
+UNION ALL
+SELECT 'subset improper subset' as test, test_bms_is_subset('(b 1 3 5)', '(b 1 3)') = false as result
+UNION ALL
+SELECT 'subset disjoint sets' as test, test_bms_is_subset('(b 1 3)', '(b 2 4)') = false as result
+UNION ALL
+SELECT 'subset comparison edge' as test,
+	test_bms_is_subset(
+		test_bms_add_range(NULL, 0, 31),
+		test_bms_add_range(NULL, 0, 63))
+	= true as result;
+
+-- copy operations
+WITH test_set AS (SELECT '(b 1 3 5 7)' AS original)
+SELECT 'copy NULL' as test, test_bms_copy(NULL) IS NULL as result
+UNION ALL
+SELECT 'copy equality' as test, test_bms_equal(original, test_bms_copy(original)) = true as result FROM test_set;
+
+-- add members operation
+SELECT test_bms_add_members('(b 1 3)', '(b 5 7)') = '(b 1 3 5 7)' as result;
+-- add members complex
+SELECT test_bms_add_members('(b 1 3 5)', '(b 100 200 300)') as result;
+
+-- hash consistency
+SELECT 'bitmap_hash NULL' as test,
+       test_bitmap_hash('(b)') = 0 as result
+UNION ALL
+SELECT 'bitmap_hash consistency' as test,
+       test_bitmap_hash('(b 1 3 5)') = test_bitmap_hash('(b 1 3 5)') as result
+UNION ALL
+SELECT 'bitmap_hash vs bms_hash_value' as test,
+       test_bitmap_hash('(b 1 3 5)') = test_bms_hash_value('(b 1 3 5)') as result
+UNION ALL
+SELECT 'bitmap_hash different sets' as test,
+       test_bitmap_hash('(b 1 3 5)') != test_bitmap_hash('(b 2 4 6)') as result;
+
+-- match function
+SELECT 'bitmap_match NULL NULL (should be 0)' as test,
+       test_bitmap_match('(b)', '(b)') = 0 as result
+UNION ALL
+SELECT 'bitmap_match NULL set (should be 1)' as test,
+       test_bitmap_match('(b)', '(b 1 3 5)') = 1 as result
+UNION ALL
+SELECT 'bitmap_match set NULL (should be 1)' as test,
+       test_bitmap_match('(b 1 3 5)', '(b)') = 1 as result
+UNION ALL
+SELECT 'bitmap_match identical sets (should be 0)' as test,
+       test_bitmap_match('(b 1 3 5)', '(b 1 3 5)') = 0 as result
+UNION ALL
+SELECT 'bitmap_match different sets (should be 1)' as test,
+       test_bitmap_match('(b 1 3 5)', '(b 2 4 6)') = 1 as result
+UNION ALL
+SELECT 'bitmap_match subset/superset (should be 1)' as test,
+       test_bitmap_match('(b 1 3)', '(b 1 3 5)') = 1 as result;
+
+-- match relationship with bms_equal
+SELECT 'bitmap_match vs bms_equal (equal sets)' as test,
+       (test_bitmap_match('(b 1 3 5)', '(b 1 3 5)') = 0) = test_bms_equal('(b 1 3 5)', '(b 1 3 5)') as result
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (different sets)' as test,
+       (test_bitmap_match('(b 1 3 5)', '(b 2 4 6)') = 0) = test_bms_equal('(b 1 3 5)', '(b 2 4 6)') as result
+UNION ALL
+SELECT 'bitmap_match vs bms_equal (NULL cases)' as test,
+       (test_bitmap_match('(b)', '(b)') = 0) = test_bms_equal('(b)', '(b)') as result;
+
+-- bitmap_match [1,3,5] vs [1,3,5]
+SELECT test_bitmap_match('(b 1 3 5)', '(b 1 3 5)') as match_value;
+-- bitmap_match [1,3,5] vs [2,4,6]
+SELECT test_bitmap_match('(b 1 3 5)', '(b 2 4 6)') as match_value;
+
+-- bitmap_match empty arrays
+SELECT test_bitmap_match('(b)', '(b)') = 0 as result;
+
+-- overlap with lists
+WITH test_lists AS (
+    SELECT
+        ARRAY[0] AS a0,
+        ARRAY[1,2] AS a12,
+        ARRAY[3,4,5] AS a345,
+        ARRAY[6,7,8,9] AS a6789
+)
+SELECT 'overlap list 0' as test,
+       test_bms_overlap_list('(b 0)', a0) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 12' as test,
+       test_bms_overlap_list('(b 2 3)', a12) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 345' as test,
+       test_bms_overlap_list('(b 3 4)', a345) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 6789' as test,
+       test_bms_overlap_list('(b 7 10)', a6789) as result
+FROM test_lists
+UNION ALL
+SELECT 'overlap list 6789 no overlap' as test,
+       test_bms_overlap_list('(b 1 5)', a6789) as result
+FROM test_lists;
+
+-- overlap empty list
+SELECT test_bms_overlap_list('(b 1)', ARRAY[]::integer[]) as result;
+
+-- random operations
+SELECT test_random_operations(-1, 10000, 81920, 0) > 0 as result;
+
+-- these should produce ERRORs
+SELECT test_bms_make_singleton(-1);
+SELECT test_bms_add_member('(b 1)', -1);
+SELECT test_bms_is_member('(b)', -5);
+SELECT test_bms_add_member('(b)', -10);
+SELECT test_bms_del_member('(b)', -20);
+SELECT test_bms_add_range('(b)', -5, 10);
+SELECT test_bms_singleton_member('(b 1 2)');
+SELECT test_bms_add_member('(b)', 1000);
+
+DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
new file mode 100644
index 00000000000..95f5ee02e3f
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -0,0 +1,136 @@
+/* src/test/modules/test_bitmapset/test_bitmapset--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION test_bitmapset" to load this file. \quit
+
+-- Bitmapset API functions
+CREATE FUNCTION test_bms_make_singleton(integer)
+RETURNS text STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_member(text, integer)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_del_member(text, integer)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_member(text, integer)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_num_members(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_copy(text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_equal(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_compare(text, text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_subset(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_subset_compare(text, text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_union(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_intersect(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_difference(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_is_empty(text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_membership(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_singleton_member(text)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_get_singleton_member(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_next_member(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_prev_member(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_hash_value(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_overlap_list(text, int4[])
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_nonempty_difference(text, text)
+RETURNS boolean
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_member_index(text, integer)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_range(text, integer, integer)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_add_members(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_int_members(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_replace_members(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bms_join(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_hash(text)
+RETURNS integer
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_bitmap_match(text, text)
+RETURNS int
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+-- Test utility functions
+CREATE FUNCTION test_random_operations(integer, integer, integer, integer)
+RETURNS integer STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
+COMMENT ON EXTENSION test_bitmapset IS 'Test code for Bitmapset';
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
new file mode 100644
index 00000000000..d1c74807ec1
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -0,0 +1,1008 @@
+/*
+ * test_bitmapset.c
+ *      Test module for bitmapset data structure
+ *
+ * This module tests the bitmapset implementation in PostgreSQL,
+ * covering all public API functions, edge cases, and memory usage.
+ *
+ * src/test/modules/test_bitmapset/test_bitmapset.c
+ */
+
+#include "postgres.h"
+
+#include <stddef.h>
+#include "catalog/pg_type.h"
+#include "common/pg_prng.h"
+#include "utils/array.h"
+#include "fmgr.h"
+#include "nodes/bitmapset.h"
+#include "nodes/nodes.h"
+#include "nodes/pg_list.h"
+#include "utils/builtins.h"
+#include "utils/timestamp.h"
+#include "varatt.h"
+
+PG_MODULE_MAGIC;
+
+/* Utility functions */
+PG_FUNCTION_INFO_V1(test_bms_from_array);
+PG_FUNCTION_INFO_V1(test_bms_to_array);
+
+/* Bitmapset API functions in order of appearance in bitmapset.c */
+PG_FUNCTION_INFO_V1(test_bms_make_singleton);
+PG_FUNCTION_INFO_V1(test_bms_add_member);
+PG_FUNCTION_INFO_V1(test_bms_del_member);
+PG_FUNCTION_INFO_V1(test_bms_is_member);
+PG_FUNCTION_INFO_V1(test_bms_num_members);
+PG_FUNCTION_INFO_V1(test_bms_copy);
+PG_FUNCTION_INFO_V1(test_bms_equal);
+PG_FUNCTION_INFO_V1(test_bms_compare);
+PG_FUNCTION_INFO_V1(test_bms_is_subset);
+PG_FUNCTION_INFO_V1(test_bms_subset_compare);
+PG_FUNCTION_INFO_V1(test_bms_union);
+PG_FUNCTION_INFO_V1(test_bms_intersect);
+PG_FUNCTION_INFO_V1(test_bms_difference);
+PG_FUNCTION_INFO_V1(test_bms_is_empty);
+PG_FUNCTION_INFO_V1(test_bms_membership);
+PG_FUNCTION_INFO_V1(test_bms_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_get_singleton_member);
+PG_FUNCTION_INFO_V1(test_bms_next_member);
+PG_FUNCTION_INFO_V1(test_bms_prev_member);
+PG_FUNCTION_INFO_V1(test_bms_hash_value);
+PG_FUNCTION_INFO_V1(test_bms_overlap);
+PG_FUNCTION_INFO_V1(test_bms_overlap_list);
+PG_FUNCTION_INFO_V1(test_bms_nonempty_difference);
+PG_FUNCTION_INFO_V1(test_bms_member_index);
+PG_FUNCTION_INFO_V1(test_bms_add_range);
+PG_FUNCTION_INFO_V1(test_bms_add_members);
+PG_FUNCTION_INFO_V1(test_bms_int_members);
+PG_FUNCTION_INFO_V1(test_bms_replace_members);
+PG_FUNCTION_INFO_V1(test_bms_join);
+PG_FUNCTION_INFO_V1(test_bitmap_hash);
+PG_FUNCTION_INFO_V1(test_bitmap_match);
+
+/* Test utility functions */
+PG_FUNCTION_INFO_V1(test_random_operations);
+
+/* Convenient macros to test results */
+#define EXPECT_TRUE(expr)	\
+	do { \
+		if (!(expr)) \
+			elog(ERROR, \
+				 "%s was unexpectedly false in file \"%s\" line %u", \
+				 #expr, __FILE__, __LINE__); \
+	} while (0)
+
+#define EXPECT_NOT_NULL(expr)	\
+	do { \
+		if ((expr) == NULL) \
+			elog(ERROR, \
+				 "%s was unexpectedly true in file \"%s\" line %u", \
+				 #expr, __FILE__, __LINE__); \
+	} while (0)
+
+/* Encode/Decode to/from TEXT and Bitmapset */
+#define BITMAPSET_TO_TEXT(bms) (text *) CStringGetTextDatum(nodeToString((bms)))
+#define TEXT_TO_BITMAPSET(str) (Bitmapset *) stringToNode(TextDatumGetCString((Datum) (str)))
+
+/*
+ * Individual test functions for each bitmapset API function
+ */
+
+Datum
+test_bms_add_member(PG_FUNCTION_ARGS)
+{
+	int			member;
+	Bitmapset  *bms = NULL;
+	text	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	bms = bms_add_member(bms, member);
+	result = BITMAPSET_TO_TEXT(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	if (result == NULL)
+		PG_RETURN_NULL();
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_add_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	/* IMPORTANT: bms_add_members modifies/frees the first argument */
+	bms1 = bms_add_members(bms1, bms2);
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (bms1 == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(bms1);
+	bms_free(bms1);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_del_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	text	   *result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	bms = bms_del_member(bms, member);
+
+	if (bms == NULL || bms_is_empty(bms))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	result = BITMAPSET_TO_TEXT(bms);
+	bms_free(bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_is_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		member;
+	bool		result;
+
+	if (PG_ARGISNULL(1))
+		PG_RETURN_BOOL(false);
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	member = PG_GETARG_INT32(1);
+	result = bms_is_member(member, bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_num_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result = 0;
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	result = bms_num_members(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_make_singleton(PG_FUNCTION_ARGS)
+{
+	int32		member;
+	Bitmapset  *bms;
+	text	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	member = PG_GETARG_INT32(0);
+	bms = bms_make_singleton(member);
+
+	result = BITMAPSET_TO_TEXT(bms);
+	bms_free(bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_copy(PG_FUNCTION_ARGS)
+{
+	text	   *bms_data;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *copy_bms;
+	text	   *result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_NULL();
+
+	bms_data = PG_GETARG_TEXT_PP(0);
+	bms = TEXT_TO_BITMAPSET(bms_data);
+	copy_bms = bms_copy(bms);
+	result = BITMAPSET_TO_TEXT(copy_bms);
+
+	if (bms)
+		bms_free(bms);
+	if (copy_bms)
+		bms_free(copy_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_equal(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result = bms_equal(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_union(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result_bms = bms_union(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_membership(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	BMS_Membership result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(BMS_EMPTY_SET);
+
+	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	result = bms_membership(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_next_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
+		PG_RETURN_INT32(-2);
+
+	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	prevmember = PG_GETARG_INT32(1);
+	result = bms_next_member(bms, prevmember);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_intersect(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result_bms = bms_intersect(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result_bms = bms_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result = bms_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_is_empty(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	result = bms_is_empty(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_is_subset(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result = bms_is_subset(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_subset_compare(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	BMS_Comparison result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result = bms_subset_compare(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32((int32) result);
+}
+
+Datum
+test_bms_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int			result;
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	result = bms_singleton_member(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_get_singleton_member(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		default_member = PG_GETARG_INT32(1);
+	int			member;
+	bool		success;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(default_member);
+
+	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	/*
+	 * bms_get_singleton_member returns bool and stores result in member
+	 * pointer
+	 */
+	success = bms_get_singleton_member(bms, &member);
+	bms_free(bms);
+
+	if (success)
+		PG_RETURN_INT32(member);
+	else
+		PG_RETURN_INT32(default_member);
+}
+
+Datum
+test_bms_prev_member(PG_FUNCTION_ARGS)
+{
+	text	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		prevmember;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-2);
+
+	bms_data = PG_GETARG_TEXT_PP(0);
+	prevmember = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-2);
+
+	bms = TEXT_TO_BITMAPSET(bms_data);
+	result = bms_prev_member(bms, prevmember);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_overlap(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result = bms_overlap(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_overlap_list(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	ArrayType  *array;
+	List	   *int_list = NIL;
+	bool		result;
+	Datum	   *elem_datums;
+	bool	   *elem_nulls;
+	int			elem_count;
+	int			i;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_BOOL(false);
+
+	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (PG_ARGISNULL(1))
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_BOOL(false);
+	}
+
+	array = PG_GETARG_ARRAYTYPE_P(1);
+
+	if (ARR_ELEMTYPE(array) != INT4OID)
+		ereport(ERROR,
+				(errcode(ERRCODE_DATATYPE_MISMATCH),
+				 errmsg("integer array expected")));
+
+	deconstruct_array(array,
+					  INT4OID, sizeof(int32), true, 'i',
+					  &elem_datums, &elem_nulls, &elem_count);
+
+	for (i = 0; i < elem_count; i++)
+	{
+		if (!elem_nulls[i])
+		{
+			int32		member = DatumGetInt32(elem_datums[i]);
+
+			int_list = lappend_int(int_list, member);
+		}
+	}
+
+	result = bms_overlap_list(bms, int_list);
+
+	if (bms)
+		bms_free(bms);
+
+	list_free(int_list);
+
+	pfree(elem_datums);
+	pfree(elem_nulls);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_nonempty_difference(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	bool		result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	result = bms_nonempty_difference(bms1, bms2);
+
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_BOOL(result);
+}
+
+Datum
+test_bms_member_index(PG_FUNCTION_ARGS)
+{
+	text	   *bms_data;
+	Bitmapset  *bms = NULL;
+	int32		member;
+	int			result;
+
+	if (PG_ARGISNULL(0))
+		PG_RETURN_INT32(-1);
+
+	bms_data = PG_GETARG_TEXT_PP(0);
+	member = PG_GETARG_INT32(1);
+
+	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
+		PG_RETURN_INT32(-1);
+
+	bms = TEXT_TO_BITMAPSET(bms_data);
+
+	result = bms_member_index(bms, member);
+	bms_free(bms);
+
+	PG_RETURN_INT32(result);
+}
+
+Datum
+test_bms_add_range(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	int32		lower,
+				upper;
+	text	   *result;
+
+	if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
+		PG_RETURN_NULL();
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	lower = PG_GETARG_INT32(1);
+	upper = PG_GETARG_INT32(2);
+
+	/* Check for invalid range */
+	if (upper < lower)
+	{
+		if (bms)
+			bms_free(bms);
+		PG_RETURN_NULL();
+	}
+
+	bms = bms_add_range(bms, lower, upper);
+
+	result = BITMAPSET_TO_TEXT(bms);
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_int_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	bms1 = bms_int_members(bms1, bms2);
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (bms1 == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(bms1);
+
+	if (bms1)
+		bms_free(bms1);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_replace_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	/* IMPORTANT: bms_replace_members modifies/frees the first argument */
+	result_bms = bms_replace_members(bms1, bms2);
+	/* bms1 is now invalid, don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_join(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	/* IMPORTANT: bms_join modifies/frees the first argument */
+	result_bms = bms_join(bms1, bms2);
+	/* bms1 is now invalid! Don't free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
+Datum
+test_bms_hash_value(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	hash_result = bms_hash_value(bms);
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_hash(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms = NULL;
+	Bitmapset  *bms_ptr;
+	uint32		hash_result;
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	bms_ptr = bms;
+
+	/* Call bitmap_hash */
+	hash_result = bitmap_hash(&bms_ptr, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (!PG_ARGISNULL(0) && bms_ptr)
+		bms_free(bms_ptr);
+
+	PG_RETURN_INT32(hash_result);
+}
+
+Datum
+test_bitmap_match(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *bms_ptr1,
+			   *bms_ptr2;
+	int			match_result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	/* Set up pointers to the Bitmapsets */
+	bms_ptr1 = bms1;
+	bms_ptr2 = bms2;
+
+	/* Call bitmap_match with addresses of the Bitmapset pointers */
+	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
+
+	/* Clean up */
+	if (bms1)
+		bms_free(bms1);
+	if (bms2)
+		bms_free(bms2);
+
+	PG_RETURN_INT32(match_result);
+}
+
+Datum
+test_random_operations(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL;
+	Bitmapset  *bms2 = NULL;
+	Bitmapset  *bms = NULL;
+	Bitmapset  *result = NULL;
+	pg_prng_state state;
+	uint64		seed = GetCurrentTimestamp();
+	int			num_ops = 5000;
+	int			total_ops = 0;
+	int			max_range = 2000;
+	int			min_value = 0;
+	int			member;
+	int		   *members;
+	int			num_members = 0;
+
+	if (!PG_ARGISNULL(0) && PG_GETARG_INT32(0) > 0)
+		seed = PG_GETARG_INT32(0);
+
+	if (!PG_ARGISNULL(1))
+		num_ops = PG_GETARG_INT32(1);
+
+	if (!PG_ARGISNULL(2))
+		max_range = PG_GETARG_INT32(2);
+
+	if (!PG_ARGISNULL(3))
+		min_value = PG_GETARG_INT32(3);
+
+	pg_prng_seed(&state, seed);
+	members = palloc(sizeof(int) * num_ops);
+
+	/* Phase 1: Random insertions */
+	for (int i = 0; i < num_ops / 2; i++)
+	{
+		member = pg_prng_uint32(&state) % max_range + min_value;
+
+		if (!bms_is_member(member, bms1))
+		{
+			members[num_members++] = member;
+			bms1 = bms_add_member(bms1, member);
+		}
+	}
+
+	/* Phase 2: Random set operations */
+	for (int i = 0; i < num_ops / 4; i++)
+	{
+		member = pg_prng_uint32(&state) % max_range + min_value;
+
+		bms2 = bms_add_member(bms2, member);
+	}
+
+	/* Test union */
+	result = bms_union(bms1, bms2);
+	EXPECT_NOT_NULL(result);
+
+	/* Verify union contains all members from first set */
+	for (int i = 0; i < num_members; i++)
+	{
+		if (!bms_is_member(members[i], result))
+			elog(ERROR, "union missing member %d", members[i]);
+	}
+	bms_free(result);
+
+	/* Test intersection */
+	result = bms_intersect(bms1, bms2);
+	if (result != NULL)
+	{
+		member = -1;
+
+		while ((member = bms_next_member(result, member)) >= 0)
+		{
+			if (!bms_is_member(member, bms1) || !bms_is_member(member, bms2))
+				elog(ERROR, "intersection contains invalid member %d", member);
+		}
+		bms_free(result);
+	}
+
+	/* Phase 3: Test range operations */
+	result = NULL;
+	for (int i = 0; i < 10; i++)
+	{
+		int			lower = pg_prng_uint32(&state) % 100;
+		int			upper = lower + (pg_prng_uint32(&state) % 20);
+
+		result = bms_add_range(result, lower, upper);
+	}
+	if (result != NULL)
+	{
+		EXPECT_TRUE(bms_num_members(result) > 0);
+		bms_free(result);
+	}
+
+	pfree(members);
+	bms_free(bms1);
+	bms_free(bms2);
+
+	for (int i = 0; i < num_ops; i++)
+	{
+		member = pg_prng_uint32(&state) % max_range + min_value;
+		switch (pg_prng_uint32(&state) % 3)
+		{
+			case 0:				/* add */
+				bms = bms_add_member(bms, member);
+				break;
+			case 1:				/* delete */
+				if (bms != NULL)
+				{
+					bms = bms_del_member(bms, member);
+				}
+				break;
+			case 2:				/* test membership */
+				if (bms != NULL)
+				{
+					bms_is_member(member, bms);
+				}
+				break;
+		}
+		total_ops++;
+	}
+
+	if (bms)
+		bms_free(bms);
+
+	PG_RETURN_INT32(total_ops);
+}
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.control b/src/test/modules/test_bitmapset/test_bitmapset.control
new file mode 100644
index 00000000000..8d02ec8bf0a
--- /dev/null
+++ b/src/test/modules/test_bitmapset/test_bitmapset.control
@@ -0,0 +1,4 @@
+comment = 'Test code for Bitmapset'
+default_version = '1.0'
+module_pathname = '$libdir/test_bitmapset'
+relocatable = true
-- 
2.49.0

#29Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#28)
Re: [PATCH] Add tests for Bitmapset

On Fri, Sep 19, 2025 at 02:48:43PM -0400, Greg Burd wrote:

I think I've incorporated your feedback which did indeed make the patch
more readable/crisp and maintainable, thank you.

coverage: HEAD v7 v8
lines......: 87.1 90.5 92.2

bitmap_match() had some duplicated tests.

bms_replace_members() was not covered, and a function was added to the
module. I get up to 93.4% for the lines, once added.

+PG_FUNCTION_INFO_V1(test_bms_from_array);
+PG_FUNCTION_INFO_V1(test_bms_to_array);
These two were still declared, are not required.

There were a couple of functions that acted as dead code in the
module, covered in the tree. As we are trying to cover the gap I
think that we should just do the whole thing. Here are the functions:
- is_empty
- subset_compare
- get_singleton_member
- nonempty_difference
- member_index
- join. The test C function had a mistake, because either input may
be modified or updated by bms_join(). The code was freeing the right
input, leading to errors in the node output function when tested.

Mixing the CTEs and the UNION ALL would have been nice if the queries
in the UNIONs relied on more than one input value, but none of them
did that, so I have removed this part and made the tests leaner. That
feels easier for the eye.

Testing on equality for the hash functions should be OK, so I have
kept these, including the NULL/0 cases.

A few incorrect things related to the style, fixed on the way, like an
incorrect copyright notice in meson.build, the top of test_bitmapset.c
was largely incorrect. It seems like these were copy-pasted from
elsewhere.

Another thing was testing with -DREALLOCATE_BITMAPSETS, which I've
done. A couple of code paths related to the test C functions don't
test for NULL input, which is still OK as these don't impact the
internal tests or the backend coverage, so I've left these out.

The result I had was good enough, so applied. The CI was OK, the
buildfarm may have a different opinion.
--
Michael

#30Greg Burd
greg@burd.me
In reply to: Michael Paquier (#29)
Re: [PATCH] Add tests for Bitmapset

On Sep 22 2025, at 3:57 am, Michael Paquier <michael@paquier.xyz> wrote:

On Fri, Sep 19, 2025 at 02:48:43PM -0400, Greg Burd wrote:

I think I've incorporated your feedback which did indeed make the patch
more readable/crisp and maintainable, thank you.

coverage: HEAD v7 v8
lines......: 87.1 90.5 92.2

Michael,

Thank you for your time and help.

bitmap_match() had some duplicated tests.

bms_replace_members() was not covered, and a function was added to the
module. I get up to 93.4% for the lines, once added.

+PG_FUNCTION_INFO_V1(test_bms_from_array);
+PG_FUNCTION_INFO_V1(test_bms_to_array);
These two were still declared, are not required.

There were a couple of functions that acted as dead code in the
module, covered in the tree. As we are trying to cover the gap I
think that we should just do the whole thing. Here are the functions:
- is_empty
- subset_compare
- get_singleton_member
- nonempty_difference
- member_index
- join. The test C function had a mistake, because either input may
be modified or updated by bms_join(). The code was freeing the right
input, leading to errors in the node output function when tested.

All great ideas, apologies for the oversights.

Mixing the CTEs and the UNION ALL would have been nice if the queries
in the UNIONs relied on more than one input value, but none of them
did that, so I have removed this part and made the tests leaner. That
feels easier for the eye.

Agreed, thank you.

Testing on equality for the hash functions should be OK, so I have
kept these, including the NULL/0 cases.

Sounds good to me.

A few incorrect things related to the style, fixed on the way, like an
incorrect copyright notice in meson.build, the top of test_bitmapset.c
was largely incorrect. It seems like these were copy-pasted from
elsewhere.

Yes, copied from the radixtree test module.

Another thing was testing with -DREALLOCATE_BITMAPSETS, which I've
done.

That seems like a good idea, I thought about doing that as well.

A couple of code paths related to the test C functions don't
test for NULL input, which is still OK as these don't impact the
internal tests or the backend coverage, so I've left these out.

Fair.

The result I had was good enough, so applied. The CI was OK, the
buildfarm may have a different opinion.
--
Michael

Thanks for the help getting this done, I really appreciate it. So far
the buildfarm seems okay. :)

best.

-greg

#31Tom Lane
tgl@sss.pgh.pa.us
In reply to: Michael Paquier (#29)
Re: [PATCH] Add tests for Bitmapset

Michael Paquier <michael@paquier.xyz> writes:

The result I had was good enough, so applied. The CI was OK, the
buildfarm may have a different opinion.

This patch seems to be rather full of arbitrary casts to or
from Datum, which is no longer okay. You need to be using
the appropriate conversion macros, such as PointerGetDatum.

https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&amp;dt=2025-09-23%2002%3A12%3A36

regards, tom lane

#32Michael Paquier
michael@paquier.xyz
In reply to: Tom Lane (#31)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Tue, Sep 23, 2025 at 01:43:47AM -0400, Tom Lane wrote:

Michael Paquier <michael@paquier.xyz> writes:

The result I had was good enough, so applied. The CI was OK, the
buildfarm may have a different opinion.

This patch seems to be rather full of arbitrary casts to or
from Datum, which is no longer okay. You need to be using
the appropriate conversion macros, such as PointerGetDatum.

https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&amp;dt=2025-09-23%2002%3A12%3A36

Right, this can ve reproduced with a -m32 added to gcc.

I don't see a need for a Datum manipulation in these conversion
macros, as we already allocate the results to and from "text"
before/after using the GETARG or RETURN macros. Using directly
text_to_cstring() and cstring_to_text() takes care of the warnings, as
well.
--
Michael

Attachments:

test_bitmapset-warnings.patchtext/x-diff; charset=us-asciiDownload
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 61f256f65a44..f5473e58ce8e 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -84,8 +84,8 @@ PG_FUNCTION_INFO_V1(test_random_operations);
 	} while (0)
 
 /* Encode/Decode to/from TEXT and Bitmapset */
-#define BITMAPSET_TO_TEXT(bms) (text *) CStringGetTextDatum(nodeToString((bms)))
-#define TEXT_TO_BITMAPSET(str) (Bitmapset *) stringToNode(TextDatumGetCString((Datum) (str)))
+#define BITMAPSET_TO_TEXT(bms) cstring_to_text(nodeToString((bms)))
+#define TEXT_TO_BITMAPSET(str) (Bitmapset *) stringToNode(text_to_cstring(str))
 
 /*
  * Individual test functions for each bitmapset API function
#33Tom Lane
tgl@sss.pgh.pa.us
In reply to: Michael Paquier (#32)
Re: [PATCH] Add tests for Bitmapset

Michael Paquier <michael@paquier.xyz> writes:

On Tue, Sep 23, 2025 at 01:43:47AM -0400, Tom Lane wrote:

This patch seems to be rather full of arbitrary casts to or
from Datum, which is no longer okay. You need to be using
the appropriate conversion macros, such as PointerGetDatum.

Right, this can ve reproduced with a -m32 added to gcc.

Curiously, I don't see these warnings on 32-bit FreeBSD
(with clang version 19.1.7). But I tested your patch on
mamba's host and confirmed that it makes that gcc happy.

I don't see a need for a Datum manipulation in these conversion
macros, as we already allocate the results to and from "text"
before/after using the GETARG or RETURN macros. Using directly
text_to_cstring() and cstring_to_text() takes care of the warnings, as
well.

Yeah, this is better, but I think the new macros could use a bit
more parenthesis-twiddling:

+#define BITMAPSET_TO_TEXT(bms) cstring_to_text(nodeToString((bms)))

The extra parens around "bms" are surely unnecessary. (If they were
necessary, it could only be because nodeToString was a macro that
failed to parenthesize its argument where needed. But that would
be a bug to fix in nodeToString, not here.)

+#define TEXT_TO_BITMAPSET(str) (Bitmapset *) stringToNode(text_to_cstring(str))

Here, on the other hand, I think an extra outer set of parens
would be a good idea, ie

+#define TEXT_TO_BITMAPSET(str) ((Bitmapset *) stringToNode(text_to_cstring(str)))

It may be that the C cast binds tightly enough that this cannot
be a problem, but I don't think assuming that is project style.

regards, tom lane

#34Greg Burd
greg@burd.me
In reply to: Tom Lane (#33)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 23 2025, at 12:46 pm, Tom Lane <tgl@sss.pgh.pa.us> wrote:

Michael Paquier <michael@paquier.xyz> writes:

On Tue, Sep 23, 2025 at 01:43:47AM -0400, Tom Lane wrote:

This patch seems to be rather full of arbitrary casts to or
from Datum, which is no longer okay. You need to be using
the appropriate conversion macros, such as PointerGetDatum.

Tom, thanks for pointing out the oversight. Apologies, I should have
tried that out in my local tests.

Right, this can ve reproduced with a -m32 added to gcc.

Curiously, I don't see these warnings on 32-bit FreeBSD
(with clang version 19.1.7). But I tested your patch on
mamba's host and confirmed that it makes that gcc happy.

I don't see a need for a Datum manipulation in these conversion
macros, as we already allocate the results to and from "text"
before/after using the GETARG or RETURN macros. Using directly
text_to_cstring() and cstring_to_text() takes care of the warnings, as
well.

Yeah, this is better, but I think the new macros could use a bit
more parenthesis-twiddling:

+#define BITMAPSET_TO_TEXT(bms) cstring_to_text(nodeToString((bms)))

Agreed, that was my mistake.

The extra parens around "bms" are surely unnecessary. (If they were
necessary, it could only be because nodeToString was a macro that
failed to parenthesize its argument where needed. But that would
be a bug to fix in nodeToString, not here.)

+#define TEXT_TO_BITMAPSET(str) (Bitmapset *) stringToNode(text_to_cstring(str))

Here, on the other hand, I think an extra outer set of parens
would be a good idea, ie

+#define TEXT_TO_BITMAPSET(str) ((Bitmapset *) stringToNode(text_to_cstring(str)))

Sounds reasonable to me.

It may be that the C cast binds tightly enough that this cannot
be a problem, but I don't think assuming that is project style.

regards, tom lane

patch attached, best.

-greg

Attachments:

v1-0001-Avoid-triggering-warnings-in-Bitmapset-tests-rela.patchapplication/octet-streamDownload
From ca3031bf1b041839bf629ea44f58371796e9ebd5 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Tue, 23 Sep 2025 14:11:10 -0400
Subject: [PATCH v1] Avoid triggering warnings in Bitmapset tests related to
 Datum casts

The Bitmapset tests encode/decode bitmaps to/from text using the available
nodeTo/FromString() functions for simplicity.  They don't need for a Datum
manipulation in their conversion macros, as we already allocate the results to
and from "text" before/after using the GETARG or RETURN macros. Using directly
text_to_cstring() and cstring_to_text() takes care of these warnings.
---
 src/test/modules/test_bitmapset/test_bitmapset.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 61f256f65a4..5bc4daa23f1 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -84,8 +84,8 @@ PG_FUNCTION_INFO_V1(test_random_operations);
 	} while (0)
 
 /* Encode/Decode to/from TEXT and Bitmapset */
-#define BITMAPSET_TO_TEXT(bms) (text *) CStringGetTextDatum(nodeToString((bms)))
-#define TEXT_TO_BITMAPSET(str) (Bitmapset *) stringToNode(TextDatumGetCString((Datum) (str)))
+#define BITMAPSET_TO_TEXT(bms) cstring_to_text(nodeToString(bms))
+#define TEXT_TO_BITMAPSET(str) ((Bitmapset *) stringToNode(text_to_cstring(str)))
 
 /*
  * Individual test functions for each bitmapset API function
-- 
2.50.1 (Apple Git-155)

#35Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#34)
Re: [PATCH] Add tests for Bitmapset

On Tue, Sep 23, 2025 at 02:26:19PM -0400, Greg Burd wrote:

patch attached, best.

All that seems to work corrently here, so done.
--
Michael

#36Greg Burd
greg@burd.me
In reply to: Michael Paquier (#35)
Re: [PATCH] Add tests for Bitmapset

On Sep 23 2025, at 7:23 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Tue, Sep 23, 2025 at 02:26:19PM -0400, Greg Burd wrote:

patch attached, best.

All that seems to work corrently here, so done.
--
Michael

Thanks Michael, Tom, for the help getting this into shape and in the tree.

best.

-greg

#37Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#36)
Re: [PATCH] Add tests for Bitmapset

On Wed, Sep 24, 2025 at 07:39:59AM -0400, Greg Burd wrote:

Thanks Michael, Tom, for the help getting this into shape and in the tree.

By the way, Greg, do you think that we should aim for a state where we
are closer to completion? We have the module up to the point where we
are in pretty good shape, with most things and the infrastructure done
but it can be improved a bit more, as well.

Based on the information provided by the coverage report at
https://coverage.postgresql.org/src/backend/nodes/bitmapset.c.gcov.html,
we still have the following things:
- bms_equal for different word counts
- bms_union, bms_nonempty_difference, bms_is_subset and bms_intersect
with shorter word counts.
- bms_different with different word counts
- A couple more cases with bms_subset_compare
- bms_member_index and word counts
- bms_overlap_list with negative number in input list.
- bms_singleton_member ERROR with empty input.
- bms_get_singleton_member with NULL input
- bms_del_member with word counts
- bms_replace_members and repalloc case
- bms_add_range, bms_join and bms_del_members, more word count cases
- bms_prev_member and the prevbit business

There is not much we can do with the random function, still we could
do something about the NULL paths in the internal functions:
https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html

The coverage of the latter matters less than the coverage of the
former, of course.
--
Michael

#38Greg Burd
greg@burd.me
In reply to: Michael Paquier (#37)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 24 2025, at 7:28 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Wed, Sep 24, 2025 at 07:39:59AM -0400, Greg Burd wrote:

Thanks Michael, Tom, for the help getting this into shape and in the tree.

By the way, Greg, do you think that we should aim for a state where we
are closer to completion?

Hi Michael,

We've come this far, why not go all the way? :)

We have the module up to the point where we
are in pretty good shape, with most things and the infrastructure done
but it can be improved a bit more, as well.

Agreed.

Based on the information provided by the coverage report at
https://coverage.postgresql.org/src/backend/nodes/bitmapset.c.gcov.html,
we still have the following things:
- bms_equal for different word counts
- bms_union, bms_nonempty_difference, bms_is_subset and bms_intersect
with shorter word counts.
- bms_different with different word counts
- A couple more cases with bms_subset_compare
- bms_member_index and word counts
- bms_overlap_list with negative number in input list.
- bms_singleton_member ERROR with empty input.
- bms_get_singleton_member with NULL input
- bms_del_member with word counts
- bms_replace_members and repalloc case
- bms_add_range, bms_join and bms_del_members, more word count cases
- bms_prev_member and the prevbit business

Thanks for the detailed analysis, I tried to address each of these in
the patch.

There is not much we can do with the random function, still we could
do something about the NULL paths in the internal functions:
https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html

Agreed.

The coverage of the latter matters less than the coverage of the
former, of course.

Agreed.

--
Michael

test_bitmapset.c
lines......: 98.9%
functions..: 100%
branches...: 82.6%

Here I removed a bit of code I thought was unnecessary and added a few
test cases. The coverage is better overall, not much to say about it.

bitmapset.c
lines......: 99.8%
functions..: 100%
branches...: 89.4%

A few branches were really tricky, my (least) favorite was the
bms_subset_compare(). To get to the first BMS_DIFFERENT return you have
to have a test case where the shorter bitmap is long enough to force two
or more iterations of the loop and in the first iteration the first word
in a needs to be a subset of b and then for the second word the opposite
where the second word of b is a subset of a and yet there can be no
overlapping bits in the two sets and the same number of words in both sets.

test_bms_subset_compare('(b 1 64 65)', '(b 1 2 64)') -> BMS_DIFFERENT

Technically the '(b 64 200)', '(b 1 201)' test case is also
BMS_DIFFERENT and so redundant, but I was so happy to find the test case
for this branch I kept them both.

best.

-greg

Attachments:

v1-0001-Further-improve-the-test-coverage-of-Bitmapset.patchapplication/octet-streamDownload
From a3ce1eeb35d3430ce55e8e7189c3aa8e74645db6 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 25 Sep 2025 12:14:49 -0400
Subject: [PATCH v1] Further improve the test coverage of Bitmapset

Improve test coverage on both bitmapset.c and the code that tests
it, test_bitmapset.c with a few more tests that trigger branch
conditions and special cases.

This extends commit 00c3d87 and f83fe65.

Author: Greg Burd <greg@burd.me>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/3027069.1758606227@sss.pgh.pa.us
---
 .../expected/test_bitmapset.out               | 852 +++++++++++++++++-
 .../test_bitmapset/sql/test_bitmapset.sql     | 173 +++-
 .../test_bitmapset/test_bitmapset--1.0.sql    |   4 +
 .../modules/test_bitmapset/test_bitmapset.c   |  62 +-
 4 files changed, 1013 insertions(+), 78 deletions(-)

diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
index abbfef1f7a6..cb6d71fb7b1 100644
--- a/src/test/modules/test_bitmapset/expected/test_bitmapset.out
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -83,6 +83,13 @@ SELECT test_bms_replace_members('(b 1 2)', '(b 3 5 7)') AS result;
  (b 3 5 7)
 (1 row)
 
+-- Force repalloc() with larger set
+SELECT test_bms_replace_members('(b 1 2 3 4 5)', '(b 500 600)') AS result;
+   result    
+-------------
+ (b 500 600)
+(1 row)
+
 -- bms_del_member()
 SELECT test_bms_del_member('(b)', -20); -- error
 ERROR:  negative bitmapset member not allowed
@@ -124,6 +131,74 @@ SELECT test_bms_del_member(test_bms_add_range('(b)', 30, 34), 32) AS result;
  (b 30 31 33 34)
 (1 row)
 
+-- Force word count changes
+SELECT test_bms_del_member('(b 1 200)', 200) AS result;
+ result 
+--------
+ (b 1)
+(1 row)
+
+SELECT test_bms_del_member('(b 1 50 100 200)', 200) AS result;
+    result    
+--------------
+ (b 1 50 100)
+(1 row)
+
+SELECT test_bms_del_member('(b 1 50 100 200)', 100) AS result;
+    result    
+--------------
+ (b 1 50 200)
+(1 row)
+
+-- bms_del_members()
+SELECT test_bms_del_members('(b)', '(b 10)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_del_members('(b 10)', '(b 10)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_del_members('(b 10)', '(b 5)') AS result;
+ result 
+--------
+ (b 10)
+(1 row)
+
+SELECT test_bms_del_members('(b 1 2 3)', '(b 2)') AS result;
+ result  
+---------
+ (b 1 3)
+(1 row)
+
+SELECT test_bms_del_members('(b 5 100)', '(b 100)') AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_del_members('(b 5 100 200)', '(b 200)') AS result;
+  result   
+-----------
+ (b 5 100)
+(1 row)
+
+SELECT test_bms_del_members('(b 1 2 100 200 300)', '(b 1 2)') AS result;
+     result      
+-----------------
+ (b 100 200 300)
+(1 row)
+
+SELECT test_bms_del_members('(b 1 2 100 200 300)', '(b 200 300)') AS result;
+   result    
+-------------
+ (b 1 2 100)
+(1 row)
+
 -- bms_join()
 SELECT test_bms_join('(b 1 3 5)', NULL) AS result;
   result   
@@ -149,8 +224,21 @@ SELECT test_bms_join('(b 1 3 5)', '(b 1 4 5)') AS result;
  (b 1 3 4 5)
 (1 row)
 
+-- Force word count changes
+SELECT test_bms_join('(b 5)', '(b 100)') AS result;
+  result   
+-----------
+ (b 5 100)
+(1 row)
+
+SELECT test_bms_join('(b 1 2)', '(b 100 200 300)') AS result;
+       result        
+---------------------
+ (b 1 2 100 200 300)
+(1 row)
+
 -- bms_union()
--- Overlapping sets.
+-- Overlapping sets
 SELECT test_bms_union('(b 1 3 5)', '(b 3 5 7)') AS result;
    result    
 -------------
@@ -181,6 +269,19 @@ SELECT test_bms_union(
  (b 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)
 (1 row)
 
+-- Union with varrying word counts
+SELECT test_bms_union('(b 1 2)', '(b 100 300)') AS result;
+     result      
+-----------------
+ (b 1 2 100 300)
+(1 row)
+
+SELECT test_bms_union('(b 100 300)', '(b 1 2)') AS result;
+     result      
+-----------------
+ (b 1 2 100 300)
+(1 row)
+
 -- bms_intersect()
 -- Overlapping sets
 SELECT test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') AS result;
@@ -196,13 +297,26 @@ SELECT test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') AS result;
  
 (1 row)
 
--- Intersect with empty.
+-- Intersect with empty
 SELECT test_bms_intersect('(b 1 3 5)', '(b)') AS result;
  result 
 --------
  
 (1 row)
 
+-- Intersect with varrying word counts
+SELECT test_bms_intersect('(b 1 300)', '(b 1 2 3 4 5)') AS result;
+ result 
+--------
+ (b 1)
+(1 row)
+
+SELECT test_bms_intersect('(b 1 2 3 4 5)', '(b 1 300)') AS result;
+ result 
+--------
+ (b 1)
+(1 row)
+
 -- bms_int_members()
 -- Overlapping sets
 SELECT test_bms_int_members('(b 1 3 5)', '(b 3 5 7)') AS result;
@@ -218,7 +332,7 @@ SELECT test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') AS result;
  
 (1 row)
 
--- Intersect with empty.
+-- Intersect with empty
 SELECT test_bms_int_members('(b 1 3 5)', '(b)') AS result;
  result 
 --------
@@ -262,13 +376,26 @@ SELECT test_bms_difference('(b 42)', '(b 42)') AS result;
 (1 row)
 
 -- Subtraction edge case
-SELECT test_bms_difference(
+SELECT length(test_bms_difference(
          test_bms_add_range('(b)', 0, 100),
          test_bms_add_range('(b)', 50, 150)
-       ) AS result;
-                                                                     result                                                                      
--------------------------------------------------------------------------------------------------------------------------------------------------
- (b 0 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)
+       )) AS result;
+ result 
+--------
+    143
+(1 row)
+
+-- Difference with different word counts
+SELECT test_bms_difference('(b 5 100)', '(b 5)') AS result;
+ result  
+---------
+ (b 100)
+(1 row)
+
+SELECT test_bms_difference('(b 1 2 100 200)', '(b 1 2)') AS result;
+   result    
+-------------
+ (b 100 200)
 (1 row)
 
 -- bms_is_member()
@@ -323,6 +450,25 @@ SELECT test_bms_member_index('(b 1 3 5)', 3) AS result;
       1
 (1 row)
 
+-- Member index with various word positions
+SELECT test_bms_member_index('(b 100 200)', 100) AS result;
+ result 
+--------
+      0
+(1 row)
+
+SELECT test_bms_member_index('(b 100 200)', 200) AS result;
+ result 
+--------
+      1
+(1 row)
+
+SELECT test_bms_member_index('(b 1 50 100 200)', 200) AS result;
+ result 
+--------
+      3
+(1 row)
+
 -- bms_num_members()
 SELECT test_bms_num_members('(b)') AS result;
  result 
@@ -373,6 +519,19 @@ SELECT test_bms_equal('(b 1 3 5)', '(b 2 4 6)') AS result;
  f
 (1 row)
 
+-- Equal with different word counts
+SELECT test_bms_equal('(b 5)', '(b 100)') AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_equal('(b 5 10)', '(b 100 200 300)') AS result;
+ result 
+--------
+ f
+(1 row)
+
 -- bms_compare()
 SELECT test_bms_compare('(b)', '(b)') AS result;
  result 
@@ -474,6 +633,19 @@ SELECT length(test_bms_add_range('(b)', 1000, 1100)) AS result;
     508
 (1 row)
 
+-- Force word count expansion
+SELECT test_bms_add_range('(b 5)', 100, 105) AS result;
+            result             
+-------------------------------
+ (b 5 100 101 102 103 104 105)
+(1 row)
+
+SELECT length(test_bms_add_range('(b 1 2)', 200, 250)) AS result;
+ result 
+--------
+    211
+(1 row)
+
 -- bms_membership()
 SELECT test_bms_membership('(b)') AS result;
  result 
@@ -513,6 +685,8 @@ SELECT test_bms_is_empty('(b 1)') AS result;
 (1 row)
 
 -- bms_singleton_member()
+SELECT test_bms_singleton_member('(b)'); -- error
+ERROR:  bitmapset is empty
 SELECT test_bms_singleton_member('(b 1 2)'); -- error
 ERROR:  bitmapset has multiple members
 SELECT test_bms_singleton_member('(b 42)') AS result;
@@ -522,11 +696,17 @@ SELECT test_bms_singleton_member('(b 42)') AS result;
 (1 row)
 
 -- bms_get_singleton_member()
+SELECT test_bms_get_singleton_member('(b)', 1000); -- error
+ test_bms_get_singleton_member 
+-------------------------------
+                            -1
+(1 row)
+
 -- Not a singleton, returns input default
 SELECT test_bms_get_singleton_member('(b 3 6)', 1000) AS result;
  result 
 --------
-   1000
+     -1
 (1 row)
 
 -- Singletone, returns sole member
@@ -593,6 +773,13 @@ SELECT test_bms_prev_member('(b)', 100) AS result;
      -2
 (1 row)
 
+-- Negative prevbit should result in highest possible bit in set
+SELECT test_bms_prev_member('(b 0 63 64 127)', -1) AS result;
+ result 
+--------
+    127
+(1 row)
+
 -- bms_hash_value()
 SELECT test_bms_hash_value('(b)') = 0 AS result;
  result 
@@ -663,47 +850,156 @@ SELECT test_bms_is_subset(test_bms_add_range(NULL, 0, 31),
  t
 (1 row)
 
--- bms_subset_compare()
-SELECT test_bms_subset_compare(NULL, NULL) AS result;
+-- Is subset with shorter word counts
+SELECT test_bms_is_subset('(b 5 100)', '(b 5)') AS result;
  result 
 --------
-      0
+ f
 (1 row)
 
-SELECT test_bms_subset_compare('(b 1 3)', NULL) AS result;
+SELECT test_bms_is_subset('(b 1 2 50 100)', '(b 1 2)') AS result;
  result 
 --------
-      2
+ f
 (1 row)
 
-SELECT test_bms_subset_compare(NULL, '(b 1 3)') AS result;
- result 
---------
-      1
+-- bms_subset_compare()
+SELECT test_bms_subset_compare(NULL, NULL);
+ test_bms_subset_compare 
+-------------------------
+                       0
 (1 row)
 
-SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3)') AS result;
- result 
---------
-      2
+SELECT test_bms_subset_compare(NULL, '(b 1 3)');
+ test_bms_subset_compare 
+-------------------------
+                       1
 (1 row)
 
-SELECT test_bms_subset_compare('(b 1 3)', '(b 1 3 5)') AS result;
- result 
---------
-      1
+SELECT test_bms_subset_compare('(b)', '(b)');
+ test_bms_subset_compare 
+-------------------------
+                       0
 (1 row)
 
-SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3 5)') AS result;
- result 
---------
-      0
+SELECT test_bms_subset_compare('(b)', '(b 1)');
+ test_bms_subset_compare 
+-------------------------
+                       1
 (1 row)
 
-SELECT test_bms_subset_compare('(b 1 3 5)', '(b 2 4 6)') AS result;
- result 
---------
-      3
+SELECT test_bms_subset_compare('(b 1)', '(b)');
+ test_bms_subset_compare 
+-------------------------
+                       2
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3)', NULL);
+ test_bms_subset_compare 
+-------------------------
+                       2
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3 5)');
+ test_bms_subset_compare 
+-------------------------
+                       0
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3)', '(b 1 3 5)');
+ test_bms_subset_compare 
+-------------------------
+                       1
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3)');
+ test_bms_subset_compare 
+-------------------------
+                       2
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 2)', '(b 1 3)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 2)', '(b 1 4)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3)', '(b 1 3 64)');
+ test_bms_subset_compare 
+-------------------------
+                       1
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3 64)', '(b 1 3)');
+ test_bms_subset_compare 
+-------------------------
+                       2
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3 64)', '(b 1 3 65)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 3)', '(b 2 4)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1)', '(b 64)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 0)', '(b 32)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 0)', '(b 64)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 64)', '(b 1)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 2)', '(b 1 2 64)');
+ test_bms_subset_compare 
+-------------------------
+                       1
+(1 row)
+
+SELECT test_bms_subset_compare('(b 64 200)', '(b 1 201)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 1 64 65)', '(b 1 2 64)');
+ test_bms_subset_compare 
+-------------------------
+                       3
+(1 row)
+
+SELECT test_bms_subset_compare('(b 2 64 128)', '(b 1 65)');
+ test_bms_subset_compare 
+-------------------------
+                       3
 (1 row)
 
 -- bms_copy()
@@ -720,12 +1016,6 @@ SELECT test_bms_copy('(b 1 3 5 7)') AS result;
 (1 row)
 
 -- bms_add_members()
-SELECT test_bms_add_member('(b)', 1000); -- error
- test_bms_add_member 
----------------------
- (b 1000)
-(1 row)
-
 SELECT test_bms_add_members('(b 1 3)', '(b 5 7)') AS result;
    result    
 -------------
@@ -866,6 +1156,11 @@ SELECT test_bms_overlap_list('(b 1)', ARRAY[]::integer[]) AS result;
  f
 (1 row)
 
+-- Overlap list with negative numbers
+SELECT test_bms_overlap_list('(b 5 10)', ARRAY[-1,5]) AS result; -- error
+ERROR:  negative bitmapset member not allowed
+SELECT test_bms_overlap_list('(b 1 2 3)', ARRAY[-5,-1,0]) AS result; -- error
+ERROR:  negative bitmapset member not allowed
 -- bms_nonempty_difference()
 SELECT test_bms_nonempty_difference(NULL, '(b 1 3 5)') AS result;
  result 
@@ -897,6 +1192,25 @@ SELECT test_bms_nonempty_difference('(b 1 3 5)', '(b 1 3 5)') AS result;
  f
 (1 row)
 
+-- Difference with different word counts
+SELECT test_bms_nonempty_difference('(b 5)', '(b 100)') AS result;
+ result 
+--------
+ t
+(1 row)
+
+SELECT test_bms_nonempty_difference('(b 100)', '(b 5)') AS result;
+ result 
+--------
+ t
+(1 row)
+
+SELECT test_bms_nonempty_difference('(b 1 2)', '(b 50 100)') AS result;
+ result 
+--------
+ t
+(1 row)
+
 -- random operations
 SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
  result 
@@ -904,4 +1218,462 @@ SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
  t
 (1 row)
 
+-- Cover the test API's corner cases such as when ARGISNULL,
+-- or VARSIZE_ANY_EXHDR == 0, etc.
+SELECT test_bitmap_hash(NULL) AS result;
+ result 
+--------
+      0
+(1 row)
+
+SELECT test_bitmap_match('(b 5)', NULL) AS result;
+ result 
+--------
+      1
+(1 row)
+
+SELECT test_bitmap_match(NULL, '(b 5)') AS result;
+ result 
+--------
+      1
+(1 row)
+
+SELECT test_bitmap_match(NULL, NULL) AS result;
+ result 
+--------
+      0
+(1 row)
+
+SELECT test_bms_add_member('(b)', NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_add_range('(b 5)', 5, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_add_range('(b 5)', NULL, 10) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_add_range('(b 5)', NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_add_range(NULL, 5, 10) AS result;
+      result      
+------------------
+ (b 5 6 7 8 9 10)
+(1 row)
+
+SELECT test_bms_add_range(NULL, 10, 5) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_add_range(NULL, NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_compare('(b 5)', NULL) AS result;
+ result 
+--------
+      1
+(1 row)
+
+SELECT test_bms_compare(NULL, '(b 5)') AS result;
+ result 
+--------
+     -1
+(1 row)
+
+SELECT test_bms_compare(NULL, NULL) AS result;
+ result 
+--------
+      0
+(1 row)
+
+SELECT test_bms_copy(NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_del_member('(b 42)', 42) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_del_member('(b 5)', NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_del_members('(b 5)', NULL) AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_del_members(NULL, '(b 5)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_difference('(b 5)', '(b 5 10)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_difference('(b 5)', NULL) AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_difference(NULL, '(b 5)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_difference(NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_equal('(b 5)', NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_equal(NULL, '(b 5)') AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_equal(NULL, NULL) AS result;
+ result 
+--------
+ t
+(1 row)
+
+SELECT test_bms_get_singleton_member('', 1000) AS result;
+ result 
+--------
+     -1
+(1 row)
+
+SELECT test_bms_get_singleton_member(NULL, -1) AS result;
+ result 
+--------
+     -1
+(1 row)
+
+SELECT test_bms_hash_value(NULL) AS result;
+ result 
+--------
+      0
+(1 row)
+
+SELECT test_bms_int_members('(b 1)', '(b 2)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_int_members('(b 5)', NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_int_members(NULL, '(b 5)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_int_members(NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_intersect('(b 1)', '(b 2)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_intersect('(b 5)', NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_intersect(NULL, '(b 5)') AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_intersect(NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_is_empty(NULL) AS result;
+ result 
+--------
+ t
+(1 row)
+
+SELECT test_bms_is_member('(b 5)', NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_is_subset('(b 5)', NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_is_subset(NULL, '(b 5)') AS result;
+ result 
+--------
+ t
+(1 row)
+
+SELECT test_bms_is_subset(NULL, NULL) AS result;
+ result 
+--------
+ t
+(1 row)
+
+SELECT test_bms_join('(b 5)', NULL) AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_join(NULL, '(b 5)') AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_join(NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_make_singleton(NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_member_index('', 5) AS result;
+ result 
+--------
+     -1
+(1 row)
+
+SELECT test_bms_member_index(NULL, 5) AS result;
+ result 
+--------
+     -1
+(1 row)
+
+SELECT test_bms_membership(NULL) AS result;
+ result 
+--------
+      0
+(1 row)
+
+SELECT test_bms_next_member('', 5) AS result;
+ result 
+--------
+     -2
+(1 row)
+
+SELECT test_bms_next_member('(b 5)', NULL) AS result;
+ result 
+--------
+     -2
+(1 row)
+
+SELECT test_bms_next_member(NULL, 5) AS result;
+ result 
+--------
+     -2
+(1 row)
+
+SELECT test_bms_next_member(NULL, NULL) AS result;
+ result 
+--------
+     -2
+(1 row)
+
+SELECT test_bms_nonempty_difference('(b 5)', NULL) AS result;
+ result 
+--------
+ t
+(1 row)
+
+SELECT test_bms_nonempty_difference(NULL, '(b 5)') AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_nonempty_difference(NULL, NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_overlap('(b 5)', NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_overlap(NULL, '(b 5)') AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_overlap(NULL, NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_overlap_list('(b 5)', NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_overlap_list(NULL, ARRAY[1,2,3]) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_overlap_list(NULL, NULL) AS result;
+ result 
+--------
+ f
+(1 row)
+
+SELECT test_bms_prev_member('', 5) AS result;
+ result 
+--------
+     -2
+(1 row)
+
+SELECT test_bms_prev_member('(b 5)', NULL) AS result;
+ result 
+--------
+     -2
+(1 row)
+
+SELECT test_bms_prev_member(NULL, 5) AS result;
+ result 
+--------
+     -2
+(1 row)
+
+SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_replace_members('(b 5)', NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_replace_members(NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
+SELECT test_bms_singleton_member(NULL) AS result;
+ result 
+--------
+       
+(1 row)
+
+SELECT test_bms_subset_compare('(b 5)', NULL) AS result;
+ result 
+--------
+      2
+(1 row)
+
+SELECT test_bms_subset_compare(NULL, '(b 5)') AS result;
+ result 
+--------
+      1
+(1 row)
+
+SELECT test_bms_subset_compare(NULL, NULL) AS result;
+ result 
+--------
+      0
+(1 row)
+
+SELECT test_bms_union('(b 5)', NULL) AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_union(NULL, '(b 5)') AS result;
+ result 
+--------
+ (b 5)
+(1 row)
+
+SELECT test_bms_union(NULL, NULL) AS result;
+ result 
+--------
+ 
+(1 row)
+
 DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
index 2b2c72c876b..67e0f01ccb6 100644
--- a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -23,6 +23,8 @@ SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
 SELECT test_bms_replace_members('(b 1 2 3)', '(b 3 5 6)') AS result;
 SELECT test_bms_replace_members('(b 1 2 3)', '(b 3 5)') AS result;
 SELECT test_bms_replace_members('(b 1 2)', '(b 3 5 7)') AS result;
+-- Force repalloc() with larger set
+SELECT test_bms_replace_members('(b 1 2 3 4 5)', '(b 500 600)') AS result;
 
 -- bms_del_member()
 SELECT test_bms_del_member('(b)', -20); -- error
@@ -34,15 +36,32 @@ SELECT test_bms_del_member('(b 1 2 3)', 2) AS result;
 SELECT test_bms_del_member(test_bms_del_member('(b 0 31 32 63 64)', 32), 63) AS result;
 -- Word boundary
 SELECT test_bms_del_member(test_bms_add_range('(b)', 30, 34), 32) AS result;
+-- Force word count changes
+SELECT test_bms_del_member('(b 1 200)', 200) AS result;
+SELECT test_bms_del_member('(b 1 50 100 200)', 200) AS result;
+SELECT test_bms_del_member('(b 1 50 100 200)', 100) AS result;
+
+-- bms_del_members()
+SELECT test_bms_del_members('(b)', '(b 10)') AS result;
+SELECT test_bms_del_members('(b 10)', '(b 10)') AS result;
+SELECT test_bms_del_members('(b 10)', '(b 5)') AS result;
+SELECT test_bms_del_members('(b 1 2 3)', '(b 2)') AS result;
+SELECT test_bms_del_members('(b 5 100)', '(b 100)') AS result;
+SELECT test_bms_del_members('(b 5 100 200)', '(b 200)') AS result;
+SELECT test_bms_del_members('(b 1 2 100 200 300)', '(b 1 2)') AS result;
+SELECT test_bms_del_members('(b 1 2 100 200 300)', '(b 200 300)') AS result;
 
 -- bms_join()
 SELECT test_bms_join('(b 1 3 5)', NULL) AS result;
 SELECT test_bms_join(NULL, '(b 2 4 6)') AS result;
 SELECT test_bms_join('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT test_bms_join('(b 1 3 5)', '(b 1 4 5)') AS result;
+-- Force word count changes
+SELECT test_bms_join('(b 5)', '(b 100)') AS result;
+SELECT test_bms_join('(b 1 2)', '(b 100 200 300)') AS result;
 
 -- bms_union()
--- Overlapping sets.
+-- Overlapping sets
 SELECT test_bms_union('(b 1 3 5)', '(b 3 5 7)') AS result;
 -- Union with NULL
 SELECT test_bms_union('(b 1 3 5)', '(b)') AS result;
@@ -53,21 +72,27 @@ SELECT test_bms_union(
          test_bms_add_range('(b)', 0, 15),
          test_bms_add_range('(b)', 10, 20)
        ) AS result;
+-- Union with varrying word counts
+SELECT test_bms_union('(b 1 2)', '(b 100 300)') AS result;
+SELECT test_bms_union('(b 100 300)', '(b 1 2)') AS result;
 
 -- bms_intersect()
 -- Overlapping sets
 SELECT test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') AS result;
 -- Disjoint sets
 SELECT test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') AS result;
--- Intersect with empty.
+-- Intersect with empty
 SELECT test_bms_intersect('(b 1 3 5)', '(b)') AS result;
+-- Intersect with varrying word counts
+SELECT test_bms_intersect('(b 1 300)', '(b 1 2 3 4 5)') AS result;
+SELECT test_bms_intersect('(b 1 2 3 4 5)', '(b 1 300)') AS result;
 
 -- bms_int_members()
 -- Overlapping sets
 SELECT test_bms_int_members('(b 1 3 5)', '(b 3 5 7)') AS result;
 -- Disjoint sets
 SELECT test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') AS result;
--- Intersect with empty.
+-- Intersect with empty
 SELECT test_bms_int_members('(b 1 3 5)', '(b)') AS result;
 -- Multiple members
 SELECT test_bms_int_members('(b 0 31 32 63 64)', '(b 31 32 64 65)') AS result;
@@ -82,10 +107,13 @@ SELECT test_bms_difference('(b 1 3 5)', '(b 1 3 5)') AS result;
 -- Substraction to empty
 SELECT test_bms_difference('(b 42)', '(b 42)') AS result;
 -- Subtraction edge case
-SELECT test_bms_difference(
+SELECT length(test_bms_difference(
          test_bms_add_range('(b)', 0, 100),
          test_bms_add_range('(b)', 50, 150)
-       ) AS result;
+       )) AS result;
+-- Difference with different word counts
+SELECT test_bms_difference('(b 5 100)', '(b 5)') AS result;
+SELECT test_bms_difference('(b 1 2 100 200)', '(b 1 2)') AS result;
 
 -- bms_is_member()
 SELECT test_bms_is_member('(b)', -5); -- error
@@ -99,6 +127,10 @@ SELECT test_bms_member_index(NULL, 1) AS result;
 SELECT test_bms_member_index('(b 1 3 5)', 2) AS result;
 SELECT test_bms_member_index('(b 1 3 5)', 1) AS result;
 SELECT test_bms_member_index('(b 1 3 5)', 3) AS result;
+-- Member index with various word positions
+SELECT test_bms_member_index('(b 100 200)', 100) AS result;
+SELECT test_bms_member_index('(b 100 200)', 200) AS result;
+SELECT test_bms_member_index('(b 1 50 100 200)', 200) AS result;
 
 -- bms_num_members()
 SELECT test_bms_num_members('(b)') AS result;
@@ -111,6 +143,9 @@ SELECT test_bms_equal('(b)', '(b 1 3 5)') AS result;
 SELECT test_bms_equal('(b 1 3 5)', '(b)') AS result;
 SELECT test_bms_equal('(b 1 3 5)', '(b 1 3 5)') AS result;
 SELECT test_bms_equal('(b 1 3 5)', '(b 2 4 6)') AS result;
+-- Equal with different word counts
+SELECT test_bms_equal('(b 5)', '(b 100)') AS result;
+SELECT test_bms_equal('(b 5 10)', '(b 100 200 300)') AS result;
 
 -- bms_compare()
 SELECT test_bms_compare('(b)', '(b)') AS result;
@@ -138,6 +173,9 @@ SELECT length(test_bms_add_range('(b)', 0, 1000)) AS result;
 -- Force reallocations
 SELECT length(test_bms_add_range('(b)', 0, 200)) AS result;
 SELECT length(test_bms_add_range('(b)', 1000, 1100)) AS result;
+-- Force word count expansion
+SELECT test_bms_add_range('(b 5)', 100, 105) AS result;
+SELECT length(test_bms_add_range('(b 1 2)', 200, 250)) AS result;
 
 -- bms_membership()
 SELECT test_bms_membership('(b)') AS result;
@@ -150,10 +188,12 @@ SELECT test_bms_is_empty('(b)') AS result;
 SELECT test_bms_is_empty('(b 1)') AS result;
 
 -- bms_singleton_member()
+SELECT test_bms_singleton_member('(b)'); -- error
 SELECT test_bms_singleton_member('(b 1 2)'); -- error
 SELECT test_bms_singleton_member('(b 42)') AS result;
 
 -- bms_get_singleton_member()
+SELECT test_bms_get_singleton_member('(b)', 1000); -- error
 -- Not a singleton, returns input default
 SELECT test_bms_get_singleton_member('(b 3 6)', 1000) AS result;
 -- Singletone, returns sole member
@@ -176,6 +216,8 @@ SELECT test_bms_prev_member('(b 5 10 15 20)', 20) AS result;
 SELECT test_bms_prev_member('(b 5 10 15 20)', 5) AS result;
 -- Empty set
 SELECT test_bms_prev_member('(b)', 100) AS result;
+-- Negative prevbit should result in highest possible bit in set
+SELECT test_bms_prev_member('(b 0 63 64 127)', -1) AS result;
 
 -- bms_hash_value()
 SELECT test_bms_hash_value('(b)') = 0 AS result;
@@ -194,22 +236,40 @@ SELECT test_bms_is_subset('(b 1 3 5)', '(b 1 3)') AS result;
 SELECT test_bms_is_subset('(b 1 3)', '(b 2 4)') AS result;
 SELECT test_bms_is_subset(test_bms_add_range(NULL, 0, 31),
                           test_bms_add_range(NULL, 0, 63)) AS result;
+-- Is subset with shorter word counts
+SELECT test_bms_is_subset('(b 5 100)', '(b 5)') AS result;
+SELECT test_bms_is_subset('(b 1 2 50 100)', '(b 1 2)') AS result;
 
 -- bms_subset_compare()
-SELECT test_bms_subset_compare(NULL, NULL) AS result;
-SELECT test_bms_subset_compare('(b 1 3)', NULL) AS result;
-SELECT test_bms_subset_compare(NULL, '(b 1 3)') AS result;
-SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3)') AS result;
-SELECT test_bms_subset_compare('(b 1 3)', '(b 1 3 5)') AS result;
-SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3 5)') AS result;
-SELECT test_bms_subset_compare('(b 1 3 5)', '(b 2 4 6)') AS result;
+SELECT test_bms_subset_compare(NULL, NULL);
+SELECT test_bms_subset_compare(NULL, '(b 1 3)');
+SELECT test_bms_subset_compare('(b)', '(b)');
+SELECT test_bms_subset_compare('(b)', '(b 1)');
+SELECT test_bms_subset_compare('(b 1)', '(b)');
+SELECT test_bms_subset_compare('(b 1 3)', NULL);
+SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3 5)');
+SELECT test_bms_subset_compare('(b 1 3)', '(b 1 3 5)');
+SELECT test_bms_subset_compare('(b 1 3 5)', '(b 1 3)');
+SELECT test_bms_subset_compare('(b 1 2)', '(b 1 3)');
+SELECT test_bms_subset_compare('(b 1 2)', '(b 1 4)');
+SELECT test_bms_subset_compare('(b 1 3)', '(b 1 3 64)');
+SELECT test_bms_subset_compare('(b 1 3 64)', '(b 1 3)');
+SELECT test_bms_subset_compare('(b 1 3 64)', '(b 1 3 65)');
+SELECT test_bms_subset_compare('(b 1 3)', '(b 2 4)');
+SELECT test_bms_subset_compare('(b 1)', '(b 64)');
+SELECT test_bms_subset_compare('(b 0)', '(b 32)');
+SELECT test_bms_subset_compare('(b 0)', '(b 64)');
+SELECT test_bms_subset_compare('(b 64)', '(b 1)');
+SELECT test_bms_subset_compare('(b 1 2)', '(b 1 2 64)');
+SELECT test_bms_subset_compare('(b 64 200)', '(b 1 201)');
+SELECT test_bms_subset_compare('(b 1 64 65)', '(b 1 2 64)');
+SELECT test_bms_subset_compare('(b 2 64 128)', '(b 1 65)');
 
 -- bms_copy()
 SELECT test_bms_copy(NULL) AS result;
 SELECT test_bms_copy('(b 1 3 5 7)') AS result;
 
 -- bms_add_members()
-SELECT test_bms_add_member('(b)', 1000); -- error
 SELECT test_bms_add_members('(b 1 3)', '(b 5 7)') AS result;
 SELECT test_bms_add_members('(b 1 3 5)', '(b 2 5 7)') AS result;
 SELECT test_bms_add_members('(b 1 3 5)', '(b 100 200 300)') AS result;
@@ -243,6 +303,9 @@ SELECT test_bms_overlap_list('(b 7 10)', ARRAY[6,7,8,9]) AS result;
 SELECT test_bms_overlap_list('(b 1 5)', ARRAY[6,7,8,9]) AS result;
 -- Empty list
 SELECT test_bms_overlap_list('(b 1)', ARRAY[]::integer[]) AS result;
+-- Overlap list with negative numbers
+SELECT test_bms_overlap_list('(b 5 10)', ARRAY[-1,5]) AS result; -- error
+SELECT test_bms_overlap_list('(b 1 2 3)', ARRAY[-5,-1,0]) AS result; -- error
 
 -- bms_nonempty_difference()
 SELECT test_bms_nonempty_difference(NULL, '(b 1 3 5)') AS result;
@@ -250,8 +313,92 @@ SELECT test_bms_nonempty_difference('(b 1 3 5)', NULL) AS result;
 SELECT test_bms_nonempty_difference('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT test_bms_nonempty_difference('(b 1 3 5)', '(b 1 5)') AS result;
 SELECT test_bms_nonempty_difference('(b 1 3 5)', '(b 1 3 5)') AS result;
+-- Difference with different word counts
+SELECT test_bms_nonempty_difference('(b 5)', '(b 100)') AS result;
+SELECT test_bms_nonempty_difference('(b 100)', '(b 5)') AS result;
+SELECT test_bms_nonempty_difference('(b 1 2)', '(b 50 100)') AS result;
 
 -- random operations
 SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
 
+-- Cover the test API's corner cases such as when ARGISNULL,
+-- or VARSIZE_ANY_EXHDR == 0, etc.
+
+SELECT test_bitmap_hash(NULL) AS result;
+SELECT test_bitmap_match('(b 5)', NULL) AS result;
+SELECT test_bitmap_match(NULL, '(b 5)') AS result;
+SELECT test_bitmap_match(NULL, NULL) AS result;
+SELECT test_bms_add_member('(b)', NULL) AS result;
+SELECT test_bms_add_range('(b 5)', 5, NULL) AS result;
+SELECT test_bms_add_range('(b 5)', NULL, 10) AS result;
+SELECT test_bms_add_range('(b 5)', NULL, NULL) AS result;
+SELECT test_bms_add_range(NULL, 5, 10) AS result;
+SELECT test_bms_add_range(NULL, 10, 5) AS result;
+SELECT test_bms_add_range(NULL, NULL, NULL) AS result;
+SELECT test_bms_compare('(b 5)', NULL) AS result;
+SELECT test_bms_compare(NULL, '(b 5)') AS result;
+SELECT test_bms_compare(NULL, NULL) AS result;
+SELECT test_bms_copy(NULL) AS result;
+SELECT test_bms_del_member('(b 42)', 42) AS result;
+SELECT test_bms_del_member('(b 5)', NULL) AS result;
+SELECT test_bms_del_members('(b 5)', NULL) AS result;
+SELECT test_bms_del_members(NULL, '(b 5)') AS result;
+SELECT test_bms_difference('(b 5)', '(b 5 10)') AS result;
+SELECT test_bms_difference('(b 5)', NULL) AS result;
+SELECT test_bms_difference(NULL, '(b 5)') AS result;
+SELECT test_bms_difference(NULL, NULL) AS result;
+SELECT test_bms_equal('(b 5)', NULL) AS result;
+SELECT test_bms_equal(NULL, '(b 5)') AS result;
+SELECT test_bms_equal(NULL, NULL) AS result;
+SELECT test_bms_get_singleton_member('', 1000) AS result;
+SELECT test_bms_get_singleton_member(NULL, -1) AS result;
+SELECT test_bms_hash_value(NULL) AS result;
+SELECT test_bms_int_members('(b 1)', '(b 2)') AS result;
+SELECT test_bms_int_members('(b 5)', NULL) AS result;
+SELECT test_bms_int_members(NULL, '(b 5)') AS result;
+SELECT test_bms_int_members(NULL, NULL) AS result;
+SELECT test_bms_intersect('(b 1)', '(b 2)') AS result;
+SELECT test_bms_intersect('(b 5)', NULL) AS result;
+SELECT test_bms_intersect(NULL, '(b 5)') AS result;
+SELECT test_bms_intersect(NULL, NULL) AS result;
+SELECT test_bms_is_empty(NULL) AS result;
+SELECT test_bms_is_member('(b 5)', NULL) AS result;
+SELECT test_bms_is_subset('(b 5)', NULL) AS result;
+SELECT test_bms_is_subset(NULL, '(b 5)') AS result;
+SELECT test_bms_is_subset(NULL, NULL) AS result;
+SELECT test_bms_join('(b 5)', NULL) AS result;
+SELECT test_bms_join(NULL, '(b 5)') AS result;
+SELECT test_bms_join(NULL, NULL) AS result;
+SELECT test_bms_make_singleton(NULL) AS result;
+SELECT test_bms_member_index('', 5) AS result;
+SELECT test_bms_member_index(NULL, 5) AS result;
+SELECT test_bms_membership(NULL) AS result;
+SELECT test_bms_next_member('', 5) AS result;
+SELECT test_bms_next_member('(b 5)', NULL) AS result;
+SELECT test_bms_next_member(NULL, 5) AS result;
+SELECT test_bms_next_member(NULL, NULL) AS result;
+SELECT test_bms_nonempty_difference('(b 5)', NULL) AS result;
+SELECT test_bms_nonempty_difference(NULL, '(b 5)') AS result;
+SELECT test_bms_nonempty_difference(NULL, NULL) AS result;
+SELECT test_bms_overlap('(b 5)', NULL) AS result;
+SELECT test_bms_overlap(NULL, '(b 5)') AS result;
+SELECT test_bms_overlap(NULL, NULL) AS result;
+SELECT test_bms_overlap_list('(b 5)', NULL) AS result;
+SELECT test_bms_overlap_list(NULL, ARRAY[1,2,3]) AS result;
+SELECT test_bms_overlap_list(NULL, NULL) AS result;
+SELECT test_bms_prev_member('', 5) AS result;
+SELECT test_bms_prev_member('(b 5)', NULL) AS result;
+SELECT test_bms_prev_member(NULL, 5) AS result;
+SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
+SELECT test_bms_replace_members('(b 5)', NULL) AS result;
+SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
+SELECT test_bms_replace_members(NULL, NULL) AS result;
+SELECT test_bms_singleton_member(NULL) AS result;
+SELECT test_bms_subset_compare('(b 5)', NULL) AS result;
+SELECT test_bms_subset_compare(NULL, '(b 5)') AS result;
+SELECT test_bms_subset_compare(NULL, NULL) AS result;
+SELECT test_bms_union('(b 5)', NULL) AS result;
+SELECT test_bms_union(NULL, '(b 5)') AS result;
+SELECT test_bms_union(NULL, NULL) AS result;
+
 DROP EXTENSION test_bitmapset;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
index 95f5ee02e3f..b95c4d0dda5 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -112,6 +112,10 @@ CREATE FUNCTION test_bms_int_members(text, text)
 RETURNS text
 AS 'MODULE_PATHNAME' LANGUAGE C;
 
+CREATE FUNCTION test_bms_del_members(text, text)
+RETURNS text
+AS 'MODULE_PATHNAME' LANGUAGE C;
+
 CREATE FUNCTION test_bms_replace_members(text, text)
 RETURNS text
 AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 5bc4daa23f1..77b6c70af66 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -58,6 +58,7 @@ PG_FUNCTION_INFO_V1(test_bms_member_index);
 PG_FUNCTION_INFO_V1(test_bms_add_range);
 PG_FUNCTION_INFO_V1(test_bms_add_members);
 PG_FUNCTION_INFO_V1(test_bms_int_members);
+PG_FUNCTION_INFO_V1(test_bms_del_members);
 PG_FUNCTION_INFO_V1(test_bms_replace_members);
 PG_FUNCTION_INFO_V1(test_bms_join);
 PG_FUNCTION_INFO_V1(test_bitmap_hash);
@@ -111,9 +112,6 @@ test_bms_add_member(PG_FUNCTION_ARGS)
 	if (bms)
 		bms_free(bms);
 
-	if (result == NULL)
-		PG_RETURN_NULL();
-
 	PG_RETURN_TEXT_P(result);
 }
 
@@ -136,9 +134,6 @@ test_bms_add_members(PG_FUNCTION_ARGS)
 	if (bms2)
 		bms_free(bms2);
 
-	if (bms1 == NULL)
-		PG_RETURN_NULL();
-
 	result = BITMAPSET_TO_TEXT(bms1);
 	bms_free(bms1);
 
@@ -161,12 +156,8 @@ test_bms_del_member(PG_FUNCTION_ARGS)
 	member = PG_GETARG_INT32(1);
 	bms = bms_del_member(bms, member);
 
-	if (bms == NULL || bms_is_empty(bms))
-	{
-		if (bms)
-			bms_free(bms);
+	if (bms_is_empty(bms))
 		PG_RETURN_NULL();
-	}
 
 	result = BITMAPSET_TO_TEXT(bms);
 	bms_free(bms);
@@ -514,12 +505,10 @@ Datum
 test_bms_get_singleton_member(PG_FUNCTION_ARGS)
 {
 	Bitmapset  *bms = NULL;
-	int32		default_member = PG_GETARG_INT32(1);
-	int			member;
-	bool		success;
+	int			member = - 1;
 
 	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(default_member);
+		PG_RETURN_INT32(member);
 
 	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
@@ -527,13 +516,10 @@ test_bms_get_singleton_member(PG_FUNCTION_ARGS)
 	 * bms_get_singleton_member returns bool and stores result in member
 	 * pointer
 	 */
-	success = bms_get_singleton_member(bms, &member);
+	bms_get_singleton_member(bms, &member);
 	bms_free(bms);
 
-	if (success)
-		PG_RETURN_INT32(member);
-	else
-		PG_RETURN_INT32(default_member);
+	PG_RETURN_INT32(member);
 }
 
 Datum
@@ -609,11 +595,6 @@ test_bms_overlap_list(PG_FUNCTION_ARGS)
 
 	array = PG_GETARG_ARRAYTYPE_P(1);
 
-	if (ARR_ELEMTYPE(array) != INT4OID)
-		ereport(ERROR,
-				(errcode(ERRCODE_DATATYPE_MISMATCH),
-				 errmsg("integer array expected")));
-
 	deconstruct_array(array,
 					  INT4OID, sizeof(int32), true, 'i',
 					  &elem_datums, &elem_nulls, &elem_count);
@@ -752,6 +733,37 @@ test_bms_int_members(PG_FUNCTION_ARGS)
 	PG_RETURN_TEXT_P(result);
 }
 
+Datum
+test_bms_del_members(PG_FUNCTION_ARGS)
+{
+	Bitmapset  *bms1 = NULL,
+			   *bms2 = NULL;
+	Bitmapset  *result_bms;
+	text	   *result;
+
+	if (!PG_ARGISNULL(0))
+		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
+	if (!PG_ARGISNULL(1))
+		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+
+	/* IMPORTANT: bms_del_members modifies/frees the first argument */
+	result_bms = bms_del_members(bms1, bms2);
+
+	/* bms1 is now invalid, do not free it */
+
+	if (bms2)
+		bms_free(bms2);
+
+	if (result_bms == NULL)
+		PG_RETURN_NULL();
+
+	result = BITMAPSET_TO_TEXT(result_bms);
+	bms_free(result_bms);
+
+	PG_RETURN_TEXT_P(result);
+}
+
 Datum
 test_bms_replace_members(PG_FUNCTION_ARGS)
 {
-- 
2.49.0

#39Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#38)
Re: [PATCH] Add tests for Bitmapset

On Sat, Sep 27, 2025 at 10:03:14AM -0400, Greg Burd wrote:

On Sep 24 2025, at 7:28 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Wed, Sep 24, 2025 at 07:39:59AM -0400, Greg Burd wrote:

Thanks Michael, Tom, for the help getting this into shape and in the tree.

By the way, Greg, do you think that we should aim for a state where we
are closer to completion?

Hi Michael,

We've come this far, why not go all the way? :)

We have the module up to the point where we
are in pretty good shape, with most things and the infrastructure done
but it can be improved a bit more, as well.

Agreed.

Based on the information provided by the coverage report at
https://coverage.postgresql.org/src/backend/nodes/bitmapset.c.gcov.html,
we still have the following things:
- bms_equal for different word counts
- bms_union, bms_nonempty_difference, bms_is_subset and bms_intersect
with shorter word counts.
- bms_different with different word counts
- A couple more cases with bms_subset_compare
- bms_member_index and word counts
- bms_overlap_list with negative number in input list.
- bms_singleton_member ERROR with empty input.
- bms_get_singleton_member with NULL input
- bms_del_member with word counts
- bms_replace_members and repalloc case
- bms_add_range, bms_join and bms_del_members, more word count cases
- bms_prev_member and the prevbit business

Thanks for the detailed analysis, I tried to address each of these in
the patch.

There is not much we can do with the random function, still we could
do something about the NULL paths in the internal functions:
https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html

Agreed.

The coverage of the latter matters less than the coverage of the
former, of course.

Agreed.
test_bitmapset.c
lines......: 98.9%
functions..: 100%
branches...: 82.6%

Here I removed a bit of code I thought was unnecessary and added a few
test cases. The coverage is better overall, not much to say about it.

bitmapset.c
lines......: 99.8%
functions..: 100%
branches...: 89.4%

No need for three tests for the word count case in bms_del_member(),
only one is enough, but I've let them as they you have proposed, as
you wanted to check more positioning with the members. These are
cheap, that's fine.

Added a comment for bms_del_members() for the two cases that trigger
word count changes.

The test changed with test_bms_difference() is indeed long, but not
that bad with 140-ish characters, so left it as-is.

Good catch with bms_del_members() that was missing. There are so many
APIs that it's easy to miss one.

The changes in test_bms_get_singleton_member() don't seem adapted,
because we also want to test if the default value given by the
function caller is changed, bms_get_singleton_member() returning a
boolean status. The patch did not use arg1 at all. Also, if arg0 is
NULL, let's return the input value.

A few branches were really tricky, my (least) favorite was the
bms_subset_compare(). To get to the first BMS_DIFFERENT return you have
to have a test case where the shorter bitmap is long enough to force two
or more iterations of the loop and in the first iteration the first word
in a needs to be a subset of b and then for the second word the opposite
where the second word of b is a subset of a and yet there can be no
overlapping bits in the two sets and the same number of words in both sets.

test_bms_subset_compare('(b 1 64 65)', '(b 1 2 64)') -> BMS_DIFFERENT

Technically the '(b 64 200)', '(b 1 201)' test case is also
BMS_DIFFERENT and so redundant, but I was so happy to find the test case
for this branch I kept them both.

I can see that you have expanded on these quite a bit, impressive.
One thing that was confusing is that some of the tests already
existed, so I've slightly reworded things to reduce the diffs. Per my
measurements, we are at more than 99% in the module and bitmapset.c
when only running make check in the module, which is nice
--
Michael

#40Greg Burd
greg@burd.me
In reply to: Michael Paquier (#39)
Re: [PATCH] Add tests for Bitmapset

On Sep 29 2025, at 2:20 am, Michael Paquier <michael@paquier.xyz> wrote:

On Sat, Sep 27, 2025 at 10:03:14AM -0400, Greg Burd wrote:

On Sep 24 2025, at 7:28 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Wed, Sep 24, 2025 at 07:39:59AM -0400, Greg Burd wrote:

Thanks Michael, Tom, for the help getting this into shape and in

the tree.

By the way, Greg, do you think that we should aim for a state where we
are closer to completion?

Hi Michael,

We've come this far, why not go all the way? :)

We have the module up to the point where we
are in pretty good shape, with most things and the infrastructure done
but it can be improved a bit more, as well.

Agreed.

Based on the information provided by the coverage report at
https://coverage.postgresql.org/src/backend/nodes/bitmapset.c.gcov.html,
we still have the following things:
- bms_equal for different word counts
- bms_union, bms_nonempty_difference, bms_is_subset and bms_intersect
with shorter word counts.
- bms_different with different word counts
- A couple more cases with bms_subset_compare
- bms_member_index and word counts
- bms_overlap_list with negative number in input list.
- bms_singleton_member ERROR with empty input.
- bms_get_singleton_member with NULL input
- bms_del_member with word counts
- bms_replace_members and repalloc case
- bms_add_range, bms_join and bms_del_members, more word count cases
- bms_prev_member and the prevbit business

Thanks for the detailed analysis, I tried to address each of these in
the patch.

There is not much we can do with the random function, still we could
do something about the NULL paths in the internal functions:
https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html

Agreed.

The coverage of the latter matters less than the coverage of the
former, of course.

Agreed.
test_bitmapset.c
lines......: 98.9%
functions..: 100%
branches...: 82.6%

Here I removed a bit of code I thought was unnecessary and added a few
test cases. The coverage is better overall, not much to say about it.

bitmapset.c
lines......: 99.8%
functions..: 100%
branches...: 89.4%

Hello Michael,

No need for three tests for the word count case in bms_del_member(),
only one is enough, but I've let them as they you have proposed, as
you wanted to check more positioning with the members. These are
cheap, that's fine.

Yes, redundant. Thanks for leaving them.

Added a comment for bms_del_members() for the two cases that trigger
word count changes.

Thanks, I considered adding comments to cases that were more subtle but
didn't find the time to review/add them. I appreciate that you added that.

The test changed with test_bms_difference() is indeed long, but not
that bad with 140-ish characters, so left it as-is.

Thanks.

Good catch with bms_del_members() that was missing. There are so many
APIs that it's easy to miss one.

Indeed, but it's covered now.

The changes in test_bms_get_singleton_member() don't seem adapted,
because we also want to test if the default value given by the
function caller is changed, bms_get_singleton_member() returning a
boolean status. The patch did not use arg1 at all. Also, if arg0 is
NULL, let's return the input value.

Doh, I see what you mean. Thanks for the adaptation.

A few branches were really tricky, my (least) favorite was the
bms_subset_compare(). To get to the first BMS_DIFFERENT return you have
to have a test case where the shorter bitmap is long enough to force two
or more iterations of the loop and in the first iteration the first word
in a needs to be a subset of b and then for the second word the opposite
where the second word of b is a subset of a and yet there can be no
overlapping bits in the two sets and the same number of words in both sets.

test_bms_subset_compare('(b 1 64 65)', '(b 1 2 64)') -> BMS_DIFFERENT

Technically the '(b 64 200)', '(b 1 201)' test case is also
BMS_DIFFERENT and so redundant, but I was so happy to find the test case
for this branch I kept them both.

I can see that you have expanded on these quite a bit, impressive.
One thing that was confusing is that some of the tests already
existed, so I've slightly reworded things to reduce the diffs.

Excellent, thanks.

Per my
measurements, we are at more than 99% in the module and bitmapset.c
when only running make check in the module, which is nice

Yes, I think that does it. Thanks so much for the guidance and help
taking this to its logical end. I greatly appreciate your guidance and time.

--
Michael

best.

-greg

#41Michael Paquier
michael@paquier.xyz
In reply to: Greg Burd (#40)
Re: [PATCH] Add tests for Bitmapset

On Mon, Sep 29, 2025 at 06:27:01AM -0400, Greg Burd wrote:

Yes, I think that does it. Thanks so much for the guidance and help
taking this to its logical end. I greatly appreciate your guidance and time.

The latest coverage report confirms 100% for bitmapset.c

The only two code paths I'm seeing as not covered are:
- test_bms_add_range() for a bms_free() case.
- test_bms_make_singleton() on NULL input, because the function is
created as strict:
=# select proisstrict from pg_proc
where proname = 'test_bms_make_singleton';
proisstrict
-------------
t
(1 row)

I'm not planning to bother about these, so we are good here.
--
Michael

#42David Rowley
dgrowleyml@gmail.com
In reply to: Michael Paquier (#41)
Re: [PATCH] Add tests for Bitmapset

On Tue, 30 Sept 2025 at 12:40, Michael Paquier <michael@paquier.xyz> wrote:

The only two code paths I'm seeing as not covered are:
- test_bms_add_range() for a bms_free() case.

One question about that: In cases like [1]https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html#699, what's the reason that
many of the bms_free() calls check if the set is NULL before calling
the function?

NULL is a valid Bitmapset, so I don't really see the need to check for
an empty set before calling bms_free(). If those were removed, then
you'd not have to care about the coverage of that line.

David

[1]: https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html#699

#43Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#42)
Re: [PATCH] Add tests for Bitmapset

On Tue, Sep 30, 2025 at 01:19:05PM +1300, David Rowley wrote:

NULL is a valid Bitmapset, so I don't really see the need to check for
an empty set before calling bms_free(). If those were removed, then
you'd not have to care about the coverage of that line.

Yeah, we could just remove them as you are suggesting, as well.
--
Michael

#44Greg Burd
greg@burd.me
In reply to: Michael Paquier (#43)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 29 2025, at 8:51 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Tue, Sep 30, 2025 at 01:19:05PM +1300, David Rowley wrote:

NULL is a valid Bitmapset, so I don't really see the need to check for
an empty set before calling bms_free(). If those were removed, then
you'd not have to care about the coverage of that line.

Good point, I agree. Thanks for reporting/reviewing David.

Yeah, we could just remove them as you are suggesting, as well.
--
Michael

Thank you both, patch attached.

best.

-greg

Attachments:

v1-0001-Don-t-check-for-NULL-before-calling-bms_free-in-t.patchapplication/octet-streamDownload
From 8c8fc8c7dc1e0c7752c35a33044f107540f94e61 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Tue, 30 Sep 2025 05:15:40 -0400
Subject: [PATCH v1] Don't check for NULL before calling bms_free() in tests

The bms_free() function safely handles NULL input, so checking for NULL
before calling it is unnecessary. Since tests serve as reference examples
for proper API usage, they should demonstrate the correct calling pattern
without redundant NULL checks.

Author: Greg Burd <greg@burd.me>
Reported-by: David Rowley<dgrowleyml@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/7BD1ABDB-B03A-464A-9BA9-A73B55AD8A1F@getmailspring.com
---
 .../modules/test_bitmapset/test_bitmapset.c   | 121 ++++++------------
 1 file changed, 40 insertions(+), 81 deletions(-)

diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 2e821320836..7a706662e9f 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -109,8 +109,7 @@ test_bms_add_member(PG_FUNCTION_ARGS)
 	bms = bms_add_member(bms, member);
 	result = BITMAPSET_TO_TEXT(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -131,8 +130,7 @@ test_bms_add_members(PG_FUNCTION_ARGS)
 	/* IMPORTANT: bms_add_members modifies/frees the first argument */
 	bms1 = bms_add_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(bms1);
 	bms_free(bms1);
@@ -181,8 +179,7 @@ test_bms_is_member(PG_FUNCTION_ARGS)
 	member = PG_GETARG_INT32(1);
 	result = bms_is_member(member, bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_BOOL(result);
 }
@@ -198,8 +195,7 @@ test_bms_num_members(PG_FUNCTION_ARGS)
 
 	result = bms_num_members(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -239,10 +235,8 @@ test_bms_copy(PG_FUNCTION_ARGS)
 	copy_bms = bms_copy(bms);
 	result = BITMAPSET_TO_TEXT(copy_bms);
 
-	if (bms)
-		bms_free(bms);
-	if (copy_bms)
-		bms_free(copy_bms);
+	bms_free(bms);
+	bms_free(copy_bms);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -262,10 +256,8 @@ test_bms_equal(PG_FUNCTION_ARGS)
 
 	result = bms_equal(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -286,10 +278,8 @@ test_bms_union(PG_FUNCTION_ARGS)
 
 	result_bms = bms_union(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	if (result_bms == NULL)
 		PG_RETURN_NULL();
@@ -312,8 +302,7 @@ test_bms_membership(PG_FUNCTION_ARGS)
 	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 	result = bms_membership(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32((int32) result);
 }
@@ -332,8 +321,7 @@ test_bms_next_member(PG_FUNCTION_ARGS)
 	prevmember = PG_GETARG_INT32(1);
 	result = bms_next_member(bms, prevmember);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -354,10 +342,8 @@ test_bms_intersect(PG_FUNCTION_ARGS)
 
 	result_bms = bms_intersect(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	if (result_bms == NULL)
 		PG_RETURN_NULL();
@@ -384,10 +370,8 @@ test_bms_difference(PG_FUNCTION_ARGS)
 
 	result_bms = bms_difference(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	if (result_bms == NULL)
 		PG_RETURN_NULL();
@@ -413,10 +397,8 @@ test_bms_compare(PG_FUNCTION_ARGS)
 
 	result = bms_compare(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32(result);
 }
@@ -432,8 +414,7 @@ test_bms_is_empty(PG_FUNCTION_ARGS)
 
 	result = bms_is_empty(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_BOOL(result);
 }
@@ -453,10 +434,8 @@ test_bms_is_subset(PG_FUNCTION_ARGS)
 
 	result = bms_is_subset(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -476,10 +455,8 @@ test_bms_subset_compare(PG_FUNCTION_ARGS)
 
 	result = bms_subset_compare(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32((int32) result);
 }
@@ -495,8 +472,7 @@ test_bms_singleton_member(PG_FUNCTION_ARGS)
 
 	result = bms_singleton_member(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -566,10 +542,8 @@ test_bms_overlap(PG_FUNCTION_ARGS)
 
 	result = bms_overlap(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -593,8 +567,7 @@ test_bms_overlap_list(PG_FUNCTION_ARGS)
 
 	if (PG_ARGISNULL(1))
 	{
-		if (bms)
-			bms_free(bms);
+		bms_free(bms);
 		PG_RETURN_BOOL(false);
 	}
 
@@ -616,8 +589,7 @@ test_bms_overlap_list(PG_FUNCTION_ARGS)
 
 	result = bms_overlap_list(bms, int_list);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	list_free(int_list);
 
@@ -642,10 +614,8 @@ test_bms_nonempty_difference(PG_FUNCTION_ARGS)
 
 	result = bms_nonempty_difference(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -695,16 +665,14 @@ test_bms_add_range(PG_FUNCTION_ARGS)
 	/* Check for invalid range */
 	if (upper < lower)
 	{
-		if (bms)
-			bms_free(bms);
+		bms_free(bms);
 		PG_RETURN_NULL();
 	}
 
 	bms = bms_add_range(bms, lower, upper);
 
 	result = BITMAPSET_TO_TEXT(bms);
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -724,16 +692,14 @@ test_bms_int_members(PG_FUNCTION_ARGS)
 
 	bms1 = bms_int_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms2);
 
 	if (bms1 == NULL)
 		PG_RETURN_NULL();
 
 	result = BITMAPSET_TO_TEXT(bms1);
 
-	if (bms1)
-		bms_free(bms1);
+	bms_free(bms1);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -757,8 +723,7 @@ test_bms_del_members(PG_FUNCTION_ARGS)
 
 	/* bms1 is now invalid, do not free it */
 
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms2);
 
 	if (result_bms == NULL)
 		PG_RETURN_NULL();
@@ -788,8 +753,7 @@ test_bms_replace_members(PG_FUNCTION_ARGS)
 
 	/* bms1 is now invalid, do not free it */
 
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms2);
 
 	if (result_bms == NULL)
 		PG_RETURN_NULL();
@@ -839,8 +803,7 @@ test_bms_hash_value(PG_FUNCTION_ARGS)
 
 	hash_result = bms_hash_value(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(hash_result);
 }
@@ -889,11 +852,8 @@ test_bitmap_match(PG_FUNCTION_ARGS)
 	/* Call bitmap_match with addresses of the Bitmapset pointers */
 	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
 
-	/* Clean up */
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32(match_result);
 }
@@ -1031,8 +991,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 		total_ops++;
 	}
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(total_ops);
 }
-- 
2.49.0

#45David Rowley
dgrowleyml@gmail.com
In reply to: Greg Burd (#44)
Re: [PATCH] Add tests for Bitmapset

On Tue, 30 Sept 2025 at 22:30, Greg Burd <greg@burd.me> wrote:

Thank you both, patch attached.

Patch looks good to me.

Just while reviewing, I was confused at the following code in
test_bms_add_range().

/* Check for invalid range */
if (upper < lower)
{
bms_free(bms);
PG_RETURN_NULL();
}

That seems wrong. You should just return the input set in that case, not NULL.

This results in:

postgres=# select test_bms_add_range('(b 1)', 2, 5); -- ok.
test_bms_add_range
--------------------
(b 1 2 3 4 5)
(1 row)

postgres=# select test_bms_add_range('(b 1)', 5, 2); -- wrong results
test_bms_add_range
--------------------

(1 row)

I'd expect the last one to return '(b 1)', effectively the input set unmodified.

If I remove the code quoted above, I also see something else unexpected:

postgres=# select test_bms_add_range('(b)', 5, 2);
test_bms_add_range
--------------------
<>
(1 row)

Now, you might blame me for that as I see you've done things like:

if (bms_is_empty(bms))
PG_RETURN_NULL();

in other places, but it's not very consistent as I can get the <> in
other locations:

postgres=# select test_bms_add_members('(b)', '(b)');
test_bms_add_members
----------------------
<>
(1 row)

It seems to me that you could save some code and all this
inconsistency by just making <> the standard way to represent an empty
Bitmapset. Or if you really want to keep the SQL NULLs, you could make
a helper macro that handles that consistently.

For me, I think stripping as much logic out of the test functions as
possible is a good way of doing things. I expect you really want to
witness the behaviour of bitmapset.c, not some anomaly of
test_bitmapset.c.

David

#46Greg Burd
greg@burd.me
In reply to: David Rowley (#45)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Sep 30 2025, at 6:29 am, David Rowley <dgrowleyml@gmail.com> wrote:

On Tue, 30 Sept 2025 at 22:30, Greg Burd <greg@burd.me> wrote:

Thank you both, patch attached.

Patch looks good to me.

Just while reviewing, I was confused at the following code in
test_bms_add_range().

/* Check for invalid range */
if (upper < lower)
{
bms_free(bms);
PG_RETURN_NULL();
}

That seems wrong. You should just return the input set in that case,
not NULL.

Agreed, I should have caught this inconsistency earlier on.

This results in:

postgres=# select test_bms_add_range('(b 1)', 2, 5); -- ok.
test_bms_add_range
--------------------
(b 1 2 3 4 5)
(1 row)

postgres=# select test_bms_add_range('(b 1)', 5, 2); -- wrong results
test_bms_add_range
--------------------

(1 row)

I'd expect the last one to return '(b 1)', effectively the input set unmodified.

If I remove the code quoted above, I also see something else unexpected:

postgres=# select test_bms_add_range('(b)', 5, 2);
test_bms_add_range
--------------------
<>
(1 row)

Now, you might blame me for that as I see you've done things like:

if (bms_is_empty(bms))
PG_RETURN_NULL();

in other places, but it's not very consistent as I can get the <> in
other locations:

postgres=# select test_bms_add_members('(b)', '(b)');
test_bms_add_members
----------------------
<>
(1 row)

It seems to me that you could save some code and all this
inconsistency by just making <> the standard way to represent an empty
Bitmapset. Or if you really want to keep the SQL NULLs, you could make
a helper macro that handles that consistently.

nodeToString() will turn NULL into '<>' because it has no way to know
that we're referring to a NULL/empty Bitmapset, but that's not what we'd
ideally like to return in those cases because NULL Bitmapsets are in
fact a thing. The standard/consistent representation for a NULL
Bitmapset encoded by nodeToString() is '(b)' so I'll update to be more
consistent across tests.

For me, I think stripping as much logic out of the test functions as
possible is a good way of doing things. I expect you really want to
witness the behaviour of bitmapset.c, not some anomaly of
test_bitmapset.c.

You are 100% correct, I've stripped away as much as possible so as to
push the responsibility for results down to the bitmapset.c code as it
should be.

David

v2 attached.

best.

-greg

Attachments:

v2-0001-Remove-NULL-check-and-other-defensive-code-in-Bit.patchapplication/octet-streamDownload
From 8199c3e0205a7eb956061be86b472a86ed266ad8 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Tue, 30 Sep 2025 05:15:40 -0400
Subject: [PATCH v2] Remove NULL check and other defensive code in Bitmapset
 tests

Some tests overshadowed their callee's responsiblity to check arguments
and be defensive or return default values, this is unnecessary and can
hide changes in the underlying code.  In addition, the bms_free()
function safely handles NULL input, so checking for NULL before calling
it is unnecessary and again hides an important aspect of the API. Since
tests serve as reference examples for proper API usage, they should
demonstrate the correct calling patterns and not duplicate error
checking in the functions they expose for testing purposes.

Author: Greg Burd <greg@burd.me>
Reported-by: David Rowley<dgrowleyml@gmail.com>
Reviewed-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/7BD1ABDB-B03A-464A-9BA9-A73B55AD8A1F@getmailspring.com
---
 .../expected/test_bitmapset.out               |  78 ++---
 .../modules/test_bitmapset/test_bitmapset.c   | 285 ++++++------------
 2 files changed, 139 insertions(+), 224 deletions(-)

diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
index be7b6399c82..2e204d687df 100644
--- a/src/test/modules/test_bitmapset/expected/test_bitmapset.out
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -63,7 +63,7 @@ SELECT test_bms_add_member('(b 10)', 10) AS result;
 SELECT test_bms_add_member('(b)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_replace_members()
@@ -76,7 +76,7 @@ SELECT test_bms_replace_members(NULL, '(b 1 2 3)') AS result;
 SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_replace_members('(b 1 2 3)', '(b 3 5 6)') AS result;
@@ -108,13 +108,13 @@ SELECT test_bms_replace_members('(b 1 2 3 4 5)', '(b 500 600)') AS result;
 SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_replace_members('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
@@ -126,7 +126,7 @@ SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
 SELECT test_bms_replace_members(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_del_member()
@@ -135,13 +135,13 @@ ERROR:  negative bitmapset member not allowed
 SELECT test_bms_del_member('(b)', 10) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_member('(b 10)', 10) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_member('(b 10)', 5) AS result;
@@ -193,26 +193,26 @@ SELECT test_bms_del_member('(b 1 50 100 200)', 100) AS result;
 SELECT test_bms_del_member('(b 42)', 42) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_member('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 -- bms_del_members()
 SELECT test_bms_del_members('(b)', '(b 10)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_members('(b 10)', '(b 10)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_members('(b 10)', '(b 5)') AS result;
@@ -262,7 +262,7 @@ SELECT test_bms_del_members('(b 5)', NULL) AS result;
 SELECT test_bms_del_members(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_join()
@@ -319,7 +319,7 @@ SELECT test_bms_join(NULL, '(b 5)') AS result;
 SELECT test_bms_join(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_union()
@@ -341,7 +341,7 @@ SELECT test_bms_union('(b 1 3 5)', '(b)') AS result;
 SELECT test_bms_union('(b)', '(b)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Overlapping ranges
@@ -383,7 +383,7 @@ SELECT test_bms_union(NULL, '(b 5)') AS result;
 SELECT test_bms_union(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_intersect()
@@ -398,14 +398,14 @@ SELECT test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Intersect with empty
 SELECT test_bms_intersect('(b 1 3 5)', '(b)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Intersect with varrying word counts
@@ -425,25 +425,25 @@ SELECT test_bms_intersect('(b 1 2 3 4 5)', '(b 1 300)') AS result;
 SELECT test_bms_intersect('(b 1)', '(b 2)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_intersect('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_intersect(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_intersect(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_int_members()
@@ -458,14 +458,14 @@ SELECT test_bms_int_members('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Intersect with empty
 SELECT test_bms_int_members('(b 1 3 5)', '(b)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Multiple members
@@ -479,25 +479,25 @@ SELECT test_bms_int_members('(b 0 31 32 63 64)', '(b 31 32 64 65)') AS result;
 SELECT test_bms_int_members('(b 1)', '(b 2)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_int_members('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_int_members(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_int_members(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_difference()
@@ -519,14 +519,14 @@ SELECT test_bms_difference('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT test_bms_difference('(b 1 3 5)', '(b 1 3 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Substraction to empty
 SELECT test_bms_difference('(b 42)', '(b 42)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Subtraction edge case
@@ -556,7 +556,7 @@ SELECT test_bms_difference('(b 1 2 100 200)', '(b 1 2)') AS result;
 SELECT test_bms_difference('(b 5)', '(b 5 10)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_difference('(b 5)', NULL) AS result;
@@ -568,13 +568,13 @@ SELECT test_bms_difference('(b 5)', NULL) AS result;
 SELECT test_bms_difference(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_difference(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_is_member()
@@ -887,19 +887,19 @@ SELECT length(test_bms_add_range('(b 1 2)', 200, 250)) AS result;
 SELECT test_bms_add_range('(b 5)', 5, NULL) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 SELECT test_bms_add_range('(b 5)', NULL, 10) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 SELECT test_bms_add_range('(b 5)', NULL, NULL) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 SELECT test_bms_add_range(NULL, 5, 10) AS result;
@@ -911,13 +911,13 @@ SELECT test_bms_add_range(NULL, 5, 10) AS result;
 SELECT test_bms_add_range(NULL, 10, 5) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_add_range(NULL, NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_membership()
@@ -1421,7 +1421,7 @@ SELECT test_bms_subset_compare(NULL, NULL) AS result;
 SELECT test_bms_copy(NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_copy('(b 1 3 5 7)') AS result;
@@ -1434,7 +1434,7 @@ SELECT test_bms_copy('(b 1 3 5 7)') AS result;
 SELECT test_bms_copy(NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_add_members()
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 2e821320836..93d83105c2d 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -26,7 +26,6 @@
 #include "nodes/pg_list.h"
 #include "utils/builtins.h"
 #include "utils/timestamp.h"
-#include "varatt.h"
 
 PG_MODULE_MAGIC;
 
@@ -84,8 +83,10 @@ PG_FUNCTION_INFO_V1(test_random_operations);
 				 #expr, __FILE__, __LINE__); \
 	} while (0)
 
+static const char *empty = "(b)";
+
 /* Encode/Decode to/from TEXT and Bitmapset */
-#define BITMAPSET_TO_TEXT(bms) cstring_to_text(nodeToString(bms))
+#define BITMAPSET_TO_TEXT(bms) cstring_to_text(bms ? nodeToString(bms) : empty)
 #define TEXT_TO_BITMAPSET(str) ((Bitmapset *) stringToNode(text_to_cstring(str)))
 
 /*
@@ -100,7 +101,7 @@ test_bms_add_member(PG_FUNCTION_ARGS)
 	text	   *result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_NULL();
+		PG_RETURN_TEXT_P(PG_GETARG_TEXT_PP(0));
 
 	if (!PG_ARGISNULL(0))
 		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
@@ -109,8 +110,7 @@ test_bms_add_member(PG_FUNCTION_ARGS)
 	bms = bms_add_member(bms, member);
 	result = BITMAPSET_TO_TEXT(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -131,8 +131,7 @@ test_bms_add_members(PG_FUNCTION_ARGS)
 	/* IMPORTANT: bms_add_members modifies/frees the first argument */
 	bms1 = bms_add_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(bms1);
 	bms_free(bms1);
@@ -148,7 +147,7 @@ test_bms_del_member(PG_FUNCTION_ARGS)
 	text	   *result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_NULL();
+		PG_RETURN_TEXT_P(PG_GETARG_TEXT_PP(0));
 
 	if (!PG_ARGISNULL(0))
 		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
@@ -156,9 +155,6 @@ test_bms_del_member(PG_FUNCTION_ARGS)
 	member = PG_GETARG_INT32(1);
 	bms = bms_del_member(bms, member);
 
-	if (bms_is_empty(bms))
-		PG_RETURN_NULL();
-
 	result = BITMAPSET_TO_TEXT(bms);
 	bms_free(bms);
 
@@ -181,8 +177,7 @@ test_bms_is_member(PG_FUNCTION_ARGS)
 	member = PG_GETARG_INT32(1);
 	result = bms_is_member(member, bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_BOOL(result);
 }
@@ -198,8 +193,7 @@ test_bms_num_members(PG_FUNCTION_ARGS)
 
 	result = bms_num_members(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -212,7 +206,7 @@ test_bms_make_singleton(PG_FUNCTION_ARGS)
 	text	   *result;
 
 	if (PG_ARGISNULL(0))
-		PG_RETURN_NULL();
+		PG_RETURN_TEXT_P(BITMAPSET_TO_TEXT(NULL));
 
 	member = PG_GETARG_INT32(0);
 	bms = bms_make_singleton(member);
@@ -226,23 +220,18 @@ test_bms_make_singleton(PG_FUNCTION_ARGS)
 Datum
 test_bms_copy(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
 	Bitmapset  *bms = NULL;
 	Bitmapset  *copy_bms;
 	text	   *result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_NULL();
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
-	bms_data = PG_GETARG_TEXT_PP(0);
-	bms = TEXT_TO_BITMAPSET(bms_data);
 	copy_bms = bms_copy(bms);
 	result = BITMAPSET_TO_TEXT(copy_bms);
 
-	if (bms)
-		bms_free(bms);
-	if (copy_bms)
-		bms_free(copy_bms);
+	bms_free(bms);
+	bms_free(copy_bms);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -262,10 +251,8 @@ test_bms_equal(PG_FUNCTION_ARGS)
 
 	result = bms_equal(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -286,13 +273,8 @@ test_bms_union(PG_FUNCTION_ARGS)
 
 	result_bms = bms_union(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
+	bms_free(bms1);
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(result_bms);
 	bms_free(result_bms);
@@ -306,14 +288,12 @@ test_bms_membership(PG_FUNCTION_ARGS)
 	Bitmapset  *bms = NULL;
 	BMS_Membership result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(BMS_EMPTY_SET);
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 	result = bms_membership(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32((int32) result);
 }
@@ -325,15 +305,17 @@ test_bms_next_member(PG_FUNCTION_ARGS)
 	int32		prevmember;
 	int			result;
 
-	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
+	if (PG_ARGISNULL(1))
 		PG_RETURN_INT32(-2);
 
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 	prevmember = PG_GETARG_INT32(1);
+
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+
 	result = bms_next_member(bms, prevmember);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -354,13 +336,8 @@ test_bms_intersect(PG_FUNCTION_ARGS)
 
 	result_bms = bms_intersect(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
+	bms_free(bms1);
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(result_bms);
 	bms_free(result_bms);
@@ -384,13 +361,8 @@ test_bms_difference(PG_FUNCTION_ARGS)
 
 	result_bms = bms_difference(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
+	bms_free(bms1);
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(result_bms);
 	bms_free(result_bms);
@@ -413,10 +385,8 @@ test_bms_compare(PG_FUNCTION_ARGS)
 
 	result = bms_compare(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32(result);
 }
@@ -432,8 +402,7 @@ test_bms_is_empty(PG_FUNCTION_ARGS)
 
 	result = bms_is_empty(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_BOOL(result);
 }
@@ -453,10 +422,8 @@ test_bms_is_subset(PG_FUNCTION_ARGS)
 
 	result = bms_is_subset(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -476,10 +443,8 @@ test_bms_subset_compare(PG_FUNCTION_ARGS)
 
 	result = bms_subset_compare(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32((int32) result);
 }
@@ -495,8 +460,7 @@ test_bms_singleton_member(PG_FUNCTION_ARGS)
 
 	result = bms_singleton_member(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -505,46 +469,38 @@ Datum
 test_bms_get_singleton_member(PG_FUNCTION_ARGS)
 {
 	Bitmapset  *bms = NULL;
-	int32		default_member = PG_GETARG_INT32(1);
-	bool		success;
 	int			member = -1;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(default_member);
+	if (!PG_ARGISNULL(1))
+		member = PG_GETARG_INT32(1);
 
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
 	/*
 	 * bms_get_singleton_member returns bool and stores result in member
-	 * pointer
+	 * pointer, we don't change the value of member when supplied so we ignore
+	 * the return value.
 	 */
-	success = bms_get_singleton_member(bms, &member);
+	(void) bms_get_singleton_member(bms, &member);
 	bms_free(bms);
 
-	if (success)
-		PG_RETURN_INT32(member);
-
-	PG_RETURN_INT32(default_member);
+	PG_RETURN_INT32(member);
 }
 
 Datum
 test_bms_prev_member(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
 	Bitmapset  *bms = NULL;
-	int32		prevmember;
+	int32		prevmember = 0;
 	int			result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(-2);
-
-	bms_data = PG_GETARG_TEXT_PP(0);
-	prevmember = PG_GETARG_INT32(1);
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
-	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
-		PG_RETURN_INT32(-2);
+	if (!PG_ARGISNULL(1))
+		prevmember = PG_GETARG_INT32(1);
 
-	bms = TEXT_TO_BITMAPSET(bms_data);
 	result = bms_prev_member(bms, prevmember);
 	bms_free(bms);
 
@@ -566,10 +522,8 @@ test_bms_overlap(PG_FUNCTION_ARGS)
 
 	result = bms_overlap(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -581,48 +535,44 @@ test_bms_overlap_list(PG_FUNCTION_ARGS)
 	ArrayType  *array;
 	List	   *int_list = NIL;
 	bool		result;
-	Datum	   *elem_datums;
-	bool	   *elem_nulls;
+	Datum	   *elem_datums = NULL;
+	bool	   *elem_nulls = NULL;
 	int			elem_count;
 	int			i;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_BOOL(false);
-
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
-	if (PG_ARGISNULL(1))
+	if (!PG_ARGISNULL(1))
 	{
-		if (bms)
-			bms_free(bms);
-		PG_RETURN_BOOL(false);
-	}
-
-	array = PG_GETARG_ARRAYTYPE_P(1);
+		array = PG_GETARG_ARRAYTYPE_P(1);
 
-	deconstruct_array(array,
-					  INT4OID, sizeof(int32), true, 'i',
-					  &elem_datums, &elem_nulls, &elem_count);
+		deconstruct_array(array,
+						  INT4OID, sizeof(int32), true, 'i',
+						  &elem_datums, &elem_nulls, &elem_count);
 
-	for (i = 0; i < elem_count; i++)
-	{
-		if (!elem_nulls[i])
+		for (i = 0; i < elem_count; i++)
 		{
-			int32		member = DatumGetInt32(elem_datums[i]);
+			if (!elem_nulls[i])
+			{
+				int32		member = DatumGetInt32(elem_datums[i]);
 
-			int_list = lappend_int(int_list, member);
+				int_list = lappend_int(int_list, member);
+			}
 		}
 	}
 
 	result = bms_overlap_list(bms, int_list);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	list_free(int_list);
 
-	pfree(elem_datums);
-	pfree(elem_nulls);
+	if (elem_datums)
+		pfree(elem_datums);
+
+	if (elem_nulls)
+		pfree(elem_nulls);
 
 	PG_RETURN_BOOL(result);
 }
@@ -642,10 +592,8 @@ test_bms_nonempty_difference(PG_FUNCTION_ARGS)
 
 	result = bms_nonempty_difference(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -653,21 +601,15 @@ test_bms_nonempty_difference(PG_FUNCTION_ARGS)
 Datum
 test_bms_member_index(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
 	Bitmapset  *bms = NULL;
-	int32		member;
+	int32		member = -1;
 	int			result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(-1);
-
-	bms_data = PG_GETARG_TEXT_PP(0);
-	member = PG_GETARG_INT32(1);
-
-	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
-		PG_RETURN_INT32(-1);
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
-	bms = TEXT_TO_BITMAPSET(bms_data);
+	if (!PG_ARGISNULL(1))
+		member = PG_GETARG_INT32(1);
 
 	result = bms_member_index(bms, member);
 	bms_free(bms);
@@ -683,28 +625,22 @@ test_bms_add_range(PG_FUNCTION_ARGS)
 				upper;
 	text	   *result;
 
-	if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
-		PG_RETURN_NULL();
+	lower = upper = 0;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	if (!PG_ARGISNULL(1))
+		lower = PG_GETARG_INT32(1);
 
-	lower = PG_GETARG_INT32(1);
-	upper = PG_GETARG_INT32(2);
+	if (!PG_ARGISNULL(2))
+		upper = PG_GETARG_INT32(2);
 
-	/* Check for invalid range */
-	if (upper < lower)
-	{
-		if (bms)
-			bms_free(bms);
-		PG_RETURN_NULL();
-	}
+	if (!PG_ARGISNULL(0))
+		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
-	bms = bms_add_range(bms, lower, upper);
+	if (!(PG_ARGISNULL(1) || PG_ARGISNULL(2)))
+		bms = bms_add_range(bms, lower, upper);
 
 	result = BITMAPSET_TO_TEXT(bms);
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -724,16 +660,11 @@ test_bms_int_members(PG_FUNCTION_ARGS)
 
 	bms1 = bms_int_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
-
-	if (bms1 == NULL)
-		PG_RETURN_NULL();
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(bms1);
 
-	if (bms1)
-		bms_free(bms1);
+	bms_free(bms1);
 
 	PG_RETURN_TEXT_P(result);
 }
@@ -757,11 +688,7 @@ test_bms_del_members(PG_FUNCTION_ARGS)
 
 	/* bms1 is now invalid, do not free it */
 
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(result_bms);
 	bms_free(result_bms);
@@ -788,11 +715,7 @@ test_bms_replace_members(PG_FUNCTION_ARGS)
 
 	/* bms1 is now invalid, do not free it */
 
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
+	bms_free(bms2);
 
 	result = BITMAPSET_TO_TEXT(result_bms);
 	bms_free(result_bms);
@@ -819,9 +742,6 @@ test_bms_join(PG_FUNCTION_ARGS)
 
 	/* bms1 and bms2 may have been recycled! Do not free any of them. */
 
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
 	result = BITMAPSET_TO_TEXT(result_bms);
 	bms_free(result_bms);
 
@@ -839,8 +759,7 @@ test_bms_hash_value(PG_FUNCTION_ARGS)
 
 	hash_result = bms_hash_value(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(hash_result);
 }
@@ -889,11 +808,8 @@ test_bitmap_match(PG_FUNCTION_ARGS)
 	/* Call bitmap_match with addresses of the Bitmapset pointers */
 	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
 
-	/* Clean up */
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32(match_result);
 }
@@ -1031,8 +947,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 		total_ops++;
 	}
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(total_ops);
 }
-- 
2.49.0

#47David Rowley
dgrowleyml@gmail.com
In reply to: Greg Burd (#46)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Wed, 1 Oct 2025 at 01:38, Greg Burd <greg@burd.me> wrote:

v2 attached.

Thanks.

I looked at this and I think we can do a bit better to simplify the
code and standardise what we do when faced with bogus inputs.

Here's what I've done:

1. Added helper macros PG_ARG_GETBITMAPSET() and
PG_RETURN_BITMAPSET_AS_TEXT(). These themselves save a few hundred
lines of code and make the functions easier to read.
2. Standardised that the test function returns NULL when it receives
invalid input. e.g if we aim to pass an "int" to the underlying
Bitmapset function, if someone calls the test function with an SQL
NULL, just return NULL rather than trying to come up with some logic
on what we should do about that.
3. I couldn't quite understand the extra parameter to
test_bms_get_singleton_member() so I ended up removing it and making
the test function return -1 when the set isn't a singleton. I didn't
search for discussion about that so I might have missed the specific
reason it was done that way.
4. Wrote some comments to try to communicate the standards defined.
This aims to offer guidance to callers of these functions and anyone
hacking on the module itself in the future.

git diff --stat looks like:

4 files changed, 233 insertions(+), 505 deletions(-)

Things not done:

1. I didn't update the expected test results.
2. I didn't rationalise the tests. I feel that there's no point in the
tests that purposefully pass invalid input to the module's test
function. It appears that's aiming to increase coverage on the test
module's C code, which I don't quite understand. In any case, due to
the helper macros, I don't think removing these will lower the
per-source-file line coverage of the module itself.

I've not checked my work very thoroughly. I can do that, or you can if
you and Michael are ok with the proposed ideas. I'm also not aiming to
commandeer anything here. Writing the patch was just the easiest way
to communicate the ideas I had.

I also wonder how worthwhile it is to try to free the Bitmapsets. I'd
have expected these allocations to be in a pretty short-lived memory
context. I count 44 calls to bms_free().

David

Attachments:

adjustments_to_test_bitmapset_module.patchapplication/octet-stream; name=adjustments_to_test_bitmapset_module.patchDownload
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
index be7b6399c82..2e204d687df 100644
--- a/src/test/modules/test_bitmapset/expected/test_bitmapset.out
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -63,7 +63,7 @@ SELECT test_bms_add_member('(b 10)', 10) AS result;
 SELECT test_bms_add_member('(b)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_replace_members()
@@ -76,7 +76,7 @@ SELECT test_bms_replace_members(NULL, '(b 1 2 3)') AS result;
 SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_replace_members('(b 1 2 3)', '(b 3 5 6)') AS result;
@@ -108,13 +108,13 @@ SELECT test_bms_replace_members('(b 1 2 3 4 5)', '(b 500 600)') AS result;
 SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_replace_members('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
@@ -126,7 +126,7 @@ SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
 SELECT test_bms_replace_members(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_del_member()
@@ -135,13 +135,13 @@ ERROR:  negative bitmapset member not allowed
 SELECT test_bms_del_member('(b)', 10) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_member('(b 10)', 10) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_member('(b 10)', 5) AS result;
@@ -193,26 +193,26 @@ SELECT test_bms_del_member('(b 1 50 100 200)', 100) AS result;
 SELECT test_bms_del_member('(b 42)', 42) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_member('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 -- bms_del_members()
 SELECT test_bms_del_members('(b)', '(b 10)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_members('(b 10)', '(b 10)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_del_members('(b 10)', '(b 5)') AS result;
@@ -262,7 +262,7 @@ SELECT test_bms_del_members('(b 5)', NULL) AS result;
 SELECT test_bms_del_members(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_join()
@@ -319,7 +319,7 @@ SELECT test_bms_join(NULL, '(b 5)') AS result;
 SELECT test_bms_join(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_union()
@@ -341,7 +341,7 @@ SELECT test_bms_union('(b 1 3 5)', '(b)') AS result;
 SELECT test_bms_union('(b)', '(b)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Overlapping ranges
@@ -383,7 +383,7 @@ SELECT test_bms_union(NULL, '(b 5)') AS result;
 SELECT test_bms_union(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_intersect()
@@ -398,14 +398,14 @@ SELECT test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Intersect with empty
 SELECT test_bms_intersect('(b 1 3 5)', '(b)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Intersect with varrying word counts
@@ -425,25 +425,25 @@ SELECT test_bms_intersect('(b 1 2 3 4 5)', '(b 1 300)') AS result;
 SELECT test_bms_intersect('(b 1)', '(b 2)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_intersect('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_intersect(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_intersect(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_int_members()
@@ -458,14 +458,14 @@ SELECT test_bms_int_members('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Intersect with empty
 SELECT test_bms_int_members('(b 1 3 5)', '(b)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Multiple members
@@ -479,25 +479,25 @@ SELECT test_bms_int_members('(b 0 31 32 63 64)', '(b 31 32 64 65)') AS result;
 SELECT test_bms_int_members('(b 1)', '(b 2)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_int_members('(b 5)', NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_int_members(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_int_members(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_difference()
@@ -519,14 +519,14 @@ SELECT test_bms_difference('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT test_bms_difference('(b 1 3 5)', '(b 1 3 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Substraction to empty
 SELECT test_bms_difference('(b 42)', '(b 42)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- Subtraction edge case
@@ -556,7 +556,7 @@ SELECT test_bms_difference('(b 1 2 100 200)', '(b 1 2)') AS result;
 SELECT test_bms_difference('(b 5)', '(b 5 10)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_difference('(b 5)', NULL) AS result;
@@ -568,13 +568,13 @@ SELECT test_bms_difference('(b 5)', NULL) AS result;
 SELECT test_bms_difference(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_difference(NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_is_member()
@@ -887,19 +887,19 @@ SELECT length(test_bms_add_range('(b 1 2)', 200, 250)) AS result;
 SELECT test_bms_add_range('(b 5)', 5, NULL) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 SELECT test_bms_add_range('(b 5)', NULL, 10) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 SELECT test_bms_add_range('(b 5)', NULL, NULL) AS result;
  result 
 --------
- 
+ (b 5)
 (1 row)
 
 SELECT test_bms_add_range(NULL, 5, 10) AS result;
@@ -911,13 +911,13 @@ SELECT test_bms_add_range(NULL, 5, 10) AS result;
 SELECT test_bms_add_range(NULL, 10, 5) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_add_range(NULL, NULL, NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_membership()
@@ -1421,7 +1421,7 @@ SELECT test_bms_subset_compare(NULL, NULL) AS result;
 SELECT test_bms_copy(NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 SELECT test_bms_copy('(b 1 3 5 7)') AS result;
@@ -1434,7 +1434,7 @@ SELECT test_bms_copy('(b 1 3 5 7)') AS result;
 SELECT test_bms_copy(NULL) AS result;
  result 
 --------
- 
+ (b)
 (1 row)
 
 -- bms_add_members()
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
index c6e6bce60a3..c7c3cce93d3 100644
--- a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -258,14 +258,13 @@ SELECT test_bms_singleton_member('(b 42)') AS result;
 SELECT test_bms_singleton_member(NULL) AS result;
 
 -- bms_get_singleton_member()
-SELECT test_bms_get_singleton_member('(b)', 1000);
+SELECT test_bms_get_singleton_member('(b)');
+-- Try with an empty set
+SELECT test_bms_get_singleton_member(NULL) AS result;
 -- Not a singleton, returns input default
-SELECT test_bms_get_singleton_member('(b 3 6)', 1000) AS result;
+SELECT test_bms_get_singleton_member('(b 3 6)') AS result;
 -- Singletone, returns sole member
-SELECT test_bms_get_singleton_member('(b 400)', 1000) AS result;
--- Test module checks
-SELECT test_bms_get_singleton_member('', 1000) AS result;
-SELECT test_bms_get_singleton_member(NULL, -1) AS result;
+SELECT test_bms_get_singleton_member('(b 400)') AS result;
 
 -- bms_next_member() and bms_prev_member()
 -- First member
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
index b95c4d0dda5..227ecb5aa3b 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -68,7 +68,7 @@ CREATE FUNCTION test_bms_singleton_member(text)
 RETURNS integer STRICT
 AS 'MODULE_PATHNAME' LANGUAGE C;
 
-CREATE FUNCTION test_bms_get_singleton_member(text, integer)
+CREATE FUNCTION test_bms_get_singleton_member(text)
 RETURNS integer
 AS 'MODULE_PATHNAME' LANGUAGE C;
 
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 2e821320836..88fd71d5495 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -26,7 +26,6 @@
 #include "nodes/pg_list.h"
 #include "utils/builtins.h"
 #include "utils/timestamp.h"
-#include "varatt.h"
 
 PG_MODULE_MAGIC;
 
@@ -84,105 +83,109 @@ PG_FUNCTION_INFO_V1(test_random_operations);
 				 #expr, __FILE__, __LINE__); \
 	} while (0)
 
+static const char *emptyset = "(b)";
+
 /* Encode/Decode to/from TEXT and Bitmapset */
-#define BITMAPSET_TO_TEXT(bms) cstring_to_text(nodeToString(bms))
+#define BITMAPSET_TO_TEXT(bms) cstring_to_text(bms ? nodeToString(bms) : emptyset)
 #define TEXT_TO_BITMAPSET(str) ((Bitmapset *) stringToNode(text_to_cstring(str)))
 
+/* Helper macro to fetch Text parameters as Bitmapsets. SQL-NULL means empty set */
+#define PG_ARG_GETBITMAPSET(n) \
+	(PG_ARGISNULL(n) ? NULL : TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(n)))
+
+/*
+ * Helper macro to handle converting sets back to text, freeing the set and
+ * returning the resulting text representation of the set.  Beware of double
+ * evaluation hazard of 'bms'.
+ */
+#define PG_RETURN_BITMAPSET_AS_TEXT(bms) \
+	do { \
+		text	   *result = BITMAPSET_TO_TEXT(bms); \
+		bms_free(bms); \
+		PG_RETURN_TEXT_P(result); \
+	} while (0);
+
 /*
  * Individual test functions for each bitmapset API function
+ *
+ * Primarily, we aim to keep these as close to simple wrapper functions as
+ * possible in order to publish the functions of bitmapset.c to the SQL layer
+ * with as little interference as possible.  We opt to return SQL NULL in
+ * cases where the input given to the SQL function isn't valid to pass to the
+ * underlying bitmapset.c function.  For example we cannot do much useful
+ * testing if someone calls test_bms_make_singleton(NULL) since
+ * bms_make_singleton() expects an integer argument.
+ *
+ * For function arguments which are to be converted to Bitmapsets, we accept
+ * SQL NULL as a valid argument to mean an empty set.  Optionally callers may
+ * pass '(b)'.
+ *
+ * For the test functions which return a Bitmapset, these are converted back
+ * to Text with empty sets being represented as '(b)'.
  */
 
 Datum
 test_bms_add_member(PG_FUNCTION_ARGS)
 {
+	Bitmapset  *bms;
 	int			member;
-	Bitmapset  *bms = NULL;
-	text	   *result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_NULL();
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
-	bms = bms_add_member(bms, member);
-	result = BITMAPSET_TO_TEXT(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms = bms_add_member(bms, member);
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_add_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	text	   *result;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* IMPORTANT: bms_add_members modifies/frees the first argument */
+	/* left input is recycled */
 	bms1 = bms_add_members(bms1, bms2);
+	bms_free(bms2);
 
-	if (bms2)
-		bms_free(bms2);
-
-	result = BITMAPSET_TO_TEXT(bms1);
-	bms_free(bms1);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_del_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		member;
-	text	   *result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_NULL();
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
-	bms = bms_del_member(bms, member);
-
-	if (bms_is_empty(bms))
-		PG_RETURN_NULL();
 
-	result = BITMAPSET_TO_TEXT(bms);
-	bms_free(bms);
+	bms = bms_del_member(bms, member);
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_is_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		member;
 	bool		result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_BOOL(false);
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
-	result = bms_is_member(member, bms);
 
-	if (bms)
-		bms_free(bms);
+	result = bms_is_member(member, bms);
+	bms_free(bms);
 
 	PG_RETURN_BOOL(result);
 }
@@ -190,16 +193,11 @@ test_bms_is_member(PG_FUNCTION_ARGS)
 Datum
 test_bms_num_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
-	int			result = 0;
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
+	int			result;
 
 	result = bms_num_members(bms);
-
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -207,65 +205,40 @@ test_bms_num_members(PG_FUNCTION_ARGS)
 Datum
 test_bms_make_singleton(PG_FUNCTION_ARGS)
 {
-	int32		member;
 	Bitmapset  *bms;
-	text	   *result;
+	int32		member;
 
 	if (PG_ARGISNULL(0))
-		PG_RETURN_NULL();
+		PG_RETURN_NULL();		/* invalid input */
 
 	member = PG_GETARG_INT32(0);
 	bms = bms_make_singleton(member);
 
-	result = BITMAPSET_TO_TEXT(bms);
-	bms_free(bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_copy(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	Bitmapset  *copy_bms;
-	text	   *result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_NULL();
-
-	bms_data = PG_GETARG_TEXT_PP(0);
-	bms = TEXT_TO_BITMAPSET(bms_data);
 	copy_bms = bms_copy(bms);
-	result = BITMAPSET_TO_TEXT(copy_bms);
-
-	if (bms)
-		bms_free(bms);
-	if (copy_bms)
-		bms_free(copy_bms);
+	bms_free(bms);
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(copy_bms);
 }
 
 Datum
 test_bms_equal(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_equal(bms1, bms2);
-
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -273,47 +246,25 @@ test_bms_equal(PG_FUNCTION_ARGS)
 Datum
 test_bms_union(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
 
 	result_bms = bms_union(bms1, bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_membership(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	BMS_Membership result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(BMS_EMPTY_SET);
-
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 	result = bms_membership(bms);
-
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32((int32) result);
 }
@@ -321,19 +272,18 @@ test_bms_membership(PG_FUNCTION_ARGS)
 Datum
 test_bms_next_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		prevmember;
 	int			result;
 
-	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
-		PG_RETURN_INT32(-2);
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();		/* invalid input */
 
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	bms = PG_ARG_GETBITMAPSET(0);
 	prevmember = PG_GETARG_INT32(1);
-	result = bms_next_member(bms, prevmember);
 
-	if (bms)
-		bms_free(bms);
+	result = bms_next_member(bms, prevmember);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -341,82 +291,41 @@ test_bms_next_member(PG_FUNCTION_ARGS)
 Datum
 test_bms_intersect(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
 
 	result_bms = bms_intersect(bms1, bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_difference(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
 
 	result_bms = bms_difference(bms1, bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_compare(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	int			result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_compare(bms1, bms2);
-
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32(result);
 }
@@ -424,16 +333,11 @@ test_bms_compare(PG_FUNCTION_ARGS)
 Datum
 test_bms_is_empty(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
 	result = bms_is_empty(bms);
-
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_BOOL(result);
 }
@@ -441,22 +345,13 @@ test_bms_is_empty(PG_FUNCTION_ARGS)
 Datum
 test_bms_is_subset(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_is_subset(bms1, bms2);
-
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -464,22 +359,13 @@ test_bms_is_subset(PG_FUNCTION_ARGS)
 Datum
 test_bms_subset_compare(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	BMS_Comparison result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_subset_compare(bms1, bms2);
-
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32((int32) result);
 }
@@ -487,16 +373,11 @@ test_bms_subset_compare(PG_FUNCTION_ARGS)
 Datum
 test_bms_singleton_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	int			result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
 	result = bms_singleton_member(bms);
-
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -504,47 +385,34 @@ test_bms_singleton_member(PG_FUNCTION_ARGS)
 Datum
 test_bms_get_singleton_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
-	int32		default_member = PG_GETARG_INT32(1);
-	bool		success;
-	int			member = -1;
-
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(default_member);
-
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
+	int			member;
 
 	/*
-	 * bms_get_singleton_member returns bool and stores result in member
-	 * pointer
+	 * Keep this simple.  Return -1 when we detect the set isn't a singleton
+	 * set, otherwise return the singleton member.
 	 */
-	success = bms_get_singleton_member(bms, &member);
-	bms_free(bms);
+	if (!bms_get_singleton_member(bms, &member))
+		member = -1;
 
-	if (success)
-		PG_RETURN_INT32(member);
+	bms_free(bms);
 
-	PG_RETURN_INT32(default_member);
+	PG_RETURN_INT32(member);
 }
 
 Datum
 test_bms_prev_member(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		prevmember;
 	int			result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(-2);
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();		/* invalid input */
 
-	bms_data = PG_GETARG_TEXT_PP(0);
+	bms = PG_ARG_GETBITMAPSET(0);
 	prevmember = PG_GETARG_INT32(1);
 
-	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
-		PG_RETURN_INT32(-2);
-
-	bms = TEXT_TO_BITMAPSET(bms_data);
 	result = bms_prev_member(bms, prevmember);
 	bms_free(bms);
 
@@ -554,22 +422,13 @@ test_bms_prev_member(PG_FUNCTION_ARGS)
 Datum
 test_bms_overlap(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_overlap(bms1, bms2);
-
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -577,52 +436,47 @@ test_bms_overlap(PG_FUNCTION_ARGS)
 Datum
 test_bms_overlap_list(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	ArrayType  *array;
 	List	   *int_list = NIL;
 	bool		result;
-	Datum	   *elem_datums;
-	bool	   *elem_nulls;
+	Datum	   *elem_datums = NULL;
+	bool	   *elem_nulls = NULL;
 	int			elem_count;
 	int			i;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_BOOL(false);
+	bms = PG_ARG_GETBITMAPSET(0);
 
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (PG_ARGISNULL(1))
+	if (!PG_ARGISNULL(1))
 	{
-		if (bms)
-			bms_free(bms);
-		PG_RETURN_BOOL(false);
-	}
-
-	array = PG_GETARG_ARRAYTYPE_P(1);
+		array = PG_GETARG_ARRAYTYPE_P(1);
 
-	deconstruct_array(array,
-					  INT4OID, sizeof(int32), true, 'i',
-					  &elem_datums, &elem_nulls, &elem_count);
+		deconstruct_array(array,
+						  INT4OID, sizeof(int32), true, 'i',
+						  &elem_datums, &elem_nulls, &elem_count);
 
-	for (i = 0; i < elem_count; i++)
-	{
-		if (!elem_nulls[i])
+		for (i = 0; i < elem_count; i++)
 		{
-			int32		member = DatumGetInt32(elem_datums[i]);
+			if (!elem_nulls[i])
+			{
+				int32		member = DatumGetInt32(elem_datums[i]);
 
-			int_list = lappend_int(int_list, member);
+				int_list = lappend_int(int_list, member);
+			}
 		}
 	}
 
 	result = bms_overlap_list(bms, int_list);
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	list_free(int_list);
 
-	pfree(elem_datums);
-	pfree(elem_nulls);
+	if (elem_datums)
+		pfree(elem_datums);
+
+	if (elem_nulls)
+		pfree(elem_nulls);
 
 	PG_RETURN_BOOL(result);
 }
@@ -630,22 +484,13 @@ test_bms_overlap_list(PG_FUNCTION_ARGS)
 Datum
 test_bms_nonempty_difference(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_nonempty_difference(bms1, bms2);
-
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_BOOL(result);
 }
@@ -653,22 +498,16 @@ test_bms_nonempty_difference(PG_FUNCTION_ARGS)
 Datum
 test_bms_member_index(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		member;
 	int			result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(-1);
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();		/* invalid input */
 
-	bms_data = PG_GETARG_TEXT_PP(0);
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
 
-	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
-		PG_RETURN_INT32(-1);
-
-	bms = TEXT_TO_BITMAPSET(bms_data);
-
 	result = bms_member_index(bms, member);
 	bms_free(bms);
 
@@ -678,169 +517,85 @@ test_bms_member_index(PG_FUNCTION_ARGS)
 Datum
 test_bms_add_range(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		lower,
 				upper;
-	text	   *result;
 
 	if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
-		PG_RETURN_NULL();
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	lower = PG_GETARG_INT32(1);
 	upper = PG_GETARG_INT32(2);
 
-	/* Check for invalid range */
-	if (upper < lower)
-	{
-		if (bms)
-			bms_free(bms);
-		PG_RETURN_NULL();
-	}
-
 	bms = bms_add_range(bms, lower, upper);
 
-	result = BITMAPSET_TO_TEXT(bms);
-	if (bms)
-		bms_free(bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_int_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
+	/* left input gets recycled */
 	bms1 = bms_int_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
-
-	if (bms1 == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(bms1);
-
-	if (bms1)
-		bms_free(bms1);
+	bms_free(bms2);
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_del_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	Bitmapset  *result_bms;
-	text	   *result;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* IMPORTANT: bms_del_members modifies/frees the first argument */
-	result_bms = bms_del_members(bms1, bms2);
-
-	/* bms1 is now invalid, do not free it */
-
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
+	/* left input gets recycled */
+	bms1 = bms_del_members(bms1, bms2);
+	bms_free(bms2);
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_replace_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* IMPORTANT: bms_replace_members modifies/frees the first argument */
-	result_bms = bms_replace_members(bms1, bms2);
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
-	/* bms1 is now invalid, do not free it */
+	/* left input gets recycled */
+	bms1 = bms_replace_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	bms_free(bms2);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_join(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
 
-	/* IMPORTANT: bms_join may recycle either input arguments */
+	/* either input can be recycled */
 	result_bms = bms_join(bms1, bms2);
 
-	/* bms1 and bms2 may have been recycled! Do not free any of them. */
+	/* memory cleanup seems more tricky than it's worth here */
 
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_hash_value(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	uint32		hash_result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
 	hash_result = bms_hash_value(bms);
-
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(hash_result);
 }
@@ -848,21 +603,12 @@ test_bms_hash_value(PG_FUNCTION_ARGS)
 Datum
 test_bitmap_hash(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
-	Bitmapset  *bms_ptr;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	uint32		hash_result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	bms_ptr = bms;
-
 	/* Call bitmap_hash */
-	hash_result = bitmap_hash(&bms_ptr, sizeof(Bitmapset *));
-
-	/* Clean up */
-	if (!PG_ARGISNULL(0) && bms_ptr)
-		bms_free(bms_ptr);
+	hash_result = bitmap_hash(&bms, sizeof(Bitmapset *));
+	bms_free(bms);
 
 	PG_RETURN_INT32(hash_result);
 }
@@ -870,30 +616,14 @@ test_bitmap_hash(PG_FUNCTION_ARGS)
 Datum
 test_bitmap_match(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	Bitmapset  *bms_ptr1,
-			   *bms_ptr2;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	int			match_result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* Set up pointers to the Bitmapsets */
-	bms_ptr1 = bms1;
-	bms_ptr2 = bms2;
-
 	/* Call bitmap_match with addresses of the Bitmapset pointers */
-	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
-
-	/* Clean up */
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	match_result = bitmap_match(&bms1, &bms2, sizeof(Bitmapset *));
+	bms_free(bms1);
+	bms_free(bms2);
 
 	PG_RETURN_INT32(match_result);
 }
@@ -1031,8 +761,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 		total_ops++;
 	}
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(total_ops);
 }
#48Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#47)
Re: [PATCH] Add tests for Bitmapset

On Wed, Oct 01, 2025 at 12:00:39PM +1300, David Rowley wrote:

1. Added helper macros PG_ARG_GETBITMAPSET() and
PG_RETURN_BITMAPSET_AS_TEXT(). These themselves save a few hundred
lines of code and make the functions easier to read.

+#define PG_RETURN_BITMAPSET_AS_TEXT(bms) \
+   do { \
+       text       *result = BITMAPSET_TO_TEXT(bms); \
+       bms_free(bms); \
+       PG_RETURN_TEXT_P(result); \
+   } while (0);

This is also something I've considered as embedding in a macro, and
discarded it. The reason was code readability, because it gives to
the reader a quick knowledge of what can be freed once a call to a
specific bitmapset.c routine is done, acting as a kind of reference
template. Here, the free call knowledge gets hidden. test_bms_copy()
becomes more confusing to me. This argument comes down to one's taste
and philosophy on the matter of test modules. These are for me tools
of coverage, but also can work as reference templates when calling an
internal routine because we also document some of its implied
behaviors, like the inputs recycled.

2. Standardised that the test function returns NULL when it receives
invalid input. e.g if we aim to pass an "int" to the underlying
Bitmapset function, if someone calls the test function with an SQL
NULL, just return NULL rather than trying to come up with some logic
on what we should do about that.

+static const char *emptyset = "(b)";

Not sure that I'm on board with hardcoding this knowledge in the test
module. But well, if you feel strongly about it, I'm not going to put
a fight for it.

3. I couldn't quite understand the extra parameter to
test_bms_get_singleton_member() so I ended up removing it and making
the test function return -1 when the set isn't a singleton. I didn't
search for discussion about that so I might have missed the specific
reason it was done that way.

It is not very far. In short, I am caring about the status returned
by bms_get_singleton_member(), then translated in the output of the
SQL function based on the default given in input:
/messages/by-id/aNolInqSzt1d1338@paquier.xyz

Perhaps not the most elegant solution, but simpler than returning a
setof without changing the meaning of the tests. So we could return
the status directly or use the default value from the input, not doing
any of these actions reduces what's reported back at SQL level.

4. Wrote some comments to try to communicate the standards defined.
This aims to offer guidance to callers of these functions and anyone
hacking on the module itself in the future.

+/* Helper macro to fetch Text parameters as Bitmapsets. SQL-NULL means empty set */
+#define PG_ARG_GETBITMAPSET(n) \
+   (PG_ARGISNULL(n) ? NULL : TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(n)))

True that embedding the PG_ARGISNULL() call may be better in a macro,
as passing NULL values to the internal routines is OK.

I also wonder how worthwhile it is to try to free the Bitmapsets. I'd
have expected these allocations to be in a pretty short-lived memory
context. I count 44 calls to bms_free().

I've wondered about that as well. However, I have concluded to leave
the free calls arounds, for the memory context argument if someone
plays more with this module. I don't mind the removal of the NULL
checks when calling bms_free() to cut lines in the module, though. I
was also seeing an argument with cross-checking the frees after a
REALLOCATE_BITMAPSETS copy, as well, for sanity checks. So I would
rather leave them as they are, not remove them. Again, that may come
up to one's view on the matter and one's philosophy around these
modules.
--
Michael

#49David Rowley
dgrowleyml@gmail.com
In reply to: Michael Paquier (#48)
Re: [PATCH] Add tests for Bitmapset

On Wed, 1 Oct 2025 at 12:37, Michael Paquier <michael@paquier.xyz> wrote:

On Wed, Oct 01, 2025 at 12:00:39PM +1300, David Rowley wrote:

1. Added helper macros PG_ARG_GETBITMAPSET() and
PG_RETURN_BITMAPSET_AS_TEXT(). These themselves save a few hundred
lines of code and make the functions easier to read.

+#define PG_RETURN_BITMAPSET_AS_TEXT(bms) \
+   do { \
+       text       *result = BITMAPSET_TO_TEXT(bms); \
+       bms_free(bms); \
+       PG_RETURN_TEXT_P(result); \
+   } while (0);

This is also something I've considered as embedding in a macro, and
discarded it. The reason was code readability, because it gives to
the reader a quick knowledge of what can be freed once a call to a
specific bitmapset.c routine is done, acting as a kind of reference
template. Here, the free call knowledge gets hidden. test_bms_copy()
becomes more confusing to me. This argument comes down to one's taste
and philosophy on the matter of test modules. These are for me tools
of coverage, but also can work as reference templates when calling an
internal routine because we also document some of its implied
behaviors, like the inputs recycled.

This sounds like another argument towards getting rid of the bms_frees
from the module.

2. Standardised that the test function returns NULL when it receives
invalid input. e.g if we aim to pass an "int" to the underlying
Bitmapset function, if someone calls the test function with an SQL
NULL, just return NULL rather than trying to come up with some logic
on what we should do about that.

+static const char *emptyset = "(b)";

Not sure that I'm on board with hardcoding this knowledge in the test
module. But well, if you feel strongly about it, I'm not going to put
a fight for it.

I'm not a huge fan of that part either. I didn't feel strongly enough
to change it when adjusting Greg's v2. For me, I don't see the problem
with leaving it up to nodeToString(), which will return "<>" for an
empty set.

3. I couldn't quite understand the extra parameter to
test_bms_get_singleton_member() so I ended up removing it and making
the test function return -1 when the set isn't a singleton. I didn't
search for discussion about that so I might have missed the specific
reason it was done that way.

It is not very far. In short, I am caring about the status returned
by bms_get_singleton_member(), then translated in the output of the
SQL function based on the default given in input:
/messages/by-id/aNolInqSzt1d1338@paquier.xyz

Perhaps not the most elegant solution, but simpler than returning a
setof without changing the meaning of the tests. So we could return
the status directly or use the default value from the input, not doing
any of these actions reduces what's reported back at SQL level.

Thanks for explaining. Is anything being lost with the -1 return?
Since that's not a valid member for a set, -1 can only be returned if
bms_get_singleton_member() returned false.

4. Wrote some comments to try to communicate the standards defined.
This aims to offer guidance to callers of these functions and anyone
hacking on the module itself in the future.

+/* Helper macro to fetch Text parameters as Bitmapsets. SQL-NULL means empty set */
+#define PG_ARG_GETBITMAPSET(n) \
+   (PG_ARGISNULL(n) ? NULL : TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(n)))

True that embedding the PG_ARGISNULL() call may be better in a macro,
as passing NULL values to the internal routines is OK.

OK good. There's a decent code reduction from this one.

I also wonder how worthwhile it is to try to free the Bitmapsets. I'd
have expected these allocations to be in a pretty short-lived memory
context. I count 44 calls to bms_free().

I've wondered about that as well. However, I have concluded to leave
the free calls arounds, for the memory context argument if someone
plays more with this module. I don't mind the removal of the NULL
checks when calling bms_free() to cut lines in the module, though. I
was also seeing an argument with cross-checking the frees after a
REALLOCATE_BITMAPSETS copy, as well, for sanity checks. So I would
rather leave them as they are, not remove them. Again, that may come
up to one's view on the matter and one's philosophy around these
modules.

Because you're not happy with embedding the bms_free() in with
PG_RETURN_BITMAPSET_AS_TEXT(), why don't we just get rid of all the
bms_free's? It's just a test module. If anyone ever comes complaining
about memory usage then we can reconsider. I think it's nice to keep
these wrappers as thin as possible in terms of the amount of C code.
Having conditional logic in them, IMO, risk hiding the true behaviour
of the underlying code that's being tested.

I know I've just come in here like a bull in a china shop. It's not my
intention to imply that anything is wrong with the code. I just put
together my thoughts in the hopes that it can be made even better.

David

#50Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#49)
Re: [PATCH] Add tests for Bitmapset

On Wed, Oct 01, 2025 at 01:07:10PM +1300, David Rowley wrote:

On Wed, 1 Oct 2025 at 12:37, Michael Paquier <michael@paquier.xyz> wrote:

This is also something I've considered as embedding in a macro, and
discarded it. The reason was code readability, because it gives to
the reader a quick knowledge of what can be freed once a call to a
specific bitmapset.c routine is done, acting as a kind of reference
template. Here, the free call knowledge gets hidden. test_bms_copy()
becomes more confusing to me. This argument comes down to one's taste
and philosophy on the matter of test modules. These are for me tools
of coverage, but also can work as reference templates when calling an
internal routine because we also document some of its implied
behaviors, like the inputs recycled.

This sounds like another argument towards getting rid of the bms_frees
from the module.

With the RETURN macro in mind, which itself cuts quite a little bit of
code, I'd rather do as you are suggesting and remove the free calls,
then. Embedding this knowledge in the return macro seems not much
adapted to me, but I don't object to this macro idea per-se.

I'm not a huge fan of that part either. I didn't feel strongly enough
to change it when adjusting Greg's v2. For me, I don't see the problem
with leaving it up to nodeToString(), which will return "<>" for an
empty set.

I think it's fine to leave it to nodeToString(). It is able to handle
a NULL input on its own.

Thanks for explaining. Is anything being lost with the -1 return?
Since that's not a valid member for a set, -1 can only be returned if
bms_get_singleton_member() returned false.

+   if (!bms_get_singleton_member(bms, &member))
+       member = -1;

Hmm. On second look, if you do that, there's no knowledge lost, I
guess.

Because you're not happy with embedding the bms_free() in with
PG_RETURN_BITMAPSET_AS_TEXT(), why don't we just get rid of all the
bms_free's? It's just a test module. If anyone ever comes complaining
about memory usage then we can reconsider. I think it's nice to keep
these wrappers as thin as possible in terms of the amount of C code.
Having conditional logic in them, IMO, risk hiding the true behaviour
of the underlying code that's being tested.

Okay. Let's just remove as much code as possible, then. This is
roughly what you have sent, minus the hardcoded empty set and the free
calls. I'll just go do that in a bit.
--
Michael

#51David Rowley
dgrowleyml@gmail.com
In reply to: Michael Paquier (#50)
Re: [PATCH] Add tests for Bitmapset

On Wed, 1 Oct 2025 at 16:41, Michael Paquier <michael@paquier.xyz> wrote:

Okay. Let's just remove as much code as possible, then. This is
roughly what you have sent, minus the hardcoded empty set and the free
calls. I'll just go do that in a bit.

Thanks. Just for reference, you may not need it if you're mostly done
already, but I had to finish this off in my head before moving on.
Feel free to ignore, but there are a couple of typos fixed at the very
least "varrying" should be "varying".

I didn't fully rationalise the tests in test_bitmapset.sql. There are
still a few which are duplicates due to '(b)' and NULL meaning the
same thing.

git diff --stat
.../test_bitmapset/expected/test_bitmapset.out | 400 ++------------
.../modules/test_bitmapset/sql/test_bitmapset.sql | 101 +---
.../modules/test_bitmapset/test_bitmapset--1.0.sql | 2 +-
src/test/modules/test_bitmapset/test_bitmapset.c | 605 +++++----------------
4 files changed, 222 insertions(+), 886 deletions(-)

I didn't look at the coverage report, but on thinking about it,
test_bitmapset.c's "PG_RETURN_NULL(); /* invalid input */" won't be
covered as I stripped out all the tests which purposefully pass
invalid input. You may not want it that way if you're keen to keep the
coverage of the test module high as well as bitmapset.c

David

#52David Rowley
dgrowleyml@gmail.com
In reply to: David Rowley (#51)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Wed, 1 Oct 2025 at 18:00, David Rowley <dgrowleyml@gmail.com> wrote:

git diff --stat
.../test_bitmapset/expected/test_bitmapset.out | 400 ++------------
.../modules/test_bitmapset/sql/test_bitmapset.sql | 101 +---
.../modules/test_bitmapset/test_bitmapset--1.0.sql | 2 +-
src/test/modules/test_bitmapset/test_bitmapset.c | 605 +++++----------------
4 files changed, 222 insertions(+), 886 deletions(-)

And once more, with the patch this time around...

David

Attachments:

adjustments_to_test_bitmapset_module_v2.patchapplication/octet-stream; name=adjustments_to_test_bitmapset_module_v2.patchDownload
diff --git a/src/test/modules/test_bitmapset/expected/test_bitmapset.out b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
index be7b6399c82..8ad7cb71330 100644
--- a/src/test/modules/test_bitmapset/expected/test_bitmapset.out
+++ b/src/test/modules/test_bitmapset/expected/test_bitmapset.out
@@ -59,13 +59,6 @@ SELECT test_bms_add_member('(b 10)', 10) AS result;
  (b 10)
 (1 row)
 
--- Test module check
-SELECT test_bms_add_member('(b)', NULL) AS result;
- result 
---------
- 
-(1 row)
-
 -- bms_replace_members()
 SELECT test_bms_replace_members(NULL, '(b 1 2 3)') AS result;
   result   
@@ -76,7 +69,7 @@ SELECT test_bms_replace_members(NULL, '(b 1 2 3)') AS result;
 SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_replace_members('(b 1 2 3)', '(b 3 5 6)') AS result;
@@ -104,19 +97,20 @@ SELECT test_bms_replace_members('(b 1 2 3 4 5)', '(b 500 600)') AS result;
  (b 500 600)
 (1 row)
 
--- Test module checks
+-- Replace with an empty set
 SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_replace_members('(b 5)', NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
+-- Replace empty set with another set
 SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
  result 
 --------
@@ -126,7 +120,7 @@ SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
 SELECT test_bms_replace_members(NULL, NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- bms_del_member()
@@ -135,13 +129,13 @@ ERROR:  negative bitmapset member not allowed
 SELECT test_bms_del_member('(b)', 10) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_del_member('(b 10)', 10) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_del_member('(b 10)', 5) AS result;
@@ -189,30 +183,24 @@ SELECT test_bms_del_member('(b 1 50 100 200)', 100) AS result;
  (b 1 50 200)
 (1 row)
 
--- Test module checks
+-- Empty resulting set
 SELECT test_bms_del_member('(b 42)', 42) AS result;
  result 
 --------
- 
-(1 row)
-
-SELECT test_bms_del_member('(b 5)', NULL) AS result;
- result 
---------
- 
+ <>
 (1 row)
 
 -- bms_del_members()
 SELECT test_bms_del_members('(b)', '(b 10)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_del_members('(b 10)', '(b 10)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_del_members('(b 10)', '(b 5)') AS result;
@@ -252,7 +240,7 @@ SELECT test_bms_del_members('(b 1 2 100 200 300)', '(b 200 300)') AS result;
  (b 1 2 100)
 (1 row)
 
--- Test module checks
+-- Test with empty sets
 SELECT test_bms_del_members('(b 5)', NULL) AS result;
  result 
 --------
@@ -262,7 +250,7 @@ SELECT test_bms_del_members('(b 5)', NULL) AS result;
 SELECT test_bms_del_members(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- bms_join()
@@ -303,23 +291,11 @@ SELECT test_bms_join('(b 1 2)', '(b 100 200 300)') AS result;
  (b 1 2 100 200 300)
 (1 row)
 
--- Test module checks
-SELECT test_bms_join('(b 5)', NULL) AS result;
- result 
---------
- (b 5)
-(1 row)
-
-SELECT test_bms_join(NULL, '(b 5)') AS result;
- result 
---------
- (b 5)
-(1 row)
-
+-- Both sets empty
 SELECT test_bms_join(NULL, NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- bms_union()
@@ -330,18 +306,18 @@ SELECT test_bms_union('(b 1 3 5)', '(b 3 5 7)') AS result;
  (b 1 3 5 7)
 (1 row)
 
--- Union with NULL
+-- Union with empty set
 SELECT test_bms_union('(b 1 3 5)', '(b)') AS result;
   result   
 -----------
  (b 1 3 5)
 (1 row)
 
--- Union of empty with empty
+-- Try both sets empty
 SELECT test_bms_union('(b)', '(b)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- Overlapping ranges
@@ -354,7 +330,7 @@ SELECT test_bms_union(
  (b 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)
 (1 row)
 
--- Union with varrying word counts
+-- Union with varying word counts
 SELECT test_bms_union('(b 1 2)', '(b 100 300)') AS result;
      result      
 -----------------
@@ -367,7 +343,7 @@ SELECT test_bms_union('(b 100 300)', '(b 1 2)') AS result;
  (b 1 2 100 300)
 (1 row)
 
--- Test module checks
+-- Unions to empty sets
 SELECT test_bms_union('(b 5)', NULL) AS result;
  result 
 --------
@@ -383,7 +359,7 @@ SELECT test_bms_union(NULL, '(b 5)') AS result;
 SELECT test_bms_union(NULL, NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- bms_intersect()
@@ -398,17 +374,17 @@ SELECT test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- Intersect with empty
 SELECT test_bms_intersect('(b 1 3 5)', '(b)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
--- Intersect with varrying word counts
+-- Intersect with varying word counts
 SELECT test_bms_intersect('(b 1 300)', '(b 1 2 3 4 5)') AS result;
  result 
 --------
@@ -421,29 +397,23 @@ SELECT test_bms_intersect('(b 1 2 3 4 5)', '(b 1 300)') AS result;
  (b 1)
 (1 row)
 
--- Test module checks
-SELECT test_bms_intersect('(b 1)', '(b 2)') AS result;
- result 
---------
- 
-(1 row)
-
+-- Intersect with empty sets
 SELECT test_bms_intersect('(b 5)', NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_intersect(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_intersect(NULL, NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- bms_int_members()
@@ -458,14 +428,14 @@ SELECT test_bms_int_members('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- Intersect with empty
 SELECT test_bms_int_members('(b 1 3 5)', '(b)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- Multiple members
@@ -475,29 +445,23 @@ SELECT test_bms_int_members('(b 0 31 32 63 64)', '(b 31 32 64 65)') AS result;
  (b 31 32 64)
 (1 row)
 
--- Test module checks
-SELECT test_bms_int_members('(b 1)', '(b 2)') AS result;
- result 
---------
- 
-(1 row)
-
+-- Intersect with empty sets
 SELECT test_bms_int_members('(b 5)', NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_int_members(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_int_members(NULL, NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- bms_difference()
@@ -519,14 +483,14 @@ SELECT test_bms_difference('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT test_bms_difference('(b 1 3 5)', '(b 1 3 5)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- Substraction to empty
 SELECT test_bms_difference('(b 42)', '(b 42)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- Subtraction edge case
@@ -556,7 +520,7 @@ SELECT test_bms_difference('(b 1 2 100 200)', '(b 1 2)') AS result;
 SELECT test_bms_difference('(b 5)', '(b 5 10)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_difference('(b 5)', NULL) AS result;
@@ -568,13 +532,13 @@ SELECT test_bms_difference('(b 5)', NULL) AS result;
 SELECT test_bms_difference(NULL, '(b 5)') AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_difference(NULL, NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 -- bms_is_member()
@@ -604,13 +568,6 @@ SELECT test_bms_is_member('(b)', 1) AS result;
  f
 (1 row)
 
--- Test module check
-SELECT test_bms_is_member('(b 5)', NULL) AS result;
- result 
---------
- f
-(1 row)
-
 -- bms_member_index()
 SELECT test_bms_member_index(NULL, 1) AS result;
  result 
@@ -655,19 +612,6 @@ SELECT test_bms_member_index('(b 1 50 100 200)', 200) AS result;
       3
 (1 row)
 
--- Test module checks
-SELECT test_bms_member_index('', 5) AS result;
- result 
---------
-     -1
-(1 row)
-
-SELECT test_bms_member_index(NULL, 5) AS result;
- result 
---------
-     -1
-(1 row)
-
 -- bms_num_members()
 SELECT test_bms_num_members('(b)') AS result;
  result 
@@ -694,6 +638,12 @@ SELECT test_bms_equal('(b)', '(b)') AS result;
  t
 (1 row)
 
+SELECT test_bms_equal(NULL, NULL) AS result;
+ result 
+--------
+ t
+(1 row)
+
 SELECT test_bms_equal('(b)', '(b 1 3 5)') AS result;
  result 
 --------
@@ -731,25 +681,6 @@ SELECT test_bms_equal('(b 5 10)', '(b 100 200 300)') AS result;
  f
 (1 row)
 
--- Test module checks
-SELECT test_bms_equal('(b 5)', NULL) AS result;
- result 
---------
- f
-(1 row)
-
-SELECT test_bms_equal(NULL, '(b 5)') AS result;
- result 
---------
- f
-(1 row)
-
-SELECT test_bms_equal(NULL, NULL) AS result;
- result 
---------
- t
-(1 row)
-
 -- bms_compare()
 SELECT test_bms_compare('(b)', '(b)') AS result;
  result 
@@ -796,25 +727,6 @@ SELECT test_bms_compare(
      -1
 (1 row)
 
--- Test module checks
-SELECT test_bms_compare('(b 5)', NULL) AS result;
- result 
---------
-      1
-(1 row)
-
-SELECT test_bms_compare(NULL, '(b 5)') AS result;
- result 
---------
-     -1
-(1 row)
-
-SELECT test_bms_compare(NULL, NULL) AS result;
- result 
---------
-      0
-(1 row)
-
 -- bms_add_range()
 SELECT test_bms_add_range('(b)', -5, 10); -- error
 ERROR:  negative bitmapset member not allowed
@@ -883,43 +795,6 @@ SELECT length(test_bms_add_range('(b 1 2)', 200, 250)) AS result;
     211
 (1 row)
 
--- Test module checks
-SELECT test_bms_add_range('(b 5)', 5, NULL) AS result;
- result 
---------
- 
-(1 row)
-
-SELECT test_bms_add_range('(b 5)', NULL, 10) AS result;
- result 
---------
- 
-(1 row)
-
-SELECT test_bms_add_range('(b 5)', NULL, NULL) AS result;
- result 
---------
- 
-(1 row)
-
-SELECT test_bms_add_range(NULL, 5, 10) AS result;
-      result      
-------------------
- (b 5 6 7 8 9 10)
-(1 row)
-
-SELECT test_bms_add_range(NULL, 10, 5) AS result;
- result 
---------
- 
-(1 row)
-
-SELECT test_bms_add_range(NULL, NULL, NULL) AS result;
- result 
---------
- 
-(1 row)
-
 -- bms_membership()
 SELECT test_bms_membership('(b)') AS result;
  result 
@@ -965,17 +840,10 @@ SELECT test_bms_is_empty('(b 1)') AS result;
  f
 (1 row)
 
--- Test module check
-SELECT test_bms_is_empty(NULL) AS result;
- result 
---------
- t
-(1 row)
-
 -- bms_singleton_member()
-SELECT test_bms_singleton_member('(b)'); -- error
+SELECT test_bms_singleton_member('(b)'); -- error empty set
 ERROR:  bitmapset is empty
-SELECT test_bms_singleton_member('(b 1 2)'); -- error
+SELECT test_bms_singleton_member('(b 1 2)'); -- error multiple members
 ERROR:  bitmapset has multiple members
 SELECT test_bms_singleton_member('(b 42)') AS result;
  result 
@@ -983,45 +851,26 @@ SELECT test_bms_singleton_member('(b 42)') AS result;
      42
 (1 row)
 
--- Test module check
-SELECT test_bms_singleton_member(NULL) AS result;
- result 
---------
-       
-(1 row)
-
 -- bms_get_singleton_member()
-SELECT test_bms_get_singleton_member('(b)', 1000);
- test_bms_get_singleton_member 
--------------------------------
-                          1000
-(1 row)
-
--- Not a singleton, returns input default
-SELECT test_bms_get_singleton_member('(b 3 6)', 1000) AS result;
- result 
---------
-   1000
-(1 row)
-
--- Singletone, returns sole member
-SELECT test_bms_get_singleton_member('(b 400)', 1000) AS result;
+-- Try with an empty set
+SELECT test_bms_get_singleton_member(NULL) AS result;
  result 
 --------
-    400
+     -1
 (1 row)
 
--- Test module checks
-SELECT test_bms_get_singleton_member('', 1000) AS result;
+-- Not a singleton, returns -1
+SELECT test_bms_get_singleton_member('(b 3 6)') AS result;
  result 
 --------
-   1000
+     -1
 (1 row)
 
-SELECT test_bms_get_singleton_member(NULL, -1) AS result;
+-- Singleton, returns sole member
+SELECT test_bms_get_singleton_member('(b 400)') AS result;
  result 
 --------
-     -1
+    400
 (1 row)
 
 -- bms_next_member() and bms_prev_member()
@@ -1088,49 +937,6 @@ SELECT test_bms_prev_member('(b 0 63 64 127)', -1) AS result;
     127
 (1 row)
 
--- Test module checks
-SELECT test_bms_next_member('', 5) AS result;
- result 
---------
-     -2
-(1 row)
-
-SELECT test_bms_next_member('(b 5)', NULL) AS result;
- result 
---------
-     -2
-(1 row)
-
-SELECT test_bms_next_member(NULL, 5) AS result;
- result 
---------
-     -2
-(1 row)
-
-SELECT test_bms_next_member(NULL, NULL) AS result;
- result 
---------
-     -2
-(1 row)
-
-SELECT test_bms_prev_member('', 5) AS result;
- result 
---------
-     -2
-(1 row)
-
-SELECT test_bms_prev_member('(b 5)', NULL) AS result;
- result 
---------
-     -2
-(1 row)
-
-SELECT test_bms_prev_member(NULL, 5) AS result;
- result 
---------
-     -2
-(1 row)
-
 -- bms_hash_value()
 SELECT test_bms_hash_value('(b)') = 0 AS result;
  result 
@@ -1176,25 +982,6 @@ SELECT test_bms_overlap('(b)', '(b 1 3 5)') AS result;
  f
 (1 row)
 
--- Test module checks
-SELECT test_bms_overlap('(b 5)', NULL) AS result;
- result 
---------
- f
-(1 row)
-
-SELECT test_bms_overlap(NULL, '(b 5)') AS result;
- result 
---------
- f
-(1 row)
-
-SELECT test_bms_overlap(NULL, NULL) AS result;
- result 
---------
- f
-(1 row)
-
 -- bms_is_subset()
 SELECT test_bms_is_subset('(b)', '(b 1 3 5)') AS result;
  result 
@@ -1398,30 +1185,11 @@ SELECT test_bms_subset_compare('(b 2 64 128)', '(b 1 65)') AS result;
       3
 (1 row)
 
--- Test module checks
-SELECT test_bms_subset_compare('(b 5)', NULL) AS result;
- result 
---------
-      2
-(1 row)
-
-SELECT test_bms_subset_compare(NULL, '(b 5)') AS result;
- result 
---------
-      1
-(1 row)
-
-SELECT test_bms_subset_compare(NULL, NULL) AS result;
- result 
---------
-      0
-(1 row)
-
 -- bms_copy()
 SELECT test_bms_copy(NULL) AS result;
  result 
 --------
- 
+ <>
 (1 row)
 
 SELECT test_bms_copy('(b 1 3 5 7)') AS result;
@@ -1430,13 +1198,6 @@ SELECT test_bms_copy('(b 1 3 5 7)') AS result;
  (b 1 3 5 7)
 (1 row)
 
--- Test module check
-SELECT test_bms_copy(NULL) AS result;
- result 
---------
- 
-(1 row)
-
 -- bms_add_members()
 SELECT test_bms_add_members('(b 1 3)', '(b 5 7)') AS result;
    result    
@@ -1481,13 +1242,6 @@ SELECT test_bitmap_hash('(b 1 3 5)') != test_bitmap_hash('(b 2 4 6)') AS result;
  t
 (1 row)
 
--- Test module check
-SELECT test_bitmap_hash(NULL) AS result;
- result 
---------
-      0
-(1 row)
-
 -- bitmap_match()
 SELECT test_bitmap_match('(b)', '(b)') AS result;
  result 
@@ -1547,25 +1301,6 @@ SELECT (test_bitmap_match('(b)', '(b)') = 0) =
  t
 (1 row)
 
--- Test module checks
-SELECT test_bitmap_match('(b 5)', NULL) AS result;
- result 
---------
-      1
-(1 row)
-
-SELECT test_bitmap_match(NULL, '(b 5)') AS result;
- result 
---------
-      1
-(1 row)
-
-SELECT test_bitmap_match(NULL, NULL) AS result;
- result 
---------
-      0
-(1 row)
-
 -- bms_overlap_list()
 SELECT test_bms_overlap_list('(b 0)', ARRAY[0]) AS result;
  result 
@@ -1678,25 +1413,6 @@ SELECT test_bms_nonempty_difference('(b 1 2)', '(b 50 100)') AS result;
  t
 (1 row)
 
--- Test module checks
-SELECT test_bms_nonempty_difference('(b 5)', NULL) AS result;
- result 
---------
- t
-(1 row)
-
-SELECT test_bms_nonempty_difference(NULL, '(b 5)') AS result;
- result 
---------
- f
-(1 row)
-
-SELECT test_bms_nonempty_difference(NULL, NULL) AS result;
- result 
---------
- f
-(1 row)
-
 -- random operations
 SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
  result 
diff --git a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
index c6e6bce60a3..18313dfa350 100644
--- a/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
+++ b/src/test/modules/test_bitmapset/sql/test_bitmapset.sql
@@ -18,8 +18,6 @@ SELECT test_bms_add_member('(b 5)', 10) AS result;
 SELECT test_bms_add_member('(b 10)', 5) AS result;
 -- idempotent change
 SELECT test_bms_add_member('(b 10)', 10) AS result;
--- Test module check
-SELECT test_bms_add_member('(b)', NULL) AS result;
 
 -- bms_replace_members()
 SELECT test_bms_replace_members(NULL, '(b 1 2 3)') AS result;
@@ -29,9 +27,10 @@ SELECT test_bms_replace_members('(b 1 2 3)', '(b 3 5)') AS result;
 SELECT test_bms_replace_members('(b 1 2)', '(b 3 5 7)') AS result;
 -- Force repalloc() with larger set
 SELECT test_bms_replace_members('(b 1 2 3 4 5)', '(b 500 600)') AS result;
--- Test module checks
+-- Replace with an empty set
 SELECT test_bms_replace_members('(b 1 2 3)', NULL) AS result;
 SELECT test_bms_replace_members('(b 5)', NULL) AS result;
+-- Replace empty set with another set
 SELECT test_bms_replace_members(NULL, '(b 5)') AS result;
 SELECT test_bms_replace_members(NULL, NULL) AS result;
 
@@ -49,9 +48,8 @@ SELECT test_bms_del_member(test_bms_add_range('(b)', 30, 34), 32) AS result;
 SELECT test_bms_del_member('(b 1 200)', 200) AS result;
 SELECT test_bms_del_member('(b 1 50 100 200)', 200) AS result;
 SELECT test_bms_del_member('(b 1 50 100 200)', 100) AS result;
--- Test module checks
+-- Empty resulting set
 SELECT test_bms_del_member('(b 42)', 42) AS result;
-SELECT test_bms_del_member('(b 5)', NULL) AS result;
 
 -- bms_del_members()
 SELECT test_bms_del_members('(b)', '(b 10)') AS result;
@@ -63,7 +61,7 @@ SELECT test_bms_del_members('(b 5 100 200)', '(b 200)') AS result;
 -- Force word count changes
 SELECT test_bms_del_members('(b 1 2 100 200 300)', '(b 1 2)') AS result;
 SELECT test_bms_del_members('(b 1 2 100 200 300)', '(b 200 300)') AS result;
--- Test module checks
+-- Test with empty sets
 SELECT test_bms_del_members('(b 5)', NULL) AS result;
 SELECT test_bms_del_members(NULL, '(b 5)') AS result;
 
@@ -75,27 +73,25 @@ SELECT test_bms_join('(b 1 3 5)', '(b 1 4 5)') AS result;
 -- Force word count changes
 SELECT test_bms_join('(b 5)', '(b 100)') AS result;
 SELECT test_bms_join('(b 1 2)', '(b 100 200 300)') AS result;
--- Test module checks
-SELECT test_bms_join('(b 5)', NULL) AS result;
-SELECT test_bms_join(NULL, '(b 5)') AS result;
+-- Both sets empty
 SELECT test_bms_join(NULL, NULL) AS result;
 
 -- bms_union()
 -- Overlapping sets
 SELECT test_bms_union('(b 1 3 5)', '(b 3 5 7)') AS result;
--- Union with NULL
+-- Union with empty set
 SELECT test_bms_union('(b 1 3 5)', '(b)') AS result;
--- Union of empty with empty
+-- Try both sets empty
 SELECT test_bms_union('(b)', '(b)') AS result;
 -- Overlapping ranges
 SELECT test_bms_union(
          test_bms_add_range('(b)', 0, 15),
          test_bms_add_range('(b)', 10, 20)
        ) AS result;
--- Union with varrying word counts
+-- Union with varying word counts
 SELECT test_bms_union('(b 1 2)', '(b 100 300)') AS result;
 SELECT test_bms_union('(b 100 300)', '(b 1 2)') AS result;
--- Test module checks
+-- Unions to empty sets
 SELECT test_bms_union('(b 5)', NULL) AS result;
 SELECT test_bms_union(NULL, '(b 5)') AS result;
 SELECT test_bms_union(NULL, NULL) AS result;
@@ -107,11 +103,10 @@ SELECT test_bms_intersect('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_intersect('(b 1 3 5)', '(b 2 4 6)') AS result;
 -- Intersect with empty
 SELECT test_bms_intersect('(b 1 3 5)', '(b)') AS result;
--- Intersect with varrying word counts
+-- Intersect with varying word counts
 SELECT test_bms_intersect('(b 1 300)', '(b 1 2 3 4 5)') AS result;
 SELECT test_bms_intersect('(b 1 2 3 4 5)', '(b 1 300)') AS result;
--- Test module checks
-SELECT test_bms_intersect('(b 1)', '(b 2)') AS result;
+-- Intersect with empty sets
 SELECT test_bms_intersect('(b 5)', NULL) AS result;
 SELECT test_bms_intersect(NULL, '(b 5)') AS result;
 SELECT test_bms_intersect(NULL, NULL) AS result;
@@ -125,8 +120,7 @@ SELECT test_bms_int_members('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT test_bms_int_members('(b 1 3 5)', '(b)') AS result;
 -- Multiple members
 SELECT test_bms_int_members('(b 0 31 32 63 64)', '(b 31 32 64 65)') AS result;
--- Test module checks
-SELECT test_bms_int_members('(b 1)', '(b 2)') AS result;
+-- Intersect with empty sets
 SELECT test_bms_int_members('(b 5)', NULL) AS result;
 SELECT test_bms_int_members(NULL, '(b 5)') AS result;
 SELECT test_bms_int_members(NULL, NULL) AS result;
@@ -160,8 +154,6 @@ SELECT test_bms_is_member('(b 1 3 5)', 1) AS result;
 SELECT test_bms_is_member('(b 1 3 5)', 2) AS result;
 SELECT test_bms_is_member('(b 1 3 5)', 3) AS result;
 SELECT test_bms_is_member('(b)', 1) AS result;
--- Test module check
-SELECT test_bms_is_member('(b 5)', NULL) AS result;
 
 -- bms_member_index()
 SELECT test_bms_member_index(NULL, 1) AS result;
@@ -172,9 +164,6 @@ SELECT test_bms_member_index('(b 1 3 5)', 3) AS result;
 SELECT test_bms_member_index('(b 100 200)', 100) AS result;
 SELECT test_bms_member_index('(b 100 200)', 200) AS result;
 SELECT test_bms_member_index('(b 1 50 100 200)', 200) AS result;
--- Test module checks
-SELECT test_bms_member_index('', 5) AS result;
-SELECT test_bms_member_index(NULL, 5) AS result;
 
 -- bms_num_members()
 SELECT test_bms_num_members('(b)') AS result;
@@ -183,6 +172,7 @@ SELECT test_bms_num_members('(b 2 4 6 8 10)') AS result;
 
 -- test_bms_equal()
 SELECT test_bms_equal('(b)', '(b)') AS result;
+SELECT test_bms_equal(NULL, NULL) AS result;
 SELECT test_bms_equal('(b)', '(b 1 3 5)') AS result;
 SELECT test_bms_equal('(b 1 3 5)', '(b)') AS result;
 SELECT test_bms_equal('(b 1 3 5)', '(b 1 3 5)') AS result;
@@ -190,10 +180,6 @@ SELECT test_bms_equal('(b 1 3 5)', '(b 2 4 6)') AS result;
 -- Equal with different word counts
 SELECT test_bms_equal('(b 5)', '(b 100)') AS result;
 SELECT test_bms_equal('(b 5 10)', '(b 100 200 300)') AS result;
--- Test module checks
-SELECT test_bms_equal('(b 5)', NULL) AS result;
-SELECT test_bms_equal(NULL, '(b 5)') AS result;
-SELECT test_bms_equal(NULL, NULL) AS result;
 
 -- bms_compare()
 SELECT test_bms_compare('(b)', '(b)') AS result;
@@ -206,10 +192,6 @@ SELECT test_bms_compare(
          test_bms_add_range('(b)', 0, 63),
          test_bms_add_range('(b)', 0, 64)
        ) AS result;
--- Test module checks
-SELECT test_bms_compare('(b 5)', NULL) AS result;
-SELECT test_bms_compare(NULL, '(b 5)') AS result;
-SELECT test_bms_compare(NULL, NULL) AS result;
 
 -- bms_add_range()
 SELECT test_bms_add_range('(b)', -5, 10); -- error
@@ -228,13 +210,6 @@ SELECT length(test_bms_add_range('(b)', 1000, 1100)) AS result;
 -- Force word count expansion
 SELECT test_bms_add_range('(b 5)', 100, 105) AS result;
 SELECT length(test_bms_add_range('(b 1 2)', 200, 250)) AS result;
--- Test module checks
-SELECT test_bms_add_range('(b 5)', 5, NULL) AS result;
-SELECT test_bms_add_range('(b 5)', NULL, 10) AS result;
-SELECT test_bms_add_range('(b 5)', NULL, NULL) AS result;
-SELECT test_bms_add_range(NULL, 5, 10) AS result;
-SELECT test_bms_add_range(NULL, 10, 5) AS result;
-SELECT test_bms_add_range(NULL, NULL, NULL) AS result;
 
 -- bms_membership()
 SELECT test_bms_membership('(b)') AS result;
@@ -247,25 +222,19 @@ SELECT test_bms_membership(NULL) AS result;
 SELECT test_bms_is_empty(NULL) AS result;
 SELECT test_bms_is_empty('(b)') AS result;
 SELECT test_bms_is_empty('(b 1)') AS result;
--- Test module check
-SELECT test_bms_is_empty(NULL) AS result;
 
 -- bms_singleton_member()
-SELECT test_bms_singleton_member('(b)'); -- error
-SELECT test_bms_singleton_member('(b 1 2)'); -- error
+SELECT test_bms_singleton_member('(b)'); -- error empty set
+SELECT test_bms_singleton_member('(b 1 2)'); -- error multiple members
 SELECT test_bms_singleton_member('(b 42)') AS result;
--- Test module check
-SELECT test_bms_singleton_member(NULL) AS result;
 
 -- bms_get_singleton_member()
-SELECT test_bms_get_singleton_member('(b)', 1000);
--- Not a singleton, returns input default
-SELECT test_bms_get_singleton_member('(b 3 6)', 1000) AS result;
--- Singletone, returns sole member
-SELECT test_bms_get_singleton_member('(b 400)', 1000) AS result;
--- Test module checks
-SELECT test_bms_get_singleton_member('', 1000) AS result;
-SELECT test_bms_get_singleton_member(NULL, -1) AS result;
+-- Try with an empty set
+SELECT test_bms_get_singleton_member(NULL) AS result;
+-- Not a singleton, returns -1
+SELECT test_bms_get_singleton_member('(b 3 6)') AS result;
+-- Singleton, returns sole member
+SELECT test_bms_get_singleton_member('(b 400)') AS result;
 
 -- bms_next_member() and bms_prev_member()
 -- First member
@@ -286,14 +255,6 @@ SELECT test_bms_prev_member('(b 5 10 15 20)', 5) AS result;
 SELECT test_bms_prev_member('(b)', 100) AS result;
 -- Negative prevbit should result in highest possible bit in set
 SELECT test_bms_prev_member('(b 0 63 64 127)', -1) AS result;
--- Test module checks
-SELECT test_bms_next_member('', 5) AS result;
-SELECT test_bms_next_member('(b 5)', NULL) AS result;
-SELECT test_bms_next_member(NULL, 5) AS result;
-SELECT test_bms_next_member(NULL, NULL) AS result;
-SELECT test_bms_prev_member('', 5) AS result;
-SELECT test_bms_prev_member('(b 5)', NULL) AS result;
-SELECT test_bms_prev_member(NULL, 5) AS result;
 
 -- bms_hash_value()
 SELECT test_bms_hash_value('(b)') = 0 AS result;
@@ -306,10 +267,6 @@ SELECT test_bms_hash_value(NULL) AS result;
 SELECT test_bms_overlap('(b 1 3 5)', '(b 3 5 7)') AS result;
 SELECT test_bms_overlap('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT test_bms_overlap('(b)', '(b 1 3 5)') AS result;
--- Test module checks
-SELECT test_bms_overlap('(b 5)', NULL) AS result;
-SELECT test_bms_overlap(NULL, '(b 5)') AS result;
-SELECT test_bms_overlap(NULL, NULL) AS result;
 
 -- bms_is_subset()
 SELECT test_bms_is_subset('(b)', '(b 1 3 5)') AS result;
@@ -350,16 +307,10 @@ SELECT test_bms_subset_compare('(b 1 2)', '(b 1 2 64)') AS result;
 SELECT test_bms_subset_compare('(b 64 200)', '(b 1 201)') AS result;
 SELECT test_bms_subset_compare('(b 1 64 65)', '(b 1 2 64)') AS result;
 SELECT test_bms_subset_compare('(b 2 64 128)', '(b 1 65)') AS result;
--- Test module checks
-SELECT test_bms_subset_compare('(b 5)', NULL) AS result;
-SELECT test_bms_subset_compare(NULL, '(b 5)') AS result;
-SELECT test_bms_subset_compare(NULL, NULL) AS result;
 
 -- bms_copy()
 SELECT test_bms_copy(NULL) AS result;
 SELECT test_bms_copy('(b 1 3 5 7)') AS result;
--- Test module check
-SELECT test_bms_copy(NULL) AS result;
 
 -- bms_add_members()
 SELECT test_bms_add_members('(b 1 3)', '(b 5 7)') AS result;
@@ -371,8 +322,6 @@ SELECT test_bitmap_hash('(b)') = 0 AS result;
 SELECT test_bitmap_hash('(b 1 3 5)') = test_bitmap_hash('(b 1 3 5)') AS result;
 SELECT test_bitmap_hash('(b 1 3 5)') = test_bms_hash_value('(b 1 3 5)') AS result;
 SELECT test_bitmap_hash('(b 1 3 5)') != test_bitmap_hash('(b 2 4 6)') AS result;
--- Test module check
-SELECT test_bitmap_hash(NULL) AS result;
 
 -- bitmap_match()
 SELECT test_bitmap_match('(b)', '(b)') AS result;
@@ -388,10 +337,6 @@ SELECT (test_bitmap_match('(b 1 3 5)', '(b 2 4 6)') = 0) =
         test_bms_equal('(b 1 3 5)', '(b 2 4 6)') AS result;
 SELECT (test_bitmap_match('(b)', '(b)') = 0) =
         test_bms_equal('(b)', '(b)') AS result;
--- Test module checks
-SELECT test_bitmap_match('(b 5)', NULL) AS result;
-SELECT test_bitmap_match(NULL, '(b 5)') AS result;
-SELECT test_bitmap_match(NULL, NULL) AS result;
 
 -- bms_overlap_list()
 SELECT test_bms_overlap_list('(b 0)', ARRAY[0]) AS result;
@@ -419,10 +364,6 @@ SELECT test_bms_nonempty_difference('(b 1 3 5)', '(b 1 3 5)') AS result;
 SELECT test_bms_nonempty_difference('(b 5)', '(b 100)') AS result;
 SELECT test_bms_nonempty_difference('(b 100)', '(b 5)') AS result;
 SELECT test_bms_nonempty_difference('(b 1 2)', '(b 50 100)') AS result;
--- Test module checks
-SELECT test_bms_nonempty_difference('(b 5)', NULL) AS result;
-SELECT test_bms_nonempty_difference(NULL, '(b 5)') AS result;
-SELECT test_bms_nonempty_difference(NULL, NULL) AS result;
 
 -- random operations
 SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
diff --git a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
index b95c4d0dda5..227ecb5aa3b 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
+++ b/src/test/modules/test_bitmapset/test_bitmapset--1.0.sql
@@ -68,7 +68,7 @@ CREATE FUNCTION test_bms_singleton_member(text)
 RETURNS integer STRICT
 AS 'MODULE_PATHNAME' LANGUAGE C;
 
-CREATE FUNCTION test_bms_get_singleton_member(text, integer)
+CREATE FUNCTION test_bms_get_singleton_member(text)
 RETURNS integer
 AS 'MODULE_PATHNAME' LANGUAGE C;
 
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 2e821320836..06f15a5d065 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -26,7 +26,6 @@
 #include "nodes/pg_list.h"
 #include "utils/builtins.h"
 #include "utils/timestamp.h"
-#include "varatt.h"
 
 PG_MODULE_MAGIC;
 
@@ -88,101 +87,93 @@ PG_FUNCTION_INFO_V1(test_random_operations);
 #define BITMAPSET_TO_TEXT(bms) cstring_to_text(nodeToString(bms))
 #define TEXT_TO_BITMAPSET(str) ((Bitmapset *) stringToNode(text_to_cstring(str)))
 
+/* Helper macro to fetch Text parameters as Bitmapsets. SQL-NULL means empty set */
+#define PG_ARG_GETBITMAPSET(n) \
+	(PG_ARGISNULL(n) ? NULL : TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(n)))
+
+/*
+ * Helper macro to handle converting sets back to text, returning the
+ * resulting text representation of the set.
+ */
+#define PG_RETURN_BITMAPSET_AS_TEXT(bms) \
+	PG_RETURN_TEXT_P(BITMAPSET_TO_TEXT(bms))
+
 /*
  * Individual test functions for each bitmapset API function
+ *
+ * Primarily, we aim to keep these as close to simple wrapper functions as
+ * possible in order to publish the functions of bitmapset.c to the SQL layer
+ * with as little interference as possible.  We opt to return SQL NULL in
+ * cases where the input given to the SQL function isn't valid to pass to the
+ * underlying bitmapset.c function.  For example, we cannot do much useful
+ * testing if someone calls test_bms_make_singleton(NULL) since
+ * bms_make_singleton() expects an integer argument.
+ *
+ * For function arguments which are to be converted to Bitmapsets, we accept
+ * SQL NULL as a valid argument to mean an empty set.  Optionally, callers may
+ * pass '(b)'.
  */
 
 Datum
 test_bms_add_member(PG_FUNCTION_ARGS)
 {
+	Bitmapset  *bms;
 	int			member;
-	Bitmapset  *bms = NULL;
-	text	   *result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_NULL();
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
-	bms = bms_add_member(bms, member);
-	result = BITMAPSET_TO_TEXT(bms);
 
-	if (bms)
-		bms_free(bms);
+	bms = bms_add_member(bms, member);
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_add_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* IMPORTANT: bms_add_members modifies/frees the first argument */
+	/* left input is recycled */
 	bms1 = bms_add_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
-
-	result = BITMAPSET_TO_TEXT(bms1);
-	bms_free(bms1);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_del_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		member;
-	text	   *result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_NULL();
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
-	bms = bms_del_member(bms, member);
 
-	if (bms_is_empty(bms))
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(bms);
-	bms_free(bms);
+	bms = bms_del_member(bms, member);
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_is_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		member;
 	bool		result;
 
 	if (PG_ARGISNULL(1))
-		PG_RETURN_BOOL(false);
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
-	result = bms_is_member(member, bms);
 
-	if (bms)
-		bms_free(bms);
+	result = bms_is_member(member, bms);
 
 	PG_RETURN_BOOL(result);
 }
@@ -190,150 +181,89 @@ test_bms_is_member(PG_FUNCTION_ARGS)
 Datum
 test_bms_num_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
-	int			result = 0;
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
+	int			result;
 
 	result = bms_num_members(bms);
 
-	if (bms)
-		bms_free(bms);
-
 	PG_RETURN_INT32(result);
 }
 
 Datum
 test_bms_make_singleton(PG_FUNCTION_ARGS)
 {
-	int32		member;
 	Bitmapset  *bms;
-	text	   *result;
+	int32		member;
 
 	if (PG_ARGISNULL(0))
-		PG_RETURN_NULL();
+		PG_RETURN_NULL();		/* invalid input */
 
 	member = PG_GETARG_INT32(0);
 	bms = bms_make_singleton(member);
 
-	result = BITMAPSET_TO_TEXT(bms);
-	bms_free(bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_copy(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	Bitmapset  *copy_bms;
-	text	   *result;
-
-	if (PG_ARGISNULL(0))
-		PG_RETURN_NULL();
 
-	bms_data = PG_GETARG_TEXT_PP(0);
-	bms = TEXT_TO_BITMAPSET(bms_data);
 	copy_bms = bms_copy(bms);
-	result = BITMAPSET_TO_TEXT(copy_bms);
 
-	if (bms)
-		bms_free(bms);
-	if (copy_bms)
-		bms_free(copy_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(copy_bms);
 }
 
 Datum
 test_bms_equal(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_equal(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
 	PG_RETURN_BOOL(result);
 }
 
 Datum
 test_bms_union(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
 
 	result_bms = bms_union(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_membership(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	BMS_Membership result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(BMS_EMPTY_SET);
-
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 	result = bms_membership(bms);
 
-	if (bms)
-		bms_free(bms);
-
 	PG_RETURN_INT32((int32) result);
 }
 
 Datum
 test_bms_next_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		prevmember;
 	int			result;
 
-	if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
-		PG_RETURN_INT32(-2);
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();		/* invalid input */
 
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	bms = PG_ARG_GETBITMAPSET(0);
 	prevmember = PG_GETARG_INT32(1);
-	result = bms_next_member(bms, prevmember);
 
-	if (bms)
-		bms_free(bms);
+	result = bms_next_member(bms, prevmember);
 
 	PG_RETURN_INT32(result);
 }
@@ -341,212 +271,115 @@ test_bms_next_member(PG_FUNCTION_ARGS)
 Datum
 test_bms_intersect(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
 
 	result_bms = bms_intersect(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_difference(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
 
 	result_bms = bms_difference(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_compare(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	int			result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_compare(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
 	PG_RETURN_INT32(result);
 }
 
 Datum
 test_bms_is_empty(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
 	result = bms_is_empty(bms);
 
-	if (bms)
-		bms_free(bms);
-
 	PG_RETURN_BOOL(result);
 }
 
 Datum
 test_bms_is_subset(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_is_subset(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
 	PG_RETURN_BOOL(result);
 }
 
 Datum
 test_bms_subset_compare(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	BMS_Comparison result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_subset_compare(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
 	PG_RETURN_INT32((int32) result);
 }
 
 Datum
 test_bms_singleton_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	int			result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
 	result = bms_singleton_member(bms);
 
-	if (bms)
-		bms_free(bms);
-
 	PG_RETURN_INT32(result);
 }
 
 Datum
 test_bms_get_singleton_member(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
-	int32		default_member = PG_GETARG_INT32(1);
-	bool		success;
-	int			member = -1;
-
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(default_member);
-
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
+	int			member;
 
 	/*
-	 * bms_get_singleton_member returns bool and stores result in member
-	 * pointer
+	 * Keep this simple.  Return -1 when we detect the set isn't a singleton
+	 * set, otherwise return the singleton member.
 	 */
-	success = bms_get_singleton_member(bms, &member);
-	bms_free(bms);
-
-	if (success)
-		PG_RETURN_INT32(member);
+	if (!bms_get_singleton_member(bms, &member))
+		member = -1;
 
-	PG_RETURN_INT32(default_member);
+	PG_RETURN_INT32(member);
 }
 
 Datum
 test_bms_prev_member(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		prevmember;
 	int			result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(-2);
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();		/* invalid input */
 
-	bms_data = PG_GETARG_TEXT_PP(0);
+	bms = PG_ARG_GETBITMAPSET(0);
 	prevmember = PG_GETARG_INT32(1);
 
-	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
-		PG_RETURN_INT32(-2);
-
-	bms = TEXT_TO_BITMAPSET(bms_data);
 	result = bms_prev_member(bms, prevmember);
-	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -554,75 +387,57 @@ test_bms_prev_member(PG_FUNCTION_ARGS)
 Datum
 test_bms_overlap(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_overlap(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
 	PG_RETURN_BOOL(result);
 }
 
 Datum
 test_bms_overlap_list(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	ArrayType  *array;
 	List	   *int_list = NIL;
 	bool		result;
-	Datum	   *elem_datums;
-	bool	   *elem_nulls;
+	Datum	   *elem_datums = NULL;
+	bool	   *elem_nulls = NULL;
 	int			elem_count;
 	int			i;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_BOOL(false);
-
-	bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	bms = PG_ARG_GETBITMAPSET(0);
 
-	if (PG_ARGISNULL(1))
+	if (!PG_ARGISNULL(1))
 	{
-		if (bms)
-			bms_free(bms);
-		PG_RETURN_BOOL(false);
-	}
+		array = PG_GETARG_ARRAYTYPE_P(1);
 
-	array = PG_GETARG_ARRAYTYPE_P(1);
+		deconstruct_array(array,
+						  INT4OID, sizeof(int32), true, 'i',
+						  &elem_datums, &elem_nulls, &elem_count);
 
-	deconstruct_array(array,
-					  INT4OID, sizeof(int32), true, 'i',
-					  &elem_datums, &elem_nulls, &elem_count);
-
-	for (i = 0; i < elem_count; i++)
-	{
-		if (!elem_nulls[i])
+		for (i = 0; i < elem_count; i++)
 		{
-			int32		member = DatumGetInt32(elem_datums[i]);
+			if (!elem_nulls[i])
+			{
+				int32		member = DatumGetInt32(elem_datums[i]);
 
-			int_list = lappend_int(int_list, member);
+				int_list = lappend_int(int_list, member);
+			}
 		}
 	}
 
 	result = bms_overlap_list(bms, int_list);
 
-	if (bms)
-		bms_free(bms);
-
 	list_free(int_list);
 
-	pfree(elem_datums);
-	pfree(elem_nulls);
+	if (elem_datums)
+		pfree(elem_datums);
+
+	if (elem_nulls)
+		pfree(elem_nulls);
 
 	PG_RETURN_BOOL(result);
 }
@@ -630,47 +445,29 @@ test_bms_overlap_list(PG_FUNCTION_ARGS)
 Datum
 test_bms_nonempty_difference(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	bool		result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
 	result = bms_nonempty_difference(bms1, bms2);
 
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
-
 	PG_RETURN_BOOL(result);
 }
 
 Datum
 test_bms_member_index(PG_FUNCTION_ARGS)
 {
-	text	   *bms_data;
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		member;
 	int			result;
 
-	if (PG_ARGISNULL(0))
-		PG_RETURN_INT32(-1);
+	if (PG_ARGISNULL(1))
+		PG_RETURN_NULL();		/* invalid input */
 
-	bms_data = PG_GETARG_TEXT_PP(0);
+	bms = PG_ARG_GETBITMAPSET(0);
 	member = PG_GETARG_INT32(1);
 
-	if (VARSIZE_ANY_EXHDR(bms_data) == 0)
-		PG_RETURN_INT32(-1);
-
-	bms = TEXT_TO_BITMAPSET(bms_data);
-
 	result = bms_member_index(bms, member);
-	bms_free(bms);
 
 	PG_RETURN_INT32(result);
 }
@@ -678,191 +475,92 @@ test_bms_member_index(PG_FUNCTION_ARGS)
 Datum
 test_bms_add_range(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms;
 	int32		lower,
 				upper;
-	text	   *result;
 
 	if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
-		PG_RETURN_NULL();
-
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+		PG_RETURN_NULL();		/* invalid input */
 
+	bms = PG_ARG_GETBITMAPSET(0);
 	lower = PG_GETARG_INT32(1);
 	upper = PG_GETARG_INT32(2);
 
-	/* Check for invalid range */
-	if (upper < lower)
-	{
-		if (bms)
-			bms_free(bms);
-		PG_RETURN_NULL();
-	}
-
 	bms = bms_add_range(bms, lower, upper);
 
-	result = BITMAPSET_TO_TEXT(bms);
-	if (bms)
-		bms_free(bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms);
 }
 
 Datum
 test_bms_int_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
+	/* left input gets recycled */
 	bms1 = bms_int_members(bms1, bms2);
 
-	if (bms2)
-		bms_free(bms2);
-
-	if (bms1 == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(bms1);
-
-	if (bms1)
-		bms_free(bms1);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_del_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	Bitmapset  *result_bms;
-	text	   *result;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
+	/* left input gets recycled */
+	bms1 = bms_del_members(bms1, bms2);
 
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* IMPORTANT: bms_del_members modifies/frees the first argument */
-	result_bms = bms_del_members(bms1, bms2);
-
-	/* bms1 is now invalid, do not free it */
-
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_replace_members(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 
-	/* IMPORTANT: bms_replace_members modifies/frees the first argument */
-	result_bms = bms_replace_members(bms1, bms2);
+	/* left input gets recycled */
+	bms1 = bms_replace_members(bms1, bms2);
 
-	/* bms1 is now invalid, do not free it */
-
-	if (bms2)
-		bms_free(bms2);
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
-
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(bms1);
 }
 
 Datum
 test_bms_join(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	Bitmapset  *result_bms;
-	text	   *result;
-
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
 
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* IMPORTANT: bms_join may recycle either input arguments */
+	/* either input can be recycled */
 	result_bms = bms_join(bms1, bms2);
 
-	/* bms1 and bms2 may have been recycled! Do not free any of them. */
-
-	if (result_bms == NULL)
-		PG_RETURN_NULL();
-
-	result = BITMAPSET_TO_TEXT(result_bms);
-	bms_free(result_bms);
+	/* memory cleanup seems more tricky than it's worth here */
 
-	PG_RETURN_TEXT_P(result);
+	PG_RETURN_BITMAPSET_AS_TEXT(result_bms);
 }
 
 Datum
 test_bms_hash_value(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	uint32		hash_result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
 	hash_result = bms_hash_value(bms);
 
-	if (bms)
-		bms_free(bms);
-
 	PG_RETURN_INT32(hash_result);
 }
 
 Datum
 test_bitmap_hash(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms = NULL;
-	Bitmapset  *bms_ptr;
+	Bitmapset  *bms = PG_ARG_GETBITMAPSET(0);
 	uint32		hash_result;
 
-	if (!PG_ARGISNULL(0))
-		bms = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	bms_ptr = bms;
-
 	/* Call bitmap_hash */
-	hash_result = bitmap_hash(&bms_ptr, sizeof(Bitmapset *));
-
-	/* Clean up */
-	if (!PG_ARGISNULL(0) && bms_ptr)
-		bms_free(bms_ptr);
+	hash_result = bitmap_hash(&bms, sizeof(Bitmapset *));
 
 	PG_RETURN_INT32(hash_result);
 }
@@ -870,30 +568,12 @@ test_bitmap_hash(PG_FUNCTION_ARGS)
 Datum
 test_bitmap_match(PG_FUNCTION_ARGS)
 {
-	Bitmapset  *bms1 = NULL,
-			   *bms2 = NULL;
-	Bitmapset  *bms_ptr1,
-			   *bms_ptr2;
+	Bitmapset  *bms1 = PG_ARG_GETBITMAPSET(0);
+	Bitmapset  *bms2 = PG_ARG_GETBITMAPSET(1);
 	int			match_result;
 
-	if (!PG_ARGISNULL(0))
-		bms1 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(0));
-
-	if (!PG_ARGISNULL(1))
-		bms2 = TEXT_TO_BITMAPSET(PG_GETARG_TEXT_PP(1));
-
-	/* Set up pointers to the Bitmapsets */
-	bms_ptr1 = bms1;
-	bms_ptr2 = bms2;
-
 	/* Call bitmap_match with addresses of the Bitmapset pointers */
-	match_result = bitmap_match(&bms_ptr1, &bms_ptr2, sizeof(Bitmapset *));
-
-	/* Clean up */
-	if (bms1)
-		bms_free(bms1);
-	if (bms2)
-		bms_free(bms2);
+	match_result = bitmap_match(&bms1, &bms2, sizeof(Bitmapset *));
 
 	PG_RETURN_INT32(match_result);
 }
@@ -1031,8 +711,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 		total_ops++;
 	}
 
-	if (bms)
-		bms_free(bms);
+	bms_free(bms);
 
 	PG_RETURN_INT32(total_ops);
 }
#53Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#51)
Re: [PATCH] Add tests for Bitmapset

On Wed, Oct 01, 2025 at 06:00:59PM +1300, David Rowley wrote:

I didn't look at the coverage report, but on thinking about it,
test_bitmapset.c's "PG_RETURN_NULL(); /* invalid input */" won't be
covered as I stripped out all the tests which purposefully pass
invalid input. You may not want it that way if you're keen to keep the
coverage of the test module high as well as bitmapset.c

Yes, that's something I was just going through, with a result pretty
close to what you have sent, including the removal and replacement of
most of tests that were specific to the test module. The prev/next
member coverage is still looking OK from here, though.

Thanks for the typos, I've missed these.
--
Michael

#54Greg Burd
greg@burd.me
In reply to: Michael Paquier (#53)
Re: [PATCH] Add tests for Bitmapset

On Oct 1 2025, at 1:14 am, Michael Paquier <michael@paquier.xyz> wrote:

On Wed, Oct 01, 2025 at 06:00:59PM +1300, David Rowley wrote:

I didn't look at the coverage report, but on thinking about it,
test_bitmapset.c's "PG_RETURN_NULL(); /* invalid input */" won't be
covered as I stripped out all the tests which purposefully pass
invalid input. You may not want it that way if you're keen to keep the
coverage of the test module high as well as bitmapset.c

Yes, that's something I was just going through, with a result pretty
close to what you have sent, including the removal and replacement of
most of tests that were specific to the test module. The prev/next
member coverage is still looking OK from here, though.

Thanks for the typos, I've missed these.
--
Michael

Michael, David,

Thank you. :)

The coverage[1]https://coverage.postgresql.org/src/backend/nodes/bitmapset.c.gcov.html looks to be 100% for everything in bitmapset.c now and
98.6% of the test code[2]https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html for Bitmapset -- more than enough and much
better than before. I do like the cleanup/simplification that you two
jointly applied. I think it's easier to maintain and reason about and
looking at the final result I can see the logic in the simplified
approach. I've learned a lot from this exercise not only about
Bitmapset and various other areas in the code but also the
approach/model for a task like this. I'll keep that in mind going forward.

best.

-greg

[1]: https://coverage.postgresql.org/src/backend/nodes/bitmapset.c.gcov.html
[2]: https://coverage.postgresql.org/src/test/modules/test_bitmapset/test_bitmapset.c.gcov.html

#55Daniel Gustafsson
daniel@yesql.se
In reply to: Michael Paquier (#53)
Re: [PATCH] Add tests for Bitmapset

On 1 Oct 2025, at 07:14, Michael Paquier <michael@paquier.xyz> wrote:

Thanks for the typos, I've missed these.

Doing post-commit review I didn't see any sharp edges, but found one more of
these so will push this shortly:

--- Substraction to empty
+-- Subtraction to empty

--
Daniel Gustafsson

#56Greg Burd
greg@burd.me
In reply to: Daniel Gustafsson (#55)
Re: [PATCH] Add tests for Bitmapset

On Oct 2 2025, at 6:00 am, Daniel Gustafsson <daniel@yesql.se> wrote:

On 1 Oct 2025, at 07:14, Michael Paquier <michael@paquier.xyz> wrote:

Thanks for the typos, I've missed these.

Doing post-commit review I didn't see any sharp edges, but found one
more of
these so will push this shortly:

--- Substraction to empty
+-- Subtraction to empty

+1, thanks. I'll be more careful in the future.

--
Daniel Gustafsson

best.

-greg

#57David Rowley
dgrowleyml@gmail.com
In reply to: Daniel Gustafsson (#55)
Re: [PATCH] Add tests for Bitmapset

On Thu, 2 Oct 2025 at 23:00, Daniel Gustafsson <daniel@yesql.se> wrote:

Doing post-commit review I didn't see any sharp edges, but found one more of
these so will push this shortly:

Any chance you could also delete the "/* memory cleanup seems more
tricky than it's worth here */" line? That comment seemed relevant
when we were actually doing bms_free() in the functions. Now that
we're not, it's a bit out of place.

David

#58Daniel Gustafsson
daniel@yesql.se
In reply to: David Rowley (#57)
Re: [PATCH] Add tests for Bitmapset

On 2 Oct 2025, at 14:11, David Rowley <dgrowleyml@gmail.com> wrote:

On Thu, 2 Oct 2025 at 23:00, Daniel Gustafsson <daniel@yesql.se> wrote:

Doing post-commit review I didn't see any sharp edges, but found one more of
these so will push this shortly:

Any chance you could also delete the "/* memory cleanup seems more
tricky than it's worth here */" line? That comment seemed relevant
when we were actually doing bms_free() in the functions. Now that
we're not, it's a bit out of place.

Sure I can take care of that while in there.

Another nitpick would be to remove the test for NULL in test_bms_make_singleton
since that is a STRICT function, making the test for NULL superfluous code:

diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 0d6c2e7aa1b..acaa93d2f11 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -201,9 +201,6 @@ test_bms_make_singleton(PG_FUNCTION_ARGS)
        Bitmapset  *bms;
        int32           member;

- if (PG_ARGISNULL(0))
- PG_RETURN_NULL(); /* invalid input */
-
member = PG_GETARG_INT32(0);
bms = bms_make_singleton(member);

I'll include all of these three tiny improvements in a commit later today.

--
Daniel Gustafsson

#59David Rowley
dgrowleyml@gmail.com
In reply to: Daniel Gustafsson (#58)
Re: [PATCH] Add tests for Bitmapset

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se> wrote:

Another nitpick would be to remove the test for NULL in test_bms_make_singleton
since that is a STRICT function, making the test for NULL superfluous code:

I didn't notice that was marked as strict. It would be good to get rid
of those lines in that case.

Thanks

David

#60Daniel Gustafsson
daniel@yesql.se
In reply to: David Rowley (#59)
Re: [PATCH] Add tests for Bitmapset

On 2 Oct 2025, at 23:00, David Rowley <dgrowleyml@gmail.com> wrote:

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se> wrote:

Another nitpick would be to remove the test for NULL in test_bms_make_singleton
since that is a STRICT function, making the test for NULL superfluous code:

I didn't notice that was marked as strict. It would be good to get rid
of those lines in that case.

Done, comment cleanup and nullness check pushed.

--
Daniel Gustafsson

#61David Rowley
dgrowleyml@gmail.com
In reply to: Daniel Gustafsson (#58)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se> wrote:

Another nitpick would be to remove the test for NULL in test_bms_make_singleton
since that is a STRICT function, making the test for NULL superfluous code:

I see test_random_operations() is also strict. Is it worth getting rid
of the SQL NULL checks on the inputs there too? Aka, the attached.

David

Attachments:

test_random_operations_is_strict_no_need_to_check_for_null_inputs.patchapplication/octet-stream; name=test_random_operations_is_strict_no_need_to_check_for_null_inputs.patchDownload
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index acaa93d2f11..8bc9b1f48e9 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -587,7 +587,7 @@ test_bitmap_match(PG_FUNCTION_ARGS)
  * "min_value" is the minimal value used for the members, that will stand
  * up to a range of "max_range".  "num_ops" defines the number of time each
  * operation is done.  "seed" is a random seed used to calculate the member
- * values.
+ * values.  When "seed" is <= 0, a random seed will be chosen automatically.
  *
  * The return value is the number of times all operations have been executed.
  */
@@ -600,25 +600,20 @@ test_random_operations(PG_FUNCTION_ARGS)
 	Bitmapset  *result = NULL;
 	pg_prng_state state;
 	uint64		seed = GetCurrentTimestamp();
-	int			num_ops = 5000;
-	int			total_ops = 0;
-	int			max_range = 2000;
-	int			min_value = 0;
+	int			num_ops;
+	int			max_range;
+	int			min_value;
 	int			member;
 	int		   *members;
 	int			num_members = 0;
+	int			total_ops = 0;
 
-	if (!PG_ARGISNULL(0) && PG_GETARG_INT32(0) > 0)
+	if (PG_GETARG_INT32(0) > 0)
 		seed = PG_GETARG_INT32(0);
 
-	if (!PG_ARGISNULL(1))
-		num_ops = PG_GETARG_INT32(1);
-
-	if (!PG_ARGISNULL(2))
-		max_range = PG_GETARG_INT32(2);
-
-	if (!PG_ARGISNULL(3))
-		min_value = PG_GETARG_INT32(3);
+	num_ops = PG_GETARG_INT32(1);
+	max_range = PG_GETARG_INT32(2);
+	min_value = PG_GETARG_INT32(3);
 
 	pg_prng_seed(&state, seed);
 	members = palloc(sizeof(int) * num_ops);
#62Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#61)
Re: [PATCH] Add tests for Bitmapset

On Fri, Oct 03, 2025 at 12:36:57PM +1300, David Rowley wrote:

I see test_random_operations() is also strict. Is it worth getting rid
of the SQL NULL checks on the inputs there too? Aka, the attached.

Yes, this was not bothering me much. Anyway, agreed about removing
these as well. I cannot find an argument in favor of making the
function callable on NULL input with default values that are hardcoded
internally in the function.

Thanks, David and Daniel.
--
Michael

#63Daniel Gustafsson
daniel@yesql.se
In reply to: David Rowley (#61)
Re: [PATCH] Add tests for Bitmapset

On 3 Oct 2025, at 01:36, David Rowley <dgrowleyml@gmail.com> wrote:

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se> wrote:

Another nitpick would be to remove the test for NULL in test_bms_make_singleton
since that is a STRICT function, making the test for NULL superfluous code:

I see test_random_operations() is also strict. Is it worth getting rid
of the SQL NULL checks on the inputs there too? Aka, the attached.

Indeed, but reading the code I wonder if STRICT was a mistake and the intention
was to allow NULL input? That being said, the function is never called with
NULL so that's mostly academic thinking. +1 for removing the NULL checks and
simplifying the code.

--
Daniel Gustafsson

#64David Rowley
dgrowleyml@gmail.com
In reply to: Daniel Gustafsson (#63)
Re: [PATCH] Add tests for Bitmapset

On Fri, 3 Oct 2025 at 21:26, Daniel Gustafsson <daniel@yesql.se> wrote:

+1 for removing the NULL checks and
simplifying the code.

Thank you both for looking. Pushed.

David

#65Greg Burd
greg@burd.me
In reply to: Daniel Gustafsson (#63)
Re: [PATCH] Add tests for Bitmapset

On Oct 3 2025, at 4:25 am, Daniel Gustafsson <daniel@yesql.se> wrote:

On 3 Oct 2025, at 01:36, David Rowley <dgrowleyml@gmail.com> wrote:

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se> wrote:

Another nitpick would be to remove the test for NULL in test_bms_make_singleton
since that is a STRICT function, making the test for NULL
superfluous code:

I see test_random_operations() is also strict. Is it worth getting rid
of the SQL NULL checks on the inputs there too? Aka, the attached.

Indeed, but reading the code I wonder if STRICT was a mistake and the intention
was to allow NULL input?

Yes, it was an oversight after I re-worked the random function.

That being said, the function is never called with
NULL so that's mostly academic thinking. +1 for removing the NULL
checks and simplifying the code.

I agree, and thank you both for the attention to detail and interest in
this test suite.

--
Daniel Gustafsson

best.

-greg

#66Ranier Vilela
ranier.vf@gmail.com
In reply to: Greg Burd (#65)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

Hi.

Em sex., 3 de out. de 2025 às 09:13, Greg Burd <greg@burd.me> escreveu:

On Oct 3 2025, at 4:25 am, Daniel Gustafsson <daniel@yesql.se> wrote:

On 3 Oct 2025, at 01:36, David Rowley <dgrowleyml@gmail.com> wrote:

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se> wrote:

Another nitpick would be to remove the test for NULL in

test_bms_make_singleton

since that is a STRICT function, making the test for NULL
superfluous code:

I see test_random_operations() is also strict. Is it worth getting rid
of the SQL NULL checks on the inputs there too? Aka, the attached.

Indeed, but reading the code I wonder if STRICT was a mistake and the

intention

was to allow NULL input?

Yes, it was an oversight after I re-worked the random function.

That being said, the function is never called with
NULL so that's mostly academic thinking. +1 for removing the NULL
checks and simplifying the code.

I agree, and thank you both for the attention to detail and interest in
this test suite.

With the patch attached, there are regression.
Is it intentional not to check the return of the function bms_is_member?

diff --strip-trailing-cr -U3
C:/dll/postgres_dev/postgres_commit/src/test/modules/test_bitmapset/expected/test_bitmapset.out
C:/dll/postgres_dev/postgres_commit/build/testrun/test_bitmapset/regress/results/test_bitmapset.out
---
C:/dll/postgres_dev/postgres_commit/src/test/modules/test_bitmapset/expected/test_bitmapset.out
2025-10-02 21:17:53.169515700 -0300
+++
C:/dll/postgres_dev/postgres_commit/build/testrun/test_bitmapset/regress/results/test_bitmapset.out
2025-10-07 21:24:00.534142300 -0300
@@ -1570,9 +1570,5 @@
 -- random operations
 SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
- result
---------
- t
-(1 row)
-
+ERROR:  union missing member 63904
 DROP EXTENSION test_bitmapset;

best regards,
Ranier Vilela

Attachments:

check-function-return-bms_is_member.txttext/plain; charset=US-ASCII; name=check-function-return-bms_is_member.txtDownload
diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 8bc9b1f48e..9e757732c5 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -700,7 +700,8 @@ test_random_operations(PG_FUNCTION_ARGS)
 			case 2:				/* test membership */
 				if (bms != NULL)
 				{
-					bms_is_member(member, bms);
+					if (!bms_is_member(member, bms))
+						elog(ERROR, "union missing member %d", member);
 				}
 				break;
 		}
#67Greg Burd
greg@burd.me
In reply to: Ranier Vilela (#66)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Oct 8 2025, at 8:10 am, Ranier Vilela <ranier.vf@gmail.com> wrote:

Hi.

Em sex., 3 de out. de 2025 às 09:13, Greg Burd <greg@burd.me> escreveu:

On Oct 3 2025, at 4:25 am, Daniel Gustafsson <daniel@yesql.se> wrote:

On 3 Oct 2025, at 01:36, David Rowley <dgrowleyml@gmail.com> wrote:

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se> wrote:

Another nitpick would be to remove the test for NULL in test_bms_make_singleton
since that is a STRICT function, making the test for NULL
superfluous code:

I see test_random_operations() is also strict. Is it worth getting rid
of the SQL NULL checks on the inputs there too? Aka, the attached.

Indeed, but reading the code I wonder if STRICT was a mistake and
the intention
was to allow NULL input?

Yes, it was an oversight after I re-worked the random function.

That being said, the function is never called with
NULL so that's mostly academic thinking.  +1 for removing the NULL
checks and simplifying the code.

I agree, and thank you both for the attention to detail and interest in
this test suite.

With the patch attached, there are regression.
Is it intentional not to check the return of the function bms_is_member?

diff --strip-trailing-cr -U3
C:/dll/postgres_dev/postgres_commit/src/test/modules/test_bitmapset/expected/test_bitmapset.out C:/dll/postgres_dev/postgres_commit/build/testrun/test_bitmapset/regress/results/test_bitmapset.out
---
C:/dll/postgres_dev/postgres_commit/src/test/modules/test_bitmapset/expected/test_bitmapset.out
2025-10-02 21:17:53.169515700 -0300
+++
C:/dll/postgres_dev/postgres_commit/build/testrun/test_bitmapset/regress/results/test_bitmapset.out
2025-10-07 21:24:00.534142300 -0300
@@ -1570,9 +1570,5 @@
 
 -- random operations
 SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
- result
---------
- t
-(1 row)
-
+ERROR:  union missing member 63904
 DROP EXTENSION test_bitmapset;
 
best regards,
Ranier Vilela

Thanks Ranier for the report.

You're correct, the tests I wrote overlooked testing the return value
and so were not accomplishing the goal of testing at all.

Adding your small suggested patched turned over another flaw. The error
message you were seeing was from later in that same function.

+ERROR:  union missing member 63904

This was emitted by the code in the second portion of the randomized
testing where there is a loop doing add/del/test operations. That error
message was misleading as it matched the earlier error message near the
change you made.

But, thankfully that pointed to a second (face palm) flaw in that
function (again, I take full credit/blame). The add/del/test loop
wasn't accumulating the anticipated set of members and so was testing if
the latest random int generated was in the set or not, which makes no
sense. I've updated that loop to retain the list of members and the
test to check against the retained list of members. I've updated the
log message to be different from those above to avoid similar confusion
in the future.

This seems to be passing now, apologies for not paying closer attention
to this code earlier on.

best.

-greg

Attachments:

v1-0001-Correct-flaws-in-randomized-Bitmapset-tests.patchapplication/octet-streamDownload
From ecfe770d4ef8139d6f852dde5037a7eb51715e89 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 8 Oct 2025 14:27:30 -0400
Subject: [PATCH v1] Correct flaws in randomized Bitmapset tests

There were two oversights in the function designated to perform
randomized tests against Bitmapset.  First, the test validating
bms_union() was not checking the return from bms_is_member() and so
wasn't testing much at all.  Second, in the second half of this function
performing randomized operations there was no tracking of what members
should exist after some number of random add/del operations.  This patch
addresses both of those issues.

Reported-by: Ranier Vilela<ranier.vf@gmail.com>
Discussion: https://postgr.es/m/CAApHDvqghMnm_zgSNefto9oaEJ0S-3Cgb3gdsV7XvLC-hMS02Q@mail.gmail.com
---
 .../modules/test_bitmapset/test_bitmapset.c   | 31 ++++++++++++++-----
 1 file changed, 23 insertions(+), 8 deletions(-)

diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 8bc9b1f48e9..00651cb8df1 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -624,10 +624,8 @@ test_random_operations(PG_FUNCTION_ARGS)
 		member = pg_prng_uint32(&state) % max_range + min_value;
 
 		if (!bms_is_member(member, bms1))
-		{
 			members[num_members++] = member;
-			bms1 = bms_add_member(bms1, member);
-		}
+		bms1 = bms_add_member(bms1, member);
 	}
 
 	/* Phase 2: Random set operations */
@@ -635,6 +633,8 @@ test_random_operations(PG_FUNCTION_ARGS)
 	{
 		member = pg_prng_uint32(&state) % max_range + min_value;
 
+		if (!bms_is_member(member, bms1) && !bms_is_member(member, bms2))
+			members[num_members++] = member;
 		bms2 = bms_add_member(bms2, member);
 	}
 
@@ -683,24 +683,39 @@ test_random_operations(PG_FUNCTION_ARGS)
 	bms_free(bms1);
 	bms_free(bms2);
 
-	for (int i = 0; i < num_ops; i++)
+	num_members = 0;
+	members = palloc(sizeof(int) * num_ops);
+
+	for (int op = 0; op < num_ops; op++)
 	{
-		member = pg_prng_uint32(&state) % max_range + min_value;
 		switch (pg_prng_uint32(&state) % 3)
 		{
 			case 0:				/* add */
+				member = pg_prng_uint32(&state) % max_range + min_value;
+				if (!bms_is_member(member, bms))
+					members[num_members++] = member;
 				bms = bms_add_member(bms, member);
 				break;
 			case 1:				/* delete */
-				if (bms != NULL)
+				if (num_members > 0)
 				{
+					int			pos = pg_prng_uint32(&state) % num_members;
+
+					member = members[pos];
+					if (!bms_is_member(member, bms))
+						elog(ERROR, "expected %d to be a valid member", member);
 					bms = bms_del_member(bms, member);
+					num_members--;
+					memmove(members + pos, members + pos + 1,
+							(num_members - pos) * sizeof(int));
 				}
 				break;
 			case 2:				/* test membership */
-				if (bms != NULL)
+				/* Verify bitmap contains all members */
+				for (int i = 0; i < num_members; i++)
 				{
-					bms_is_member(member, bms);
+					if (!bms_is_member(members[i], bms))
+						elog(ERROR, "missing member %d", members[i]);
 				}
 				break;
 		}
-- 
2.49.0

#68Ranier Vilela
ranier.vf@gmail.com
In reply to: Greg Burd (#67)
Re: [PATCH] Add tests for Bitmapset

Em qua., 8 de out. de 2025 às 15:48, Greg Burd <greg@burd.me> escreveu:

On Oct 8 2025, at 8:10 am, Ranier Vilela <ranier.vf@gmail.com> wrote:

Hi.

Em sex., 3 de out. de 2025 às 09:13, Greg Burd <greg@burd.me> escreveu:

On Oct 3 2025, at 4:25 am, Daniel Gustafsson <daniel@yesql.se> wrote:

On 3 Oct 2025, at 01:36, David Rowley <dgrowleyml@gmail.com> wrote:

On Fri, 3 Oct 2025 at 01:33, Daniel Gustafsson <daniel@yesql.se>

wrote:

Another nitpick would be to remove the test for NULL in

test_bms_make_singleton

since that is a STRICT function, making the test for NULL
superfluous code:

I see test_random_operations() is also strict. Is it worth getting

rid

of the SQL NULL checks on the inputs there too? Aka, the attached.

Indeed, but reading the code I wonder if STRICT was a mistake and
the intention
was to allow NULL input?

Yes, it was an oversight after I re-worked the random function.

That being said, the function is never called with
NULL so that's mostly academic thinking. +1 for removing the NULL
checks and simplifying the code.

I agree, and thank you both for the attention to detail and interest in
this test suite.

With the patch attached, there are regression.
Is it intentional not to check the return of the function bms_is_member?

diff --strip-trailing-cr -U3

C:/dll/postgres_dev/postgres_commit/src/test/modules/test_bitmapset/expected/test_bitmapset.out
C:/dll/postgres_dev/postgres_commit/build/testrun/test_bitmapset/regress/results/test_bitmapset.out

---

C:/dll/postgres_dev/postgres_commit/src/test/modules/test_bitmapset/expected/test_bitmapset.out

2025-10-02 21:17:53.169515700 -0300
+++

C:/dll/postgres_dev/postgres_commit/build/testrun/test_bitmapset/regress/results/test_bitmapset.out

2025-10-07 21:24:00.534142300 -0300
@@ -1570,9 +1570,5 @@

-- random operations
SELECT test_random_operations(-1, 10000, 81920, 0) > 0 AS result;
- result
---------
- t
-(1 row)
-
+ERROR:  union missing member 63904
DROP EXTENSION test_bitmapset;

best regards,
Ranier Vilela

Thanks Ranier for the report.

You're correct, the tests I wrote overlooked testing the return value
and so were not accomplishing the goal of testing at all.

Adding your small suggested patched turned over another flaw. The error
message you were seeing was from later in that same function.

+ERROR: union missing member 63904

This was emitted by the code in the second portion of the randomized
testing where there is a loop doing add/del/test operations. That error
message was misleading as it matched the earlier error message near the
change you made.

But, thankfully that pointed to a second (face palm) flaw in that
function (again, I take full credit/blame). The add/del/test loop
wasn't accumulating the anticipated set of members and so was testing if
the latest random int generated was in the set or not, which makes no
sense. I've updated that loop to retain the list of members and the
test to check against the retained list of members. I've updated the
log message to be different from those above to avoid similar confusion
in the future.

This seems to be passing now, apologies for not paying closer attention
to this code earlier on.

Great. Thank you for their efforts.

Tests pass here too (Windows).

LGTM.

best regards,
Ranier Vilela

#69David Rowley
dgrowleyml@gmail.com
In reply to: Greg Burd (#67)
Re: [PATCH] Add tests for Bitmapset

On Thu, 9 Oct 2025 at 07:48, Greg Burd <greg@burd.me> wrote:

bms = bms_del_member(bms, member);
+                    num_members--;
+                    memmove(members + pos, members + pos + 1,
+                                     (num_members - pos) * sizeof(int));

I don't think there's any need to maintain the order of that members
array, so couldn't you just do this?:

bms = bms_del_member(bms, member);
members[pos] = members[--num_members];

David

#70Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#69)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Thu, Oct 09, 2025 at 02:57:41PM +1300, David Rowley wrote:

I don't think there's any need to maintain the order of that members
array, so couldn't you just do this?:

bms = bms_del_member(bms, member);
members[pos] = members[--num_members];

Yep, I was just playing with all that and moving the last element to
the member we know is gone would be cheaper. I have also added more
comments to document everything in a more precise way, while going
through.

I also do not see a point in preventing inserts in the second set at
the beginning of the function. This forces bms_union() to do more
operations with overlapping sets.

What do you think about the attached?
--
Michael

Attachments:

v2-0001-test_bitmapset-Improve-random-function.patchtext/x-diff; charset=us-asciiDownload
From 03c6ee49b133e9f77dbd07e1df0a4e0aece511d7 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Thu, 9 Oct 2025 11:11:51 +0900
Subject: [PATCH v2] test_bitmapset: Improve random function

---
 .../modules/test_bitmapset/test_bitmapset.c   | 48 ++++++++++++++-----
 1 file changed, 36 insertions(+), 12 deletions(-)

diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 8bc9b1f48e9a..ce2034b43290 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -618,23 +618,23 @@ test_random_operations(PG_FUNCTION_ARGS)
 	pg_prng_seed(&state, seed);
 	members = palloc(sizeof(int) * num_ops);
 
-	/* Phase 1: Random insertions */
+	/* Phase 1: Random insertions in first set */
 	for (int i = 0; i < num_ops / 2; i++)
 	{
 		member = pg_prng_uint32(&state) % max_range + min_value;
 
 		if (!bms_is_member(member, bms1))
-		{
 			members[num_members++] = member;
-			bms1 = bms_add_member(bms1, member);
-		}
+		bms1 = bms_add_member(bms1, member);
 	}
 
-	/* Phase 2: Random set operations */
+	/* Phase 2: Random insertions in second set */
 	for (int i = 0; i < num_ops / 4; i++)
 	{
 		member = pg_prng_uint32(&state) % max_range + min_value;
 
+		if (!bms_is_member(member, bms2))
+			members[num_members++] = member;
 		bms2 = bms_add_member(bms2, member);
 	}
 
@@ -642,7 +642,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 	result = bms_union(bms1, bms2);
 	EXPECT_NOT_NULL(result);
 
-	/* Verify union contains all members from first set */
+	/* Verify union contains all members from first and second sets */
 	for (int i = 0; i < num_members; i++)
 	{
 		if (!bms_is_member(members[i], result))
@@ -650,7 +650,10 @@ test_random_operations(PG_FUNCTION_ARGS)
 	}
 	bms_free(result);
 
-	/* Test intersection */
+	/*
+	 * Test intersection, checking that all the members in the result are from
+	 * both the first and second sets.
+	 */
 	result = bms_intersect(bms1, bms2);
 	if (result != NULL)
 	{
@@ -683,24 +686,44 @@ test_random_operations(PG_FUNCTION_ARGS)
 	bms_free(bms1);
 	bms_free(bms2);
 
-	for (int i = 0; i < num_ops; i++)
+	/*
+	 * Phase 4: mix of operations on a single set, cross-checking a bitmap
+	 * with a secondary state, "members".  There can be up to "num_ops"
+	 * members added, very unlikely still possible if all the operations hit
+	 * the "0" case.
+	 */
+	num_members = 0;
+	members = palloc(sizeof(int) * num_ops);
+
+	for (int op = 0; op < num_ops; op++)
 	{
-		member = pg_prng_uint32(&state) % max_range + min_value;
 		switch (pg_prng_uint32(&state) % 3)
 		{
 			case 0:				/* add */
+				member = pg_prng_uint32(&state) % max_range + min_value;
+				if (!bms_is_member(member, bms))
+					members[num_members++] = member;
 				bms = bms_add_member(bms, member);
 				break;
 			case 1:				/* delete */
-				if (bms != NULL)
+				if (num_members > 0)
 				{
+					int			pos = pg_prng_uint32(&state) % num_members;
+
+					member = members[pos];
+					if (!bms_is_member(member, bms))
+						elog(ERROR, "expected %d to be a valid member", member);
+
 					bms = bms_del_member(bms, member);
+					members[pos] = members[--num_members];
 				}
 				break;
 			case 2:				/* test membership */
-				if (bms != NULL)
+				/* Verify that bitmap contains all members */
+				for (int i = 0; i < num_members; i++)
 				{
-					bms_is_member(member, bms);
+					if (!bms_is_member(members[i], bms))
+						elog(ERROR, "missing member %d", members[i]);
 				}
 				break;
 		}
@@ -708,6 +731,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 	}
 
 	bms_free(bms);
+	pfree(members);
 
 	PG_RETURN_INT32(total_ops);
 }
-- 
2.51.0

#71David Rowley
dgrowleyml@gmail.com
In reply to: Michael Paquier (#70)
Re: [PATCH] Add tests for Bitmapset

On Thu, 9 Oct 2025 at 15:13, Michael Paquier <michael@paquier.xyz> wrote:

What do you think about the attached?

Thanks. Looks pretty good.

+ members = palloc(sizeof(int) * num_ops);

Any reason to pfree that and allocate that to the same size as it already was?

Wondering if the "members[pos] = members[--num_members];" is worth a
short comment. Maybe something like: /* zap this member by moving the
final array member into its place and shrinking the array by 1 */

David

#72Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#71)
1 attachment(s)
Re: [PATCH] Add tests for Bitmapset

On Thu, Oct 09, 2025 at 04:35:55PM +1300, David Rowley wrote:

On Thu, 9 Oct 2025 at 15:13, Michael Paquier <michael@paquier.xyz> wrote:

What do you think about the attached?

Thanks. Looks pretty good.

+ members = palloc(sizeof(int) * num_ops);

Any reason to pfree that and allocate that to the same size as it already was?

No reason. We can shortcut that a bit.

Wondering if the "members[pos] = members[--num_members];" is worth a
short comment. Maybe something like: /* zap this member by moving the
final array member into its place and shrinking the array by 1 */

Yes, a comment can be adapted here. Sounds good to me.
--
Michael

Attachments:

v3-0001-test_bitmapset-Improve-random-function.patchtext/x-diff; charset=us-asciiDownload
From d7ba7df53ad8d1c45dadb7e01c47b4c30f5bfb75 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Thu, 9 Oct 2025 12:46:59 +0900
Subject: [PATCH v3] test_bitmapset: Improve random function

---
 .../modules/test_bitmapset/test_bitmapset.c   | 57 ++++++++++++++-----
 1 file changed, 44 insertions(+), 13 deletions(-)

diff --git a/src/test/modules/test_bitmapset/test_bitmapset.c b/src/test/modules/test_bitmapset/test_bitmapset.c
index 8bc9b1f48e9a..abbdde85e0b3 100644
--- a/src/test/modules/test_bitmapset/test_bitmapset.c
+++ b/src/test/modules/test_bitmapset/test_bitmapset.c
@@ -616,25 +616,31 @@ test_random_operations(PG_FUNCTION_ARGS)
 	min_value = PG_GETARG_INT32(3);
 
 	pg_prng_seed(&state, seed);
+
+	/*
+	 * There can be up to "num_ops" members added.  This is very unlikely
+	 * still possible if all the operations hit the "0" case during phase 4
+	 * where multiple operation types are mixed together.
+	 */
 	members = palloc(sizeof(int) * num_ops);
 
-	/* Phase 1: Random insertions */
+	/* Phase 1: Random insertions in first set */
 	for (int i = 0; i < num_ops / 2; i++)
 	{
 		member = pg_prng_uint32(&state) % max_range + min_value;
 
 		if (!bms_is_member(member, bms1))
-		{
 			members[num_members++] = member;
-			bms1 = bms_add_member(bms1, member);
-		}
+		bms1 = bms_add_member(bms1, member);
 	}
 
-	/* Phase 2: Random set operations */
+	/* Phase 2: Random insertions in second set */
 	for (int i = 0; i < num_ops / 4; i++)
 	{
 		member = pg_prng_uint32(&state) % max_range + min_value;
 
+		if (!bms_is_member(member, bms2))
+			members[num_members++] = member;
 		bms2 = bms_add_member(bms2, member);
 	}
 
@@ -642,7 +648,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 	result = bms_union(bms1, bms2);
 	EXPECT_NOT_NULL(result);
 
-	/* Verify union contains all members from first set */
+	/* Verify union contains all members from first and second sets */
 	for (int i = 0; i < num_members; i++)
 	{
 		if (!bms_is_member(members[i], result))
@@ -650,7 +656,10 @@ test_random_operations(PG_FUNCTION_ARGS)
 	}
 	bms_free(result);
 
-	/* Test intersection */
+	/*
+	 * Test intersection, checking that all the members in the result are from
+	 * both the first and second sets.
+	 */
 	result = bms_intersect(bms1, bms2);
 	if (result != NULL)
 	{
@@ -679,28 +688,49 @@ test_random_operations(PG_FUNCTION_ARGS)
 		bms_free(result);
 	}
 
-	pfree(members);
 	bms_free(bms1);
 	bms_free(bms2);
 
-	for (int i = 0; i < num_ops; i++)
+	/*
+	 * Phase 4: mix of operations on a single set, cross-checking a bitmap
+	 * with a secondary state, "members".
+	 */
+	num_members = 0;
+
+	for (int op = 0; op < num_ops; op++)
 	{
-		member = pg_prng_uint32(&state) % max_range + min_value;
 		switch (pg_prng_uint32(&state) % 3)
 		{
 			case 0:				/* add */
+				member = pg_prng_uint32(&state) % max_range + min_value;
+				if (!bms_is_member(member, bms))
+					members[num_members++] = member;
 				bms = bms_add_member(bms, member);
 				break;
 			case 1:				/* delete */
-				if (bms != NULL)
+				if (num_members > 0)
 				{
+					int			pos = pg_prng_uint32(&state) % num_members;
+
+					member = members[pos];
+					if (!bms_is_member(member, bms))
+						elog(ERROR, "expected %d to be a valid member", member);
+
 					bms = bms_del_member(bms, member);
+
+					/*
+					 * Move the final array member at the position of the member
+					 * just deleted, reducing the array size by one.
+					 */
+					members[pos] = members[--num_members];
 				}
 				break;
 			case 2:				/* test membership */
-				if (bms != NULL)
+				/* Verify that bitmap contains all members */
+				for (int i = 0; i < num_members; i++)
 				{
-					bms_is_member(member, bms);
+					if (!bms_is_member(members[i], bms))
+						elog(ERROR, "missing member %d", members[i]);
 				}
 				break;
 		}
@@ -708,6 +738,7 @@ test_random_operations(PG_FUNCTION_ARGS)
 	}
 
 	bms_free(bms);
+	pfree(members);
 
 	PG_RETURN_INT32(total_ops);
 }
-- 
2.51.0

#73Greg Burd
greg@burd.me
In reply to: Michael Paquier (#72)
Re: [PATCH] Add tests for Bitmapset

On Oct 8 2025, at 11:47 pm, Michael Paquier <michael@paquier.xyz> wrote:

On Thu, Oct 09, 2025 at 04:35:55PM +1300, David Rowley wrote:

On Thu, 9 Oct 2025 at 15:13, Michael Paquier <michael@paquier.xyz> wrote:

What do you think about the attached?

Thanks. Looks pretty good.

+ members = palloc(sizeof(int) * num_ops);

Any reason to pfree that and allocate that to the same size as it
already was?

No reason. We can shortcut that a bit.

Wondering if the "members[pos] = members[--num_members];" is worth a
short comment. Maybe something like: /* zap this member by moving the
final array member into its place and shrinking the array by 1 */

Yes, a comment can be adapted here. Sounds good to me.
--
Michael

Michael, David,

This patch LGTM. I appreciate the additional work you've both put into it.

You're right, of course, I didn’t need to preserve the order of elements
when deleting. This is where I'd started and I don't recall why I
changed it and didn't revert to this simpler solution.

+ members[pos] = members[--num_members];

Phase 2 might record a value to members that was also recorded in phase
1, but that seems harmless. That's why I had:

+ if (!bms_is_member(member, bms1) && !bms_is_member(member, bms2))

I hadn't thought to optimize this function, but given the amount of time
the tests run in aggregate globally, it makes sense.

best.

-greg

#74David Rowley
dgrowleyml@gmail.com
In reply to: Michael Paquier (#72)
Re: [PATCH] Add tests for Bitmapset

On Thu, 9 Oct 2025 at 16:47, Michael Paquier <michael@paquier.xyz> wrote:

Yes, a comment can be adapted here. Sounds good to me.

Thanks. v3 looks good to me.

David

#75Michael Paquier
michael@paquier.xyz
In reply to: David Rowley (#74)
Re: [PATCH] Add tests for Bitmapset

On Fri, Oct 10, 2025 at 08:33:33AM +1300, David Rowley wrote:

On Thu, 9 Oct 2025 at 16:47, Michael Paquier <michael@paquier.xyz> wrote:

Yes, a comment can be adapted here. Sounds good to me.

Thanks. v3 looks good to me.

Thanks for double-checking. Applied after running an indent.
--
Michael