From 86f318be70a6e1d0b6b0aa59e804373cfb2630bf Mon Sep 17 00:00:00 2001
From: Bjorn Pagen <hello@bjornpagen.com>
Date: Sat, 28 Nov 2026 00:11:06 -0600
Subject: [PATCH v1] Keep parameterized paths for NESTED_LOOP_MEMOIZE advice.

NESTED_LOOP_MEMOIZE advice could come back as "matched, failed" for a
join that the planner was able to do that way.  Memoize needs a
parameterized scan of the inner relation.  But add_path() discards a
parameterized path when an unparameterized one is estimated to cost no
more and return no more rows, which happens when both that scan and
the outer side of the join are expected to return one row.  By the
time the join is planned and the advice is applied, the path is gone.

Add PGS_CONSIDER_UNPARAMETERIZED to fix this.  Unsetting it disables a
rel's unparameterized scan paths, just as unsetting
PGS_CONSIDER_NONPARTIAL disables its non-partial ones, so they can no
longer push a parameterized path out.  pg_plan_advice unsets it for a
relation that NESTED_LOOP_MEMOIZE names by itself, and for that
relation's child rels.  A join on the inner side isn't handled,
because we can't tell which of its relations needs the parameterized
path.

If such advice still can't be followed, say because no index matches
the join clause, EXPLAIN now marks the inner scan as disabled along
with the join.
---
 .../pg_plan_advice/expected/join_strategy.out | 56 +++++++++++++++
 contrib/pg_plan_advice/pgpa_planner.c         | 69 ++++++++++++++++++-
 contrib/pg_plan_advice/sql/join_strategy.sql  | 26 +++++++
 src/backend/optimizer/path/costsize.c         | 34 +++++++++
 src/backend/optimizer/plan/planner.c          |  5 +-
 src/include/nodes/pathnodes.h                 |  8 +++
 6 files changed, 195 insertions(+), 3 deletions(-)

diff --git a/contrib/pg_plan_advice/expected/join_strategy.out b/contrib/pg_plan_advice/expected/join_strategy.out
index 0f9db69219..14d9304ee0 100644
--- a/contrib/pg_plan_advice/expected/join_strategy.out
+++ b/contrib/pg_plan_advice/expected/join_strategy.out
@@ -337,3 +337,59 @@ EXPLAIN (COSTS OFF, PLAN_ADVICE)
 (14 rows)
 
 COMMIT;
+-- NESTED_LOOP_MEMOIZE needs a parameterized scan of the inner table. Here,
+-- the planner would normally discard that scan, because it expects an
+-- unparameterized scan of join_key, or of a partition of join_key_part, to
+-- cost no more and return no more rows. The advice should work anyway.
+CREATE TABLE join_key (a int, b int, PRIMARY KEY (a, b))
+	WITH (autovacuum_enabled = false);
+INSERT INTO join_key SELECT g, g FROM generate_series(1,1000) g;
+VACUUM ANALYZE join_key;
+CREATE TABLE join_key_part (a int, b int, PRIMARY KEY (a, b))
+	PARTITION BY RANGE (b);
+CREATE TABLE join_key_part_1 PARTITION OF join_key_part
+	FOR VALUES FROM (1) TO (501) WITH (autovacuum_enabled = false);
+CREATE TABLE join_key_part_2 PARTITION OF join_key_part
+	FOR VALUES FROM (501) TO (1001) WITH (autovacuum_enabled = false);
+INSERT INTO join_key_part SELECT g, g FROM generate_series(1,1000) g;
+VACUUM ANALYZE join_key_part;
+BEGIN;
+SET LOCAL pg_plan_advice.advice = 'NESTED_LOOP_MEMOIZE(k)';
+EXPLAIN (COSTS OFF)
+	SELECT * FROM join_fact f JOIN join_key k ON k.b = f.dim_id AND k.a = 1
+	WHERE f.id = 5;
+                          QUERY PLAN                           
+---------------------------------------------------------------
+ Nested Loop
+   ->  Index Scan using join_fact_pkey on join_fact f
+         Index Cond: (id = 5)
+   ->  Memoize
+         Cache Key: f.dim_id
+         Cache Mode: logical
+         ->  Index Only Scan using join_key_pkey on join_key k
+               Index Cond: ((a = 1) AND (b = f.dim_id))
+ Supplied Plan Advice:
+   NESTED_LOOP_MEMOIZE(k) /* matched */
+(10 rows)
+
+EXPLAIN (COSTS OFF)
+	SELECT * FROM join_fact f JOIN join_key_part k ON k.b = f.dim_id
+	AND k.a = 1 WHERE f.id = 5;
+                                     QUERY PLAN                                      
+-------------------------------------------------------------------------------------
+ Nested Loop
+   ->  Index Scan using join_fact_pkey on join_fact f
+         Index Cond: (id = 5)
+   ->  Memoize
+         Cache Key: f.dim_id
+         Cache Mode: logical
+         ->  Append
+               ->  Index Only Scan using join_key_part_1_pkey on join_key_part_1 k_1
+                     Index Cond: ((a = 1) AND (b = f.dim_id))
+               ->  Index Only Scan using join_key_part_2_pkey on join_key_part_2 k_2
+                     Index Cond: ((a = 1) AND (b = f.dim_id))
+ Supplied Plan Advice:
+   NESTED_LOOP_MEMOIZE(k) /* matched */
+(13 rows)
+
+COMMIT;
diff --git a/contrib/pg_plan_advice/pgpa_planner.c b/contrib/pg_plan_advice/pgpa_planner.c
index 9f924b6af1..87b89c76db 100644
--- a/contrib/pg_plan_advice/pgpa_planner.c
+++ b/contrib/pg_plan_advice/pgpa_planner.c
@@ -150,6 +150,8 @@ static void pgpa_planner_apply_scan_advice(RelOptInfo *rel,
 										   pgpa_trove_entry *rel_entries,
 										   Bitmapset *rel_indexes);
 static uint64 pgpa_join_strategy_mask_from_advice_tag(pgpa_advice_tag_type tag);
