From e4f70adb688b5abf400f797ba0f15290a9529ac1 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Thu, 13 Nov 2025 12:18:19 -0500
Subject: [PATCH v5 1/5] Add some test scaffolding to join_selectivity().

This not-meant-for-commit patch adds some instrumentation to
plancat.c's join_selectivity() to log the result and runtime
of a join selectivity function.  This is useful for manual
testing of performance patches in eqjoinsel().

To improve the accuracy of the runtime measurement, run the
function 1000 times in each call.  The regression tests still
take a reasonable amount of time with this overhead, although
it's noticeably more than usual.
---
 src/backend/optimizer/util/plancat.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index d950bd93002..15c50e068a0 100644
--- a/src/backend/optimizer/util/plancat.c
+++ b/src/backend/optimizer/util/plancat.c
@@ -42,6 +42,7 @@
 #include "parser/parse_relation.h"
 #include "parser/parsetree.h"
 #include "partitioning/partdesc.h"
+#include "portability/instr_time.h"
 #include "rewrite/rewriteHandler.h"
 #include "rewrite/rewriteManip.h"
 #include "statistics/statistics.h"
@@ -2123,6 +2124,8 @@ join_selectivity(PlannerInfo *root,
 {
 	RegProcedure oprjoin = get_oprjoin(operatorid);
 	float8		result;
+	instr_time	start_time,
+				end_time;
 
 	/*
 	 * if the oprjoin procedure is missing for whatever reason, use a
@@ -2131,6 +2134,10 @@ join_selectivity(PlannerInfo *root,
 	if (!oprjoin)
 		return (Selectivity) 0.5;
 
+	INSTR_TIME_SET_CURRENT(start_time);
+
+	for (int i = 0; i < 1000; i++)
+	{
 	result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
 												 inputcollid,
 												 PointerGetDatum(root),
@@ -2138,6 +2145,21 @@ join_selectivity(PlannerInfo *root,
 												 PointerGetDatum(args),
 												 Int16GetDatum(jointype),
 												 PointerGetDatum(sjinfo)));
+	CHECK_FOR_INTERRUPTS();
+	}
+
+	/* Don't be chatty during initdb */
+	if (IsUnderPostmaster)
+	{
+		INSTR_TIME_SET_CURRENT(end_time);
+
+		INSTR_TIME_SUBTRACT(end_time, start_time);
+
+		/* multiply by 1e6 to get microsecs, divide by 1000 to cancel loop */
+		elog(LOG, "join_selectivity(opr %u, jointype %d) = %f, time %g us",
+			 operatorid, jointype, result,
+			 INSTR_TIME_GET_DOUBLE(end_time) * 1e3);
+	}
 
 	if (result < 0.0 || result > 1.0)
 		elog(ERROR, "invalid join selectivity: %f", result);
-- 
2.43.7