+static bool pgpa_join_advice_requires_parameterization(pgpa_trove *trove,
+													   pgpa_identifier *rid);
 static pgpa_jo_outcome pgpa_join_order_permits_join(int outer_count,
 													int inner_count,
 													pgpa_identifier *rids,
@@ -440,6 +442,7 @@ pgpa_build_simple_rel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 		pgpa_identifier *rid;
 		pgpa_trove_result tresult_scan;
 		pgpa_trove_result tresult_rel;
+		bool		parameterize;
 
 		/* Search for scan advice and general rel advice. */
 		rid = &proot->rid_array[rel->relid - 1];
@@ -448,8 +451,26 @@ pgpa_build_simple_rel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 		pgpa_trove_lookup(pps->trove, PGPA_TROVE_LOOKUP_REL, 1, rid,
 						  &tresult_rel);
 
+		/*
+		 * Join method advice can require that this rel be scanned using a
+		 * parameterized path. If this is a child rel, the advice might
+		 * instead name its topmost parent.
+		 */
+		parameterize =
+			pgpa_join_advice_requires_parameterization(pps->trove, rid);
+		if (!parameterize && rel->top_parent != NULL)
+		{
+			pgpa_identifier *parent_rid;
+
+			parent_rid = &proot->rid_array[rel->top_parent->relid - 1];
+			parameterize =
+				pgpa_join_advice_requires_parameterization(pps->trove,
+														   parent_rid);
+		}
+
 		/* If relevant entries were found, apply them. */
-		if (tresult_scan.indexes != NULL || tresult_rel.indexes != NULL)
+		if (tresult_scan.indexes != NULL || tresult_rel.indexes != NULL ||
+			parameterize)
 		{
 			uint64		original_mask = rel->pgs_mask;
 
@@ -460,6 +481,14 @@ pgpa_build_simple_rel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 										   tresult_rel.entries,
 										   tresult_rel.indexes);
 
+			/*
+			 * We have to disable the unparameterized paths now. Otherwise,
+			 * add_path() might discard the parameterized ones before the join
+			 * is planned.
+			 */
+			if (parameterize)
+				rel->pgs_mask &= ~PGS_CONSIDER_UNPARAMETERIZED;
+
 			/* Emit debugging message, if enabled. */
 			if (pg_plan_advice_trace_mask && original_mask != rel->pgs_mask)
 			{
@@ -1242,6 +1271,44 @@ pgpa_join_strategy_mask_from_advice_tag(pgpa_advice_tag_type tag)
 	}
 }
 
+/*
+ * Does join method advice require a parameterized scan of the relation
+ * with the given identifier?
+ *
+ * That's the case if the relation is, by itself, supposed to be the inner
+ * side of a nested loop with memoization, since Memoize is only ever used
+ * above a parameterized path. As in pgpa_planner_apply_join_path_advice,
+ * the answer is no if the join method advice for the relation conflicts.
+ */
+static bool
+pgpa_join_advice_requires_parameterization(pgpa_trove *trove,
+										   pgpa_identifier *rid)
+{
+	pgpa_trove_result tresult;
+	uint64		join_mask = 0;
+	int			i = -1;
+
+	pgpa_trove_lookup(trove, PGPA_TROVE_LOOKUP_JOIN, 1, rid, &tresult);
+	while ((i = bms_next_member(tresult.indexes, i)) >= 0)
+	{
+		pgpa_trove_entry *entry = &tresult.entries[i];
+		uint64		my_join_mask;
+
+		/* Consider only join method advice for this relation by itself. */
+		my_join_mask = pgpa_join_strategy_mask_from_advice_tag(entry->tag);
+		if (my_join_mask == 0 ||
+			pgpa_identifiers_match_target(1, rid,
+										  entry->target) != PGPA_ITM_EQUAL)
+			continue;
+
+		if (join_mask != 0 && join_mask != my_join_mask)
+			return false;
+		join_mask = my_join_mask;
+	}
+
+	return join_mask == PGS_NESTLOOP_MEMOIZE;
+}
+
 /*
  * Does a certain item of join order advice permit a certain join?
  *
diff --git a/contrib/pg_plan_advice/sql/join_strategy.sql b/contrib/pg_plan_advice/sql/join_strategy.sql
index edd5c4c0e1..5364266df5 100644
--- a/contrib/pg_plan_advice/sql/join_strategy.sql
+++ b/contrib/pg_plan_advice/sql/join_strategy.sql
@@ -82,3 +82,29 @@ SET LOCAL pg_plan_advice.advice = 'NESTED_LOOP_PLAIN(f d)';
 EXPLAIN (COSTS OFF, PLAN_ADVICE)
 	SELECT * FROM join_fact f JOIN join_dim d ON f.dim_id = d.id;
 COMMIT;
+
+-- NESTED_LOOP_MEMOIZE needs a parameterized scan of the inner table. Here,
+-- the planner would normally discard that scan, because it expects an
+-- unparameterized scan of join_key, or of a partition of join_key_part, to
+-- cost no more and return no more rows. The advice should work anyway.
+CREATE TABLE join_key (a int, b int, PRIMARY KEY (a, b))
+	WITH (autovacuum_enabled = false);
+INSERT INTO join_key SELECT g, g FROM generate_series(1,1000) g;
+VACUUM ANALYZE join_key;
+CREATE TABLE join_key_part (a int, b int, PRIMARY KEY (a, b))
+	PARTITION BY RANGE (b);
+CREATE TABLE join_key_part_1 PARTITION OF join_key_part
+	FOR VALUES FROM (1) TO (501) WITH (autovacuum_enabled = false);
+CREATE TABLE join_key_part_2 PARTITION OF join_key_part
+	FOR VALUES FROM (501) TO (1001) WITH (autovacuum_enabled = false);
+INSERT INTO join_key_part SELECT g, g FROM generate_series(1,1000) g;
+VACUUM ANALYZE join_key_part;
+BEGIN;
+SET LOCAL pg_plan_advice.advice = 'NESTED_LOOP_MEMOIZE(k)';
+EXPLAIN (COSTS OFF)
+	SELECT * FROM join_fact f JOIN join_key k ON k.b = f.dim_id AND k.a = 1
+	WHERE f.id = 5;
+EXPLAIN (COSTS OFF)
+	SELECT * FROM join_fact f JOIN join_key_part k ON k.b = f.dim_id
+	AND k.a = 1 WHERE f.id = 5;
+COMMIT;
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index f760ef9aa3..391dadd2cf 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -334,6 +334,9 @@ cost_seqscan(Path *path, PlannerInfo *root,
 	else
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
 
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
+
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 	path->startup_cost = startup_cost;
@@ -412,6 +415,9 @@ cost_samplescan(Path *path, PlannerInfo *root,
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
 
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
+
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 	path->startup_cost = startup_cost;
@@ -605,6 +611,8 @@ cost_index(IndexPath *path, PlannerInfo *root, double loop_count,
 	/* is this scan type disabled? */
 	enable_mask = (indexonly ? PGS_INDEXONLYSCAN : PGS_INDEXSCAN)
 		| (partial_path ? 0 : PGS_CONSIDER_NONPARTIAL);
+	if (path->path.param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->path.disabled_nodes =
 		(baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 
@@ -1103,6 +1111,9 @@ cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
 	startup_cost += path->pathtarget->cost.startup;
 	run_cost += path->pathtarget->cost.per_tuple * path->rows;
 
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
+
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 	path->startup_cost = startup_cost;
@@ -1344,6 +1355,8 @@ cost_tidscan(Path *path, PlannerInfo *root,
 	 */
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -1462,6 +1475,8 @@ cost_tidrangescan(Path *path, PlannerInfo *root,
 	Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0);
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -1519,6 +1534,8 @@ cost_subqueryscan(SubqueryScanPath *path, PlannerInfo *root,
 	 */
 	if (path->path.parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->path.disabled_nodes = path->subpath->disabled_nodes
 		+ (((baserel->pgs_mask & enable_mask) != enable_mask) ? 1 : 0);
 	path->path.startup_cost = path->subpath->startup_cost;
@@ -1614,6 +1631,8 @@ cost_functionscan(Path *path, PlannerInfo *root,
 
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -1675,6 +1694,8 @@ cost_tablefuncscan(Path *path, PlannerInfo *root,
 
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -1727,6 +1748,8 @@ cost_valuesscan(Path *path, PlannerInfo *root,
 
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -1779,6 +1802,8 @@ cost_ctescan(Path *path, PlannerInfo *root,
 
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -1821,6 +1846,8 @@ cost_namedtuplestorescan(Path *path, PlannerInfo *root,
 
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -1860,6 +1887,8 @@ cost_resultscan(Path *path, PlannerInfo *root,
 
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 	path->disabled_nodes =
 		(baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
 	path->startup_cost = startup_cost;
@@ -2327,6 +2356,9 @@ cost_append(AppendPath *apath, PlannerInfo *root)
 	if (apath->path.parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
 
+	if (apath->path.param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
+
 	apath->path.disabled_nodes =
 		(rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
 	apath->path.startup_cost = 0;
@@ -2549,6 +2581,8 @@ cost_merge_append(Path *path, PlannerInfo *root,
 
 	if (path->parallel_workers == 0)
 		enable_mask |= PGS_CONSIDER_NONPARTIAL;
+	if (path->param_info == NULL)
+		enable_mask |= PGS_CONSIDER_UNPARAMETERIZED;
 
 	/*
 	 * Avoid log(0)...
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 568a1b2a34..2ee44b8e9c 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -502,7 +502,7 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	 * index scan paths.
 	 */
 	glob->default_pgs_mask = PGS_APPEND | PGS_MERGE_APPEND | PGS_FOREIGNJOIN |
-		PGS_GATHER | PGS_CONSIDER_NONPARTIAL;
+		PGS_GATHER | PGS_CONSIDER_NONPARTIAL | PGS_CONSIDER_UNPARAMETERIZED;
 	if (enable_tidscan)
 		glob->default_pgs_mask |= PGS_TIDSCAN;
 	if (enable_seqscan)
@@ -7168,7 +7168,8 @@ plan_cluster_use_sort(Oid tableOid, Oid indexOid)
 	 * Initialize the strategies needed for the two non-partial scan paths we
 	 * compare below.  Index scans are enabled, as checked above.
 	 */
-	glob->default_pgs_mask = PGS_CONSIDER_NONPARTIAL | PGS_INDEXSCAN;
+	glob->default_pgs_mask = PGS_CONSIDER_NONPARTIAL |
+		PGS_CONSIDER_UNPARAMETERIZED | PGS_INDEXSCAN;
 	if (enable_seqscan)
 		glob->default_pgs_mask |= PGS_SEQSCAN;
 
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 2ba1dbfb67..a3d09ca1be 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -62,6 +62,13 @@
  * plugin can nudge the planner toward a particular strategy by disabling
  * all of the others, but that doesn't work here: unsetting PGS_SEQSCAN,
  * for instance, would disable both partial and non-partial sequential scans.
+ *
+ * Likewise, unsetting PGS_CONSIDER_UNPARAMETERIZED disables all of a rel's
+ * unparameterized scan paths, since no other bit distinguishes those from
+ * parameterized ones. This is the only way to be sure of having a
+ * parameterized path to use on the inner side of a nested loop: add_path()
+ * discards a parameterized path if some unparameterized path that isn't
+ * disabled is estimated to cost no more and return no more rows.
  */
 #define PGS_SEQSCAN					0x00000001
 #define PGS_INDEXSCAN				0x00000002
@@ -82,6 +89,7 @@
 #define PGS_CONSIDER_INDEXONLY		0x00010000
 #define PGS_CONSIDER_PARTITIONWISE	0x00020000
 #define PGS_CONSIDER_NONPARTIAL		0x00040000
+#define PGS_CONSIDER_UNPARAMETERIZED	0x00080000
 
 /*
  * Convenience macros for useful combination of the bits defined above.
-- 
2.54.0 (Apple Git-157)

