Hi,

When a partitioned table is on the inner side of a parameterized Nested Loop
(or in a correlated subquery), the Append/MergeAppend is rescanned for every
outer row and run-time pruning picks the partition(s) to scan. With many
partitions, this is much slower than it needs to be. The attached patches
try to address this.

This builds on the discussion in "Improve the performance of nested loop
join in the case of partitioned inner table" [1], from 2023. 0002 is a
rework of that proposal following David's review. 0001 is a new
improvement that I found while looking at where the time actually goes.

--- 0001: Defer changed-parameter signaling of Append/MergeAppend children

On every rescan, ExecReScanAppend() loops over all of its children and
calls UpdateChangedParamSet() (or ExecReScan()) on each one, even though
run-time pruning will then pick only one or a few of them to execute.
That's O(number of partitions) per outer row, and each iteration
allocates and frees a small Bitmapset (via bms_intersect() +
bms_join()). Profiling a Nested Loop into a 1000-partition table on
master shows about 58% of the execution time in ExecReScanAppend(),
against about ~2% for the pruning itself.

0001 records each rescan with a generation counter instead, and delivers
the pending signaling to a child only just before that child is about to
be executed. Children that pruning skips are never touched, so a rescan
becomes O(1) plus the work for the children that actually run. Each
child ends up with exactly the same signaling as on master. If a rescan
has a different set of changed parameters than the pending one, the
lagging children are brought up to date first.

The deferral is only used when the Append/MergeAppend has run-time pruning.
Without it, every child runs after each rescan anyway, so deferring would only
add bookkeeping. In an earlier version that deferred unconditionally, that
showed up as a 2-3% slowdown for rescans of a 1000-child Append. Those nodes
now keep the existing eager signaling, and that case is within noise of
master.

--- 0002: Skip run-time partition re-pruning when the parameter values are 
unchanged

Nested Loop marks its parameters as changed for every outer row, even
when the value is the same as for the previous row, so Append throws
away its pruning result and prunes again. The values of the Params used
by run-time pruning are saved, copying pass-by-ref values into a small
memory context, and compared with datumIsEqual() on rescan. Pruning is
redone only if one of them actually changed. TOASTed values and InitPlan
outputs that haven't been computed yet are always treated as changed.

--- Benchmarks

I compared release builds (cassert off) of master at 73401447c34, master
+ 0001 and master + 0001 + 0002, each on a freshly restarted cluster
with the same data set. Each query ran in 3 to 5 rounds of 5 runs after
a warm-up, and the numbers are the median of all runs. Results and plans
are identical on all builds for every case. The cases cover:

- range, list and hash partitioning with 2 to 1000 partitions, a DEFAULT
  partition, and two-level partitioning;
- int, bigint-vs-int, 300-byte text, uuid, timestamptz, TOASTed text and
  NULL keys;
- inner, LEFT, semi and anti Nested Loop joins, and correlated SubPlans;
- corner cases: pruning disabled, run-time pruning that keeps 50 or about
  90% of 1000 partitions, Parallel Append under a rescanned Gather, and
  generic plans with initial + run-time pruning;
- postgres_fdw foreign partitions, with sync and async Append;
- Appends without a partitioned table (UNION ALL with 2 and 16 arms, and
  inheritance with 16 and 1000 children), and Nested Loop rescans without
  parameters.

"chg" means the outer key changes on every row, and "rep" means the same rows
sorted by the key, so it repeats on consecutive rows. Times in ms:

                                         master    0001   0001+0002
  list, 1000 partitions, chg               1120     114      115
  list, 1000 partitions, rep               1039      59       49
  hash, 1000 partitions, chg               1071      93       95
  hash, 1000 partitions, rep               1015      55       47
  timestamptz, 365 daily ranges, chg        398      77       77
  timestamptz, 365 daily ranges, rep        381      50       42
  hash, 16 partitions, chg                  102      88       89
  hash, 16 partitions, rep                   70      56       51
  text 300 bytes, hash 16, chg              151     131      134
  text 300 bytes, hash 16, rep              105      92       74
  correlated SubPlan, 1000 partitions      3243    2147     2235
  range, 2 partitions, chg                   81      81       81
  range 1000, pruning keeps ~90%, chg      2529    2475     2423
  UNION ALL, 16 arms                        664     660      659
  hash 1000, rescans without params        1288    1277     1315

The full results are in the attached PDF.

The improvement grows with the number of partitions: about 90-95% faster
with 1000 partitions, 40-90% with 90-365, and about 15% with 16. With
only 2 partitions there's no measurable difference. One option would be
to enable this only above some number of partitions, though since small
partition counts don't seem to regress, I'm not sure the extra knob is
worth it. Opinions welcome. When pruning keeps most partitions, there's
nothing to save and the patches stay within noise of master; the same
goes for Appends without a partitioned table, and for rescans without
parameters, which all stay within about +/-3% of master, which seems
noise level on my machine, but I might be interpreting the results
wrong. Other testing methodology feedback is welcome, I tried my best to
find cases where these patches introduce a considerable regression.

As David expected in [1], 0002 adds some overhead when the parameter changes
on every outer row: in a profile of the 1000-partition "chg" case, saving and
comparing the values is about 4% of the execution time. It doesn't show up
clearly in the end-to-end timings above, and with 0001 the combined patches
are faster than master in every "chg" case. On top of 0002, we could still add
the adaptive behavior David suggested: stop saving and comparing after the
values change N times in a row, similar to the heuristic in 3592e0ff9, and
start again once pruning keeps returning the same partition.

Thoughts?

[1] 
https://www.postgresql.org/message-id/CAHdr9ueefdCCCq1mXAYfLmRgEKfhWQDCU7=xmureeazjcow...@mail.gmail.com

--
Matheus Alcantara
EDB: https://www.enterprisedb.com
From 1ae13448ad2c463ed004b4713183b43d4ae41337 Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <[email protected]>
Date: Mon, 23 Nov 2026 19:14:42 -0300
Subject: [PATCH v1 1/2] Defer changed-parameter signaling of
 Append/MergeAppend children

When an Append or MergeAppend node is rescanned, it has to do the
changed-parameter signaling for its children itself, and until now it
did that eagerly by calling UpdateChangedParamSet() or ExecReScan() on
every child. That costs O(number of children) per rescan, even when
run-time partition pruning means that only one or a few of them will be
executed before the next rescan. This is the common case on the inner
side of a parameterized nested loop over a partitioned table, where the
per-rescan loop over all partitions can dominate the execution time with
many partitions.

Instead, record each rescan in a generation counter, along with the
chgParam set, and deliver the pending signaling to each child only just
before it is next executed. A rescan with a different chgParam set than
the one pending first brings all lagging children up to date, so that
the signaling each child receives is exactly what it would have received
before.

This is only done for nodes that do run-time pruning. Without it, every
child is executed after each rescan anyway, so deferring would just add
overhead; such nodes keep signaling all of their children right away,
now through the new ExecReScanChildren().

search_plan_tree() in execCurrent.c relied on Append children having
been rescanned, so teach it to treat a child with deferred signaling as
having a pending rescan.
---
 src/backend/executor/execAmi.c                | 126 +++++++++++++
 src/backend/executor/execCurrent.c            |   8 +
 src/backend/executor/nodeAppend.c             |  52 ++++--
 src/backend/executor/nodeMergeAppend.c        |  43 +++--
 src/include/executor/executor.h               |  24 +++
 src/include/nodes/execnodes.h                 |  44 +++++
 src/test/regress/expected/partition_prune.out | 174 ++++++++++++++++++
 src/test/regress/sql/partition_prune.sql      |  66 +++++++
 src/tools/pgindent/typedefs.list              |   1 +
 9 files changed, 499 insertions(+), 39 deletions(-)

diff --git a/src/backend/executor/execAmi.c b/src/backend/executor/execAmi.c
index 41f9bce70a7..4a684f4cf91 100644
--- a/src/backend/executor/execAmi.c
+++ b/src/backend/executor/execAmi.c
@@ -318,6 +318,132 @@ ExecReScan(PlanState *node)
        }
 }
 
+/*
+ * ExecInitDeferredChildRescan
+ *             Initialize a DeferredChildRescan for a node with 'nchildren' 
children.
+ *
+ * All children start out up to date, and stay so as long as the node never
+ * calls ExecDeferChildRescan(), so ExecPrepareDeferredChild() is then a
+ * no-op.
+ */
+void
+ExecInitDeferredChildRescan(DeferredChildRescan *dcr, int nchildren)
+{
+       dcr->generation = 0;
+       dcr->child_generation = palloc0_array(uint64, Max(nchildren, 1));
+       dcr->pending_chgparam = NULL;
+}
+
+/*
+ * rescan_child
+ *             Do the changed-parameter signaling for a child that a node with 
an
+ *             arbitrary list of children would traditionally do in its ReScan
+ *             function.
+ */
+static inline void
+rescan_child(PlanState *child, Bitmapset *chgParam)
+{
+       if (chgParam != NULL)
+               UpdateChangedParamSet(child, chgParam);
+
+       /*
+        * If chgParam of child is not null then the plan will be re-scanned by
+        * the first ExecProcNode or by the first ExecAsyncRequest.
+        */
+       if (child->chgParam == NULL)
+               ExecReScan(child);
+}
+
+/*
+ * ExecReScanChildren
+ *             Do the changed-parameter signaling for all of a node's children 
right
+ *             away.
+ *
+ * ExecReScan() doesn't know about the children of nodes like Append, so such
+ * nodes must do changed-parameter signaling for them in their ReScan
+ * function.  This is the plain way of doing it; see ExecDeferChildRescan()
+ * for an alternative that pays off when only a few of the children are
+ * executed after each rescan.
+ */
+void
+ExecReScanChildren(PlanState **children, int nchildren, Bitmapset *chgParam)
+{
+       for (int i = 0; i < nchildren; i++)
+               rescan_child(children[i], chgParam);
+}
+
+/*
+ * ExecDeferChildRescan
+ *             Called from a node's ReScan function, in place of doing the
+ *             changed-parameter signaling for each of its children itself.
+ *
+ * ExecReScan() doesn't know about the children of nodes like Append, so such
+ * nodes must do changed-parameter signaling for them. Rather than doing it
+ * for all children right away, we just record that a rescan happened, by
+ * incrementing the generation counter, which makes every child "lagging"
+ * (see DeferredChildRescan). ExecPrepareDeferredChild() then does the
+ * signaling for a lagging child just before that child is next executed,
+ * making it "up to date" again. This matters when only a few children are
+ * executed per rescan, for example because of run-time partition pruning on
+ * the inner side of a parameterized nested loop: the rescan itself is O(1),
+ * and children that are never executed are never signaled.
+ *
+ * To be able to tell exactly which parameters a lagging child needs to be
+ * told have changed, we require that all rescans that a child may have
+ * missed were done with the same chgParam set, which we remember in
+ * pending_chgparam. When a rescan has a different set than the previous
+ * ones, we first bring all lagging children up to date using the old set.
+ * That's rare in practice: the inner side of a nested loop is always
+ * rescanned with the same set of parameters.
+ */
+void
+ExecDeferChildRescan(DeferredChildRescan *dcr, PlanState **children,
+                                        int nchildren, Bitmapset *chgParam)
+{
+       if (!bms_equal(chgParam, dcr->pending_chgparam))
+       {
+               /*
+                * The set of changed parameters differs from that of the 
rescans that
+                * lagging children have missed, so we can't keep deferring 
their
+                * signaling with a single pending set. Bring them up to date 
now,
+                * with the old set, and start over with the new one.
+                */
+               for (int i = 0; i < nchildren; i++)
+               {
+                       if (dcr->child_generation[i] != dcr->generation)
+                       {
+                               rescan_child(children[i], 
dcr->pending_chgparam);
+                               dcr->child_generation[i] = dcr->generation;
+                       }
+               }
+
+               bms_free(dcr->pending_chgparam);
+               dcr->pending_chgparam = bms_copy(chgParam);
+       }
+
+       /* Advance the clock; every child is now lagging */
+       dcr->generation++;
+}
+
+/*
+ * ExecCatchUpChildRescan
+ *             Deliver changed-parameter signaling deferred by 
ExecDeferChildRescan()
+ *             to the given child. Use ExecPrepareDeferredChild() instead of
+ *             calling this directly.
+ */
+void
+ExecCatchUpChildRescan(DeferredChildRescan *dcr, PlanState *child,
+                                          int childno)
+{
+       Assert(dcr->child_generation[childno] != dcr->generation);
+
+       /* Apply the signaling of the missed rescans, once */
+       rescan_child(child, dcr->pending_chgparam);
+
+       /* The child is up to date now */
+       dcr->child_generation[childno] = dcr->generation;
+}
+
 /*
  * ExecMarkPos
  *
diff --git a/src/backend/executor/execCurrent.c 
b/src/backend/executor/execCurrent.c
index 9058de2e998..418b696d698 100644
--- a/src/backend/executor/execCurrent.c
+++ b/src/backend/executor/execCurrent.c
@@ -360,6 +360,11 @@ search_plan_tree(PlanState *node, Oid table_oid,
                         * We do need to watch out for multiple matches 
(possible if
                         * Append was from UNION ALL rather than an inheritance 
tree).
                         *
+                        * Also, an input whose rescan has been deferred (see
+                        * ExecDeferChildRescan) may still appear to be 
positioned on a
+                        * tuple from before the rescan, so treat that like a 
pending
+                        * rescan.
+                        *
                         * Note: we can NOT descend through MergeAppend 
similarly, since
                         * its inputs are likely all active, and we don't know 
which one
                         * returned the current output tuple.  (Perhaps that 
could be
@@ -385,6 +390,9 @@ search_plan_tree(PlanState *node, Oid table_oid,
                                        if (result)
                                                return NULL;    /* multiple 
matches */
                                        result = elem;
+                                       if 
(astate->as_child_rescan.child_generation[i] !=
+                                               
astate->as_child_rescan.generation)
+                                               *pending_rescan = true;
                                }
                                break;
                        }
diff --git a/src/backend/executor/nodeAppend.c 
b/src/backend/executor/nodeAppend.c
index f7ce2f17409..a2a82ea67e4 100644
--- a/src/backend/executor/nodeAppend.c
+++ b/src/backend/executor/nodeAppend.c
@@ -220,6 +220,7 @@ ExecInitAppend(Append *node, EState *estate, int eflags)
        appendstate->as_first_partial_plan = firstvalid;
        appendstate->appendplans = appendplanstates;
        appendstate->as_nplans = nplans;
+       ExecInitDeferredChildRescan(&appendstate->as_child_rescan, nplans);
 
        /*
         * Initialize Append's result tuple type and slot.  If the child plans 
all
@@ -420,7 +421,6 @@ void
 ExecReScanAppend(AppendState *node)
 {
        int                     nasyncplans = node->as_nasyncplans;
-       int                     i;
 
        /* If there are any async subplans, reset async requests made for them. 
*/
        if (nasyncplans > 0)
@@ -442,24 +442,20 @@ ExecReScanAppend(AppendState *node)
                node->as_valid_asyncplans = NULL;
        }
 
-       for (i = 0; i < node->as_nplans; i++)
-       {
-               PlanState  *subnode = node->appendplans[i];
-
-               /*
-                * ExecReScan doesn't know about my subplans, so I have to do
-                * changed-parameter signaling myself.
-                */
-               if (node->ps.chgParam != NULL)
-                       UpdateChangedParamSet(subnode, node->ps.chgParam);
-
-               /*
-                * If chgParam of subnode is not null then plan will be 
re-scanned by
-                * first ExecProcNode or by first ExecAsyncRequest.
-                */
-               if (subnode->chgParam == NULL)
-                       ExecReScan(subnode);
-       }
+       /*
+        * ExecReScan doesn't know about my subplans, so I have to do
+        * changed-parameter signaling myself.  With run-time pruning, most of
+        * them might not be executed before the next rescan, so defer the
+        * signaling until each subplan is next chosen; see 
choose_next_subplan_*
+        * and ExecAppendAsyncBegin.  Otherwise all of them will be executed, so
+        * just do it right away.
+        */
+       if (node->as_prune_state && node->as_prune_state->do_exec_prune)
+               ExecDeferChildRescan(&node->as_child_rescan, node->appendplans,
+                                                        node->as_nplans, 
node->ps.chgParam);
+       else
+               ExecReScanChildren(node->appendplans, node->as_nplans,
+                                                  node->ps.chgParam);
 
        /* Let choose_next_subplan_* function handle setting the first subplan 
*/
        node->as_whichplan = INVALID_SUBPLAN_INDEX;
@@ -604,6 +600,10 @@ choose_next_subplan_locally(AppendState *node)
 
        node->as_whichplan = nextplan;
 
+       /* Deliver any deferred rescan signaling before it gets executed */
+       ExecPrepareDeferredChild(&node->as_child_rescan,
+                                                        
node->appendplans[nextplan], nextplan);
+
        return true;
 }
 
@@ -681,6 +681,11 @@ choose_next_subplan_for_leader(AppendState *node)
 
        LWLockRelease(&pstate->pa_lock);
 
+       /* Deliver any deferred rescan signaling before it gets executed */
+       ExecPrepareDeferredChild(&node->as_child_rescan,
+                                                        
node->appendplans[node->as_whichplan],
+                                                        node->as_whichplan);
+
        return true;
 }
 
@@ -812,6 +817,11 @@ choose_next_subplan_for_worker(AppendState *node)
 
        LWLockRelease(&pstate->pa_lock);
 
+       /* Deliver any deferred rescan signaling before it gets executed */
+       ExecPrepareDeferredChild(&node->as_child_rescan,
+                                                        
node->appendplans[node->as_whichplan],
+                                                        node->as_whichplan);
+
        return true;
 }
 
@@ -898,6 +908,10 @@ ExecAppendAsyncBegin(AppendState *node)
                Assert(areq->request_index == i);
                Assert(!areq->callback_pending);
 
+               /* Deliver any deferred rescan signaling before it gets 
executed */
+               ExecPrepareDeferredChild(&node->as_child_rescan,
+                                                                
node->appendplans[i], i);
+
                /* Do the actual work. */
                ExecAsyncRequest(areq);
        }
diff --git a/src/backend/executor/nodeMergeAppend.c 
b/src/backend/executor/nodeMergeAppend.c
index 236be9599a4..235e623c340 100644
--- a/src/backend/executor/nodeMergeAppend.c
+++ b/src/backend/executor/nodeMergeAppend.c
@@ -135,6 +135,7 @@ ExecInitMergeAppend(MergeAppend *node, EState *estate, int 
eflags)
        mergeplanstates = palloc_array(PlanState *, nplans);
        mergestate->mergeplans = mergeplanstates;
        mergestate->ms_nplans = nplans;
+       ExecInitDeferredChildRescan(&mergestate->ms_child_rescan, nplans);
 
        mergestate->ms_slots = palloc0_array(TupleTableSlot *, nplans);
        mergestate->ms_heap = binaryheap_allocate(nplans, heap_compare_slots,
@@ -287,6 +288,15 @@ ExecMergeAppend(PlanState *pstate)
                        node->ms_valid_subplans =
                                ExecFindMatchingSubPlans(node->ms_prune_state, 
false, NULL);
 
+               /*
+                * Deliver any deferred rescan signaling to the subplans we're 
about
+                * to execute.
+                */
+               i = -1;
+               while ((i = bms_next_member(node->ms_valid_subplans, i)) >= 0)
+                       ExecPrepareDeferredChild(&node->ms_child_rescan,
+                                                                        
node->mergeplans[i], i);
+
                /*
                 * First time through: pull the first tuple from each valid 
subplan,
                 * and set up the heap.
@@ -462,8 +472,6 @@ ExecEndMergeAppend(MergeAppendState *node)
 void
 ExecReScanMergeAppend(MergeAppendState *node)
 {
-       int                     i;
-
        /* If there are any async subplans, reset async requests made for them. 
*/
        if (node->ms_nasyncplans > 0)
                ExecMergeAppendAsyncReset(node);
@@ -481,24 +489,19 @@ ExecReScanMergeAppend(MergeAppendState *node)
                node->ms_valid_subplans = NULL;
        }
 
-       for (i = 0; i < node->ms_nplans; i++)
-       {
-               PlanState  *subnode = node->mergeplans[i];
-
-               /*
-                * ExecReScan doesn't know about my subplans, so I have to do
-                * changed-parameter signaling myself.
-                */
-               if (node->ps.chgParam != NULL)
-                       UpdateChangedParamSet(subnode, node->ps.chgParam);
-
-               /*
-                * If chgParam of subnode is not null then plan will be 
re-scanned by
-                * first ExecProcNode or by first ExecAsyncRequest.
-                */
-               if (subnode->chgParam == NULL)
-                       ExecReScan(subnode);
-       }
+       /*
+        * ExecReScan doesn't know about my subplans, so I have to do
+        * changed-parameter signaling myself.  With run-time pruning, most of
+        * them might not be executed before the next rescan, so defer the
+        * signaling until each subplan is next executed; see ExecMergeAppend.
+        * Otherwise all of them will be executed, so just do it right away.
+        */
+       if (node->ms_prune_state && node->ms_prune_state->do_exec_prune)
+               ExecDeferChildRescan(&node->ms_child_rescan, node->mergeplans,
+                                                        node->ms_nplans, 
node->ps.chgParam);
+       else
+               ExecReScanChildren(node->mergeplans, node->ms_nplans,
+                                                  node->ps.chgParam);
 
        binaryheap_reset(node->ms_heap);
        node->ms_initialized = false;
diff --git a/src/include/executor/executor.h b/src/include/executor/executor.h
index 95498600aba..c5de7778786 100644
--- a/src/include/executor/executor.h
+++ b/src/include/executor/executor.h
@@ -106,6 +106,15 @@ extern PGDLLIMPORT ExecutorCheckPerms_hook_type 
ExecutorCheckPerms_hook;
 typedef struct Path Path;              /* avoid including pathnodes.h here */
 
 extern void ExecReScan(PlanState *node);
+extern void ExecReScanChildren(PlanState **children, int nchildren,
+                                                          Bitmapset *chgParam);
+extern void ExecInitDeferredChildRescan(DeferredChildRescan *dcr,
+                                                                               
int nchildren);
+extern void ExecDeferChildRescan(DeferredChildRescan *dcr,
+                                                                PlanState 
**children, int nchildren,
+                                                                Bitmapset 
*chgParam);
+extern void ExecCatchUpChildRescan(DeferredChildRescan *dcr,
+                                                                  PlanState 
*child, int childno);
 extern void ExecMarkPos(PlanState *node);
 extern void ExecRestrPos(PlanState *node);
 extern bool ExecSupportsMarkRestore(Path *pathnode);
@@ -328,6 +337,21 @@ ExecProcNode(PlanState *node)
 
        return node->ExecProcNode(node);
 }
+
+/*
+ * ExecPrepareDeferredChild
+ *
+ * Must be called before executing the childno'th child of a node that uses
+ * ExecDeferChildRescan(), to deliver any rescan signaling that was deferred.
+ */
+static inline void
+ExecPrepareDeferredChild(DeferredChildRescan *dcr, PlanState *child,
+                                                int childno)
+{
+       /* Is the child lagging, i.e. has it missed any rescans of its parent? 
*/
+       if (dcr->child_generation[childno] != dcr->generation)
+               ExecCatchUpChildRescan(dcr, child, childno);
+}
 #endif
 
 /*
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index e4fd53c383b..68f19356de3 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -1505,6 +1505,48 @@ typedef struct ModifyTableState
  */
 
 struct AppendState;
+
+/* ----------------
+ *      DeferredChildRescan information
+ *
+ *             Append and MergeAppend have to do changed-parameter signaling to
+ *             their child plans themselves when they are rescanned.  Doing 
that
+ *             eagerly costs O(number of children) per rescan, which is 
wasteful
+ *             when run-time partition pruning means that only a few of the
+ *             children will actually be executed before the next rescan, such 
as
+ *             on the inner side of a parameterized nested loop.  This struct 
lets
+ *             such nodes defer the signaling of each child until just before 
that
+ *             child is next executed; see ExecDeferChildRescan().
+ *
+ *             This works because the signaling is idempotent: a child that 
misses
+ *             several rescans in a row, all with the same chgParam set, ends 
up in
+ *             the same state whether it is signaled once per rescan or just 
once
+ *             before it next runs.  So for each child we only need to know 
whether
+ *             it has missed any rescans, and which chgParam set they had.
+ *
+ *             generation                      a clock, incremented on every 
rescan of the
+ *                                                     parent.
+ *             child_generation        per child, the value of generation when 
that
+ *                                                     child was last 
signaled.  A child is "up to
+ *                                                     date" when this equals 
generation, and
+ *                                                     "lagging" (it has 
missed at least one rescan)
+ *                                                     otherwise.  
Incrementing generation thus makes
+ *                                                     all children lagging 
without touching any of
+ *                                                     them.
+ *             pending_chgparam        the chgParam set of the rescans that 
lagging
+ *                                                     children have missed.  
One set suffices because
+ *                                                     all of those rescans 
used the same set: a rescan
+ *                                                     with a different set 
first brings all lagging
+ *                                                     children up to date 
using the old one.
+ * ----------------
+ */
+typedef struct DeferredChildRescan
+{
+       uint64          generation;
+       uint64     *child_generation;
+       Bitmapset  *pending_chgparam;
+} DeferredChildRescan;
+
 typedef struct AppendState AppendState;
 struct ParallelAppendState;
 typedef struct ParallelAppendState ParallelAppendState;
@@ -1536,6 +1578,7 @@ struct AppendState
        bool            as_valid_subplans_identified;   /* is as_valid_subplans 
valid? */
        Bitmapset  *as_valid_subplans;
        Bitmapset  *as_valid_asyncplans;        /* valid asynchronous plans 
indexes */
+       DeferredChildRescan as_child_rescan;    /* deferred rescan of subplans 
*/
        bool            (*choose_next_subplan) (AppendState *);
 };
 
@@ -1572,6 +1615,7 @@ typedef struct MergeAppendState
        Bitmapset  *ms_asyncpending;    /* async plans with an outstanding 
request */
        struct WaitEventSet *ms_eventset;       /* WaitEventSet used to 
configure file
                                                                                
 * descriptor wait events */
+       DeferredChildRescan ms_child_rescan;    /* deferred rescan of subplans 
*/
 } MergeAppendState;
 
 /* ----------------
diff --git a/src/test/regress/expected/partition_prune.out 
b/src/test/regress/expected/partition_prune.out
index 3506ecec477..a05fecee7a2 100644
--- a/src/test/regress/expected/partition_prune.out
+++ b/src/test/regress/expected/partition_prune.out
@@ -3456,6 +3456,180 @@ order by tbl1.col1, tprt.col1;
 (0 rows)
 
 drop table tbl1, tprt;
+-- Run-time pruning on the inner side of a nested loop whose outer side has
+-- runs of repeated values, NULLs, and changing values, so that the result of
+-- pruning is sometimes reused and sometimes recomputed.
+create table nlp_outer (id int, a int, b text);
+insert into nlp_outer values
+  (1, 1, 'a'), (2, 1, 'a'), (3, 1, 'a'), (4, 2, 'b'), (5, 2, 'b'),
+  (6, null, null), (7, null, null), (8, 1, 'b'), (9, 1, 'b'), (10, 3, 'c');
+create table nlp (a int, b text) partition by list (a);
+create table nlp_1 partition of nlp for values in (1) partition by list (b);
+create table nlp_1_a partition of nlp_1 for values in ('a');
+create table nlp_1_b partition of nlp_1 for values in ('b');
+create table nlp_2 partition of nlp for values in (2);
+create table nlp_3 partition of nlp for values in (3);
+create table nlp_null partition of nlp for values in (null);
+insert into nlp values (1, 'a'), (1, 'b'), (2, 'b'), (3, 'c'), (null, null);
+create index on nlp (a, b);
+create index on nlp_outer (id);
+create table nlph (a int, b text) partition by hash (a);
+create table nlph_0 partition of nlph for values with (modulus 4, remainder 0);
+create table nlph_1 partition of nlph for values with (modulus 4, remainder 1);
+create table nlph_2 partition of nlph for values with (modulus 4, remainder 2);
+create table nlph_3 partition of nlph for values with (modulus 4, remainder 3);
+insert into nlph select a, b from nlp;
+create index on nlph (b);
+analyze nlp_outer, nlp, nlph;
+set enable_hashjoin = off;
+set enable_mergejoin = off;
+set enable_material = off;
+set enable_memoize = off;
+set enable_seqscan = off;
+set enable_bitmapscan = off;
+set enable_sort = off;
+-- The outer scan's order must be stable for the expected loop counts.
+explain (analyze, costs off, summary off, timing off, buffers off)
+select * from (select * from nlp_outer order by id) o
+  join nlp n on n.a = o.a and n.b = o.b;
+                                       QUERY PLAN                              
         
+----------------------------------------------------------------------------------------
+ Nested Loop (actual rows=8.00 loops=1)
+   ->  Index Scan using nlp_outer_id_idx on nlp_outer (actual rows=10.00 
loops=1)
+         Index Searches: 1
+   ->  Append (actual rows=0.80 loops=10)
+         ->  Index Scan using nlp_1_a_a_b_idx on nlp_1_a n_1 (actual rows=1.00 
loops=3)
+               Index Cond: ((a = nlp_outer.a) AND (b = nlp_outer.b))
+               Index Searches: 3
+         ->  Index Scan using nlp_1_b_a_b_idx on nlp_1_b n_2 (actual rows=1.00 
loops=2)
+               Index Cond: ((a = nlp_outer.a) AND (b = nlp_outer.b))
+               Index Searches: 2
+         ->  Index Scan using nlp_2_a_b_idx on nlp_2 n_3 (actual rows=1.00 
loops=2)
+               Index Cond: ((a = nlp_outer.a) AND (b = nlp_outer.b))
+               Index Searches: 2
+         ->  Index Scan using nlp_3_a_b_idx on nlp_3 n_4 (actual rows=1.00 
loops=1)
+               Index Cond: ((a = nlp_outer.a) AND (b = nlp_outer.b))
+               Index Searches: 1
+         ->  Index Scan using nlp_null_a_b_idx on nlp_null n_5 (never executed)
+               Index Cond: ((a = nlp_outer.a) AND (b = nlp_outer.b))
+               Index Searches: 0
+(19 rows)
+
+select o.id, n.* from (select * from nlp_outer order by id) o
+  join nlp n on n.a = o.a and n.b = o.b;
+ id | a | b 
+----+---+---
+  1 | 1 | a
+  2 | 1 | a
+  3 | 1 | a
+  4 | 2 | b
+  5 | 2 | b
+  8 | 1 | b
+  9 | 1 | b
+ 10 | 3 | c
+(8 rows)
+
+-- Same, through a MergeAppend.
+explain (analyze, costs off, summary off, timing off, buffers off)
+select * from (select * from nlp_outer order by id) o,
+  lateral (select * from nlph n where n.a = o.a order by n.b limit 1) s;
+                                        QUERY PLAN                             
           
+------------------------------------------------------------------------------------------
+ Nested Loop (actual rows=8.00 loops=1)
+   ->  Index Scan using nlp_outer_id_idx on nlp_outer (actual rows=10.00 
loops=1)
+         Index Searches: 1
+   ->  Limit (actual rows=0.80 loops=10)
+         ->  Merge Append (actual rows=0.80 loops=10)
+               Sort Key: n.b
+               ->  Index Scan using nlph_0_b_idx on nlph_0 n_1 (actual 
rows=1.00 loops=5)
+                     Filter: (a = nlp_outer.a)
+                     Index Searches: 5
+               ->  Index Scan using nlph_1_b_idx on nlph_1 n_2 (actual 
rows=1.00 loops=1)
+                     Filter: (a = nlp_outer.a)
+                     Index Searches: 1
+               ->  Index Scan using nlph_2_b_idx on nlph_2 n_3 (actual 
rows=1.00 loops=2)
+                     Filter: (a = nlp_outer.a)
+                     Index Searches: 2
+               ->  Index Scan using nlph_3_b_idx on nlph_3 n_4 (never executed)
+                     Filter: (a = nlp_outer.a)
+                     Index Searches: 0
+(18 rows)
+
+select o.id, s.* from (select * from nlp_outer order by id) o,
+  lateral (select * from nlph n where n.a = o.a order by n.b limit 1) s;
+ id | a | b 
+----+---+---
+  1 | 1 | a
+  2 | 1 | a
+  3 | 1 | a
+  4 | 2 | b
+  5 | 2 | b
+  8 | 1 | a
+  9 | 1 | a
+ 10 | 3 | c
+(8 rows)
+
+-- Here the inner Append is rescanned alternately because of a change in o1.a
+-- and o2.b, so it doesn't always see the same set of changed Params.
+select o1.id, o2.id, n.* from nlp_outer o1, nlp_outer o2,
+  lateral (select * from nlp n where n.a = o1.a and n.b = o2.b offset 0) n
+order by 1, 2;
+ id | id | a | b 
+----+----+---+---
+  1 |  1 | 1 | a
+  1 |  2 | 1 | a
+  1 |  3 | 1 | a
+  1 |  4 | 1 | b
+  1 |  5 | 1 | b
+  1 |  8 | 1 | b
+  1 |  9 | 1 | b
+  2 |  1 | 1 | a
+  2 |  2 | 1 | a
+  2 |  3 | 1 | a
+  2 |  4 | 1 | b
+  2 |  5 | 1 | b
+  2 |  8 | 1 | b
+  2 |  9 | 1 | b
+  3 |  1 | 1 | a
+  3 |  2 | 1 | a
+  3 |  3 | 1 | a
+  3 |  4 | 1 | b
+  3 |  5 | 1 | b
+  3 |  8 | 1 | b
+  3 |  9 | 1 | b
+  4 |  4 | 2 | b
+  4 |  5 | 2 | b
+  4 |  8 | 2 | b
+  4 |  9 | 2 | b
+  5 |  4 | 2 | b
+  5 |  5 | 2 | b
+  5 |  8 | 2 | b
+  5 |  9 | 2 | b
+  8 |  1 | 1 | a
+  8 |  2 | 1 | a
+  8 |  3 | 1 | a
+  8 |  4 | 1 | b
+  8 |  5 | 1 | b
+  8 |  8 | 1 | b
+  8 |  9 | 1 | b
+  9 |  1 | 1 | a
+  9 |  2 | 1 | a
+  9 |  3 | 1 | a
+  9 |  4 | 1 | b
+  9 |  5 | 1 | b
+  9 |  8 | 1 | b
+  9 |  9 | 1 | b
+ 10 | 10 | 3 | c
+(44 rows)
+
+reset enable_hashjoin;
+reset enable_mergejoin;
+reset enable_material;
+reset enable_memoize;
+reset enable_seqscan;
+reset enable_bitmapscan;
+reset enable_sort;
+drop table nlp, nlph, nlp_outer;
 -- Test with columns defined in varying orders between each level
 create table part_abc (a int not null, b int not null, c int not null) 
partition by list (a);
 create table part_bac (b int not null, a int not null, c int not null) 
partition by list (b);
diff --git a/src/test/regress/sql/partition_prune.sql 
b/src/test/regress/sql/partition_prune.sql
index d6e096dc565..997e2338b91 100644
--- a/src/test/regress/sql/partition_prune.sql
+++ b/src/test/regress/sql/partition_prune.sql
@@ -897,6 +897,72 @@ order by tbl1.col1, tprt.col1;
 
 drop table tbl1, tprt;
 
+-- Run-time pruning on the inner side of a nested loop whose outer side has
+-- runs of repeated values, NULLs, and changing values, so that the result of
+-- pruning is sometimes reused and sometimes recomputed.
+create table nlp_outer (id int, a int, b text);
+insert into nlp_outer values
+  (1, 1, 'a'), (2, 1, 'a'), (3, 1, 'a'), (4, 2, 'b'), (5, 2, 'b'),
+  (6, null, null), (7, null, null), (8, 1, 'b'), (9, 1, 'b'), (10, 3, 'c');
+create table nlp (a int, b text) partition by list (a);
+create table nlp_1 partition of nlp for values in (1) partition by list (b);
+create table nlp_1_a partition of nlp_1 for values in ('a');
+create table nlp_1_b partition of nlp_1 for values in ('b');
+create table nlp_2 partition of nlp for values in (2);
+create table nlp_3 partition of nlp for values in (3);
+create table nlp_null partition of nlp for values in (null);
+insert into nlp values (1, 'a'), (1, 'b'), (2, 'b'), (3, 'c'), (null, null);
+create index on nlp (a, b);
+create index on nlp_outer (id);
+create table nlph (a int, b text) partition by hash (a);
+create table nlph_0 partition of nlph for values with (modulus 4, remainder 0);
+create table nlph_1 partition of nlph for values with (modulus 4, remainder 1);
+create table nlph_2 partition of nlph for values with (modulus 4, remainder 2);
+create table nlph_3 partition of nlph for values with (modulus 4, remainder 3);
+insert into nlph select a, b from nlp;
+create index on nlph (b);
+analyze nlp_outer, nlp, nlph;
+
+set enable_hashjoin = off;
+set enable_mergejoin = off;
+set enable_material = off;
+set enable_memoize = off;
+set enable_seqscan = off;
+set enable_bitmapscan = off;
+set enable_sort = off;
+
+-- The outer scan's order must be stable for the expected loop counts.
+explain (analyze, costs off, summary off, timing off, buffers off)
+select * from (select * from nlp_outer order by id) o
+  join nlp n on n.a = o.a and n.b = o.b;
+
+select o.id, n.* from (select * from nlp_outer order by id) o
+  join nlp n on n.a = o.a and n.b = o.b;
+
+-- Same, through a MergeAppend.
+explain (analyze, costs off, summary off, timing off, buffers off)
+select * from (select * from nlp_outer order by id) o,
+  lateral (select * from nlph n where n.a = o.a order by n.b limit 1) s;
+
+select o.id, s.* from (select * from nlp_outer order by id) o,
+  lateral (select * from nlph n where n.a = o.a order by n.b limit 1) s;
+
+-- Here the inner Append is rescanned alternately because of a change in o1.a
+-- and o2.b, so it doesn't always see the same set of changed Params.
+select o1.id, o2.id, n.* from nlp_outer o1, nlp_outer o2,
+  lateral (select * from nlp n where n.a = o1.a and n.b = o2.b offset 0) n
+order by 1, 2;
+
+reset enable_hashjoin;
+reset enable_mergejoin;
+reset enable_material;
+reset enable_memoize;
+reset enable_seqscan;
+reset enable_bitmapscan;
+reset enable_sort;
+
+drop table nlp, nlph, nlp_outer;
+
 -- Test with columns defined in varying orders between each level
 create table part_abc (a int not null, b int not null, c int not null) 
partition by list (a);
 create table part_bac (b int not null, a int not null, c int not null) 
partition by list (b);
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..b0bb9123ffd 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -663,6 +663,7 @@ DecodingWorkerShared
 DefElem
 DefElemAction
 DefaultACLInfo
+DeferredChildRescan
 DefineStmt
 DefnDumperPtr
 DeleteStmt
-- 
2.50.1 (Apple Git-155)

From af2876571011f51bce8fe4d240df9aa038229814 Mon Sep 17 00:00:00 2001
From: Matheus Alcantara <[email protected]>
Date: Mon, 23 Nov 2026 19:15:05 -0300
Subject: [PATCH v1 2/2] Skip run-time partition re-pruning when the parameter
 values are unchanged

When an Append or MergeAppend node with run-time ("exec") pruning was
rescanned with any of its pruning parameters marked as changed, it
always threw away the set of valid subplans and redid the pruning.
However, the parameters are often marked as changed when their values
are in fact the same; for example, a nested loop marks all its
parameters as changed for every outer row, even when consecutive outer
rows have the same values.

So, remember the parameter values used for the last exec pruning, and
on rescan only redo the pruning if one of them actually differs.  Values
are compared with datumIsEqual(), so a value that is equal but not
binary-identical just leads to a harmless re-prune.  We don't attempt
to remember external (e.g. toasted) varlena values, nor values of
InitPlan params that haven't been computed yet; in those cases, we
always re-prune.

Since a parallel-aware Append can now keep its valid subplans across a
rescan, the leader must mark the invalid subplans as finished whenever
it starts a scan, as ExecAppendReInitializeDSM resets that state.
---
 src/backend/executor/execPartition.c   | 260 +++++++++++++++++++++++++
 src/backend/executor/nodeAppend.c      |  17 +-
 src/backend/executor/nodeMergeAppend.c |   4 +-
 src/include/executor/execPartition.h   |  28 +++
 src/tools/pgindent/typedefs.list       |   1 +
 5 files changed, 301 insertions(+), 9 deletions(-)

diff --git a/src/backend/executor/execPartition.c 
b/src/backend/executor/execPartition.c
index a7ec585763e..afb838374aa 100644
--- a/src/backend/executor/execPartition.c
+++ b/src/backend/executor/execPartition.c
@@ -24,16 +24,19 @@
 #include "foreign/fdwapi.h"
 #include "mb/pg_wchar.h"
 #include "miscadmin.h"
+#include "nodes/nodeFuncs.h"
 #include "partitioning/partbounds.h"
 #include "partitioning/partdesc.h"
 #include "partitioning/partprune.h"
 #include "rewrite/rewriteManip.h"
 #include "utils/acl.h"
+#include "utils/datum.h"
 #include "utils/injection_point.h"
 #include "utils/lsyscache.h"
 #include "utils/partcache.h"
 #include "utils/rls.h"
 #include "utils/ruleutils.h"
+#include "varatt.h"
 
 
 /*-----------------------
@@ -197,6 +200,10 @@ static void 
InitExecPartitionPruneContexts(PartitionPruneState *prunestate,
                                                                                
   PlanState *parent_plan,
                                                                                
   Bitmapset *initially_valid_subplans,
                                                                                
   int n_total_subplans);
+static void InitExecParamTracking(PartitionPruneState *prunestate);
+static bool find_exec_param_types_walker(Node *node,
+                                                                               
 PartitionPruneState *prunestate);
+static void save_exec_param_values(PartitionPruneState *prunestate);
 static void find_matching_subplans_recurse(PartitionPruningData *prunedata,
                                                                                
   PartitionedRelPruningData *pprune,
                                                                                
   bool initial_prune,
@@ -2146,6 +2153,10 @@ CreatePartitionPruneState(EState *estate, 
PartitionPruneInfo *pruneinfo,
        prunestate->other_subplans = bms_copy(pruneinfo->other_subplans);
        prunestate->do_initial_prune = false;   /* may be set below */
        prunestate->do_exec_prune = false;      /* may be set below */
+       prunestate->nexecparams = 0;
+       prunestate->execparams = NULL;
+       prunestate->execparams_valid = false;
+       prunestate->execparam_context = NULL;
        prunestate->num_partprunedata = n_part_hierarchies;
 
        /*
@@ -2368,9 +2379,126 @@ CreatePartitionPruneState(EState *estate, 
PartitionPruneInfo *pruneinfo,
                i++;
        }
 
+       if (prunestate->do_exec_prune)
+               InitExecParamTracking(prunestate);
+
        return prunestate;
 }
 
+/*
+ * InitExecParamTracking
+ *             Set up prunestate->execparams, which 
ExecPartitionPruneParamsChanged
+ *             uses to detect whether exec pruning needs to be performed again.
+ *
+ * We need the type of each Param to be able to compare and copy its value,
+ * so dig the Params out of the exec pruning steps.  If for some reason we
+ * don't find all of them, leave execparams NULL, which means that pruning
+ * will be done again every time any of the Params is reported as changed.
+ */
+static void
+InitExecParamTracking(PartitionPruneState *prunestate)
+{
+       int                     nparams = 
bms_num_members(prunestate->execparamids);
+       int                     paramid;
+       int                     i;
+       bool            need_context = false;
+
+       /* No Params used by exec pruning, so nothing to track */
+       if (nparams == 0)
+               return;
+
+       /* One entry per Param, in execparamids order; types are filled in 
below */
+       prunestate->nexecparams = nparams;
+       prunestate->execparams = palloc0_array(PartitionPruneParam, nparams);
+       i = 0;
+       paramid = -1;
+       while ((paramid = bms_next_member(prunestate->execparamids, paramid)) 
>= 0)
+               prunestate->execparams[i++].paramid = paramid;
+
+       /* Look for the Params in the exec pruning steps of every partitioned 
rel */
+       for (i = 0; i < prunestate->num_partprunedata; i++)
+       {
+               PartitionPruningData *prunedata = prunestate->partprunedata[i];
+
+               for (int j = 0; j < prunedata->num_partrelprunedata; j++)
+               {
+                       PartitionedRelPruningData *pprune = 
&prunedata->partrelprunedata[j];
+                       ListCell   *lc;
+
+                       foreach(lc, pprune->exec_pruning_steps)
+                       {
+                               PartitionPruneStepOp *step = lfirst(lc);
+
+                               /* Only "op" steps have expressions; combine 
steps don't */
+                               if (!IsA(step, PartitionPruneStepOp))
+                                       continue;
+
+                               (void) find_exec_param_types_walker((Node *) 
step->exprs,
+                                                                               
                        prunestate);
+                       }
+               }
+       }
+
+       /* Check that every Param was found, and whether any is pass-by-ref */
+       for (i = 0; i < nparams; i++)
+       {
+               PartitionPruneParam *pp = &prunestate->execparams[i];
+
+               /* typlen is never 0 for a valid type, so this one wasn't found 
*/
+               if (pp->typlen == 0)
+               {
+                       /* Give up on tracking; always re-prune when Params 
change */
+                       pfree(prunestate->execparams);
+                       prunestate->execparams = NULL;
+                       prunestate->nexecparams = 0;
+                       return;
+               }
+
+               /* Pass-by-ref values must be copied, see 
save_exec_param_values */
+               if (!pp->typbyval)
+                       need_context = true;
+       }
+
+       /* Create memory context for the saved copies of pass-by-ref values */
+       if (need_context)
+               prunestate->execparam_context =
+                       AllocSetContextCreate(CurrentMemoryContext,
+                                                                 "Partition 
Prune Params",
+                                                                 
ALLOCSET_SMALL_SIZES);
+}
+
+/*
+ * find_exec_param_types_walker
+ *             Fill in the type details of each entry in 
prunestate->execparams.
+ */
+static bool
+find_exec_param_types_walker(Node *node, PartitionPruneState *prunestate)
+{
+       if (node == NULL)
+               return false;
+
+       if (IsA(node, Param))
+       {
+               Param      *param = (Param *) node;
+
+               if (param->paramkind != PARAM_EXEC)
+                       return false;
+
+               for (int i = 0; i < prunestate->nexecparams; i++)
+               {
+                       PartitionPruneParam *pp = &prunestate->execparams[i];
+
+                       if (pp->paramid == param->paramid && pp->typlen == 0)
+                               get_typlenbyval(param->paramtype, &pp->typlen,
+                                                               &pp->typbyval);
+               }
+               return false;
+       }
+
+       return expression_tree_walker(node, find_exec_param_types_walker,
+                                                                 prunestate);
+}
+
 /*
  * Initialize a PartitionPruneContext for the given list of pruning steps.
  */
@@ -2693,9 +2821,141 @@ ExecFindMatchingSubPlans(PartitionPruneState 
*prunestate,
 
        MemoryContextReset(prunestate->prune_context);
 
+       /*
+        * Remember the values of the Params that this result is based on, so 
that
+        * ExecPartitionPruneParamsChanged can tell if it can be reused.
+        */
+       if (!initial_prune && prunestate->execparams != NULL)
+               save_exec_param_values(prunestate);
+
        return result;
 }
 
+/*
+ * ExecPartitionPruneParamsChanged
+ *             Determine whether exec pruning must be performed again, given 
that
+ *             the parent plan node is being rescanned with the given chgParam.
+ *
+ * Exec pruning has to be redone whenever the value of any of the Params in
+ * prunestate->execparamids changes.  However, plan nodes that set Params,
+ * such as a parameterized Nested Loop, report a Param as changed each time
+ * they set it, even if its new value is the same as before.  To avoid
+ * pointless work in that case, compare the current values with the values
+ * that were used by the last exec pruning.  The values are compared using
+ * datumIsEqual(), so values that are equal but have a different binary
+ * representation will be considered as changed, which is harmless.
+ */
+bool
+ExecPartitionPruneParamsChanged(PartitionPruneState *prunestate,
+                                                               Bitmapset 
*chgParam)
+{
+       ParamExecData *paramvals;
+
+       /* None of the Params used by exec pruning was reported as changed */
+       if (!bms_overlap(chgParam, prunestate->execparamids))
+               return false;
+
+       /*
+        * No saved values to compare with: tracking is disabled, pruning hasn't
+        * been done yet, or the last save gave up partway.
+        */
+       if (!prunestate->execparams_valid)
+               return true;
+
+       paramvals = prunestate->econtext->ecxt_param_exec_vals;
+       for (int i = 0; i < prunestate->nexecparams; i++)
+       {
+               PartitionPruneParam *pp = &prunestate->execparams[i];
+               ParamExecData *prm = &paramvals[pp->paramid];
+
+               /* Not reported as changed, so its saved value still holds */
+               if (!bms_is_member(pp->paramid, chgParam))
+                       continue;
+
+               /* An InitPlan output that hasn't been recomputed yet */
+               if (prm->execPlan != NULL)
+                       return true;
+
+               /* Changed between NULL and non-NULL */
+               if (prm->isnull != pp->isnull)
+                       return true;
+
+               /* Both NULL, so equal */
+               if (prm->isnull)
+                       continue;
+
+               /* We don't save TOAST pointers, see save_exec_param_values */
+               if (pp->typlen == -1 &&
+                       VARATT_IS_EXTERNAL(DatumGetPointer(prm->value)))
+                       return true;
+
+               if (!datumIsEqual(prm->value, pp->value, pp->typbyval, 
pp->typlen))
+                       return true;
+       }
+
+       /* Every changed Param has the same value as at the last pruning */
+       return false;
+}
+
+/*
+ * save_exec_param_values
+ *             Save the current values of the Params in prunestate->execparams.
+ */
+static void
+save_exec_param_values(PartitionPruneState *prunestate)
+{
+       ParamExecData *paramvals = prunestate->econtext->ecxt_param_exec_vals;
+       MemoryContext oldcontext;
+
+       /*
+        * Invalidate first: the reset below frees the memory the saved values
+        * point to, and we may give up partway through the loop.
+        */
+       prunestate->execparams_valid = false;
+
+       /*
+        * Free the copies saved by the previous call, which are no longer 
needed.
+        * Otherwise every re-prune would leak a copy of each pass-by-ref value.
+        * The context is only created if some Param is pass-by-ref.
+        */
+       if (prunestate->execparam_context != NULL)
+               MemoryContextReset(prunestate->execparam_context);
+
+       for (int i = 0; i < prunestate->nexecparams; i++)
+       {
+               PartitionPruneParam *pp = &prunestate->execparams[i];
+               ParamExecData *prm = &paramvals[pp->paramid];
+
+               /*
+                * If an InitPlan output wasn't computed because the pruning 
steps
+                * didn't need it, we don't know what value the result is based 
on.
+                */
+               if (prm->execPlan != NULL)
+                       return;
+
+               pp->isnull = prm->isnull;
+               if (prm->isnull || pp->typbyval)
+               {
+                       pp->value = prm->value;
+                       continue;
+               }
+
+               /*
+                * Don't try to remember TOAST pointers or expanded objects, 
since
+                * comparing those wouldn't tell us whether the value is the 
same.
+                */
+               if (pp->typlen == -1 &&
+                       VARATT_IS_EXTERNAL(DatumGetPointer(prm->value)))
+                       return;
+
+               oldcontext = 
MemoryContextSwitchTo(prunestate->execparam_context);
+               pp->value = datumCopy(prm->value, false, pp->typlen);
+               MemoryContextSwitchTo(oldcontext);
+       }
+
+       prunestate->execparams_valid = true;
+}
+
 /*
  * find_matching_subplans_recurse
  *             Recursive worker function for ExecFindMatchingSubPlans
diff --git a/src/backend/executor/nodeAppend.c 
b/src/backend/executor/nodeAppend.c
index a2a82ea67e4..b66b1650fac 100644
--- a/src/backend/executor/nodeAppend.c
+++ b/src/backend/executor/nodeAppend.c
@@ -432,8 +432,8 @@ ExecReScanAppend(AppendState *node)
         * the new parameter values.
         */
        if (node->as_prune_state &&
-               bms_overlap(node->ps.chgParam,
-                                       node->as_prune_state->execparamids))
+               ExecPartitionPruneParamsChanged(node->as_prune_state,
+                                                                               
node->ps.chgParam))
        {
                node->as_valid_subplans_identified = false;
                bms_free(node->as_valid_subplans);
@@ -648,13 +648,16 @@ choose_next_subplan_for_leader(AppendState *node)
                        node->as_valid_subplans =
                                ExecFindMatchingSubPlans(node->as_prune_state, 
false, NULL);
                        node->as_valid_subplans_identified = true;
+               }
 
-                       /*
-                        * Mark each invalid plan as finished to allow the loop 
below to
-                        * select the first valid subplan.
-                        */
+               /*
+                * Mark each invalid plan as finished to allow the loop below to
+                * select the first valid subplan.  We must do this even if the 
valid
+                * subplans were kept from before a rescan, since
+                * ExecAppendReInitializeDSM will have reset pa_finished.
+                */
+               if (node->as_prune_state)
                        mark_invalid_subplans_as_finished(node);
-               }
        }
 
        /* Loop until we find a subplan to execute. */
diff --git a/src/backend/executor/nodeMergeAppend.c 
b/src/backend/executor/nodeMergeAppend.c
index 235e623c340..eadfc700fb9 100644
--- a/src/backend/executor/nodeMergeAppend.c
+++ b/src/backend/executor/nodeMergeAppend.c
@@ -482,8 +482,8 @@ ExecReScanMergeAppend(MergeAppendState *node)
         * the new parameter values.
         */
        if (node->ms_prune_state &&
-               bms_overlap(node->ps.chgParam,
-                                       node->ms_prune_state->execparamids))
+               ExecPartitionPruneParamsChanged(node->ms_prune_state,
+                                                                               
node->ps.chgParam))
        {
                bms_free(node->ms_valid_subplans);
                node->ms_valid_subplans = NULL;
diff --git a/src/include/executor/execPartition.h 
b/src/include/executor/execPartition.h
index 12ad870d55a..ff7c4c34fce 100644
--- a/src/include/executor/execPartition.h
+++ b/src/include/executor/execPartition.h
@@ -87,6 +87,19 @@ typedef struct PartitionPruningData
        pg_attribute_counted_by(num_partrelprunedata) PartitionedRelPruningData 
partrelprunedata[FLEXIBLE_ARRAY_MEMBER];
 } PartitionPruningData;
 
+/*
+ * PartitionPruneParam - Holds the value that a PARAM_EXEC Param used in exec
+ * pruning steps had the last time exec pruning was performed.
+ */
+typedef struct PartitionPruneParam
+{
+       int                     paramid;
+       int16           typlen;
+       bool            typbyval;
+       bool            isnull;
+       Datum           value;
+} PartitionPruneParam;
+
 /*
  * PartitionPruneState - State object required for plan nodes to perform
  * run-time partition pruning.
@@ -113,6 +126,15 @@ typedef struct PartitionPruningData
  *                                             startup (at any hierarchy 
level).
  * do_exec_prune               true if pruning should be performed during
  *                                             executor run (at any hierarchy 
level).
+ * nexecparams                 Number of entries in execparams.
+ * execparams                  Values of the Params in execparamids as of the 
last
+ *                                             exec pruning, used by 
ExecPartitionPruneParamsChanged
+ *                                             to skip pruning again when none 
of them changed.
+ *                                             NULL if we're not able to do 
that.
+ * execparams_valid            true if execparams holds the values used by the 
last
+ *                                             exec pruning.
+ * execparam_context   Memory context holding copies of pass-by-reference
+ *                                             values in execparams.
  * num_partprunedata   Number of items in "partprunedata" array.
  * partprunedata               Array of PartitionPruningData pointers for the 
plan's
  *                                             partitioned relation(s), one 
for each partitioning
@@ -126,6 +148,10 @@ typedef struct PartitionPruneState
        MemoryContext prune_context;
        bool            do_initial_prune;
        bool            do_exec_prune;
+       int                     nexecparams;
+       PartitionPruneParam *execparams;
+       bool            execparams_valid;
+       MemoryContext execparam_context;
        int                     num_partprunedata;
        pg_attribute_counted_by(num_partprunedata) PartitionPruningData 
*partprunedata[FLEXIBLE_ARRAY_MEMBER];
 } PartitionPruneState;
@@ -137,6 +163,8 @@ extern PartitionPruneState 
*ExecInitPartitionExecPruning(PlanState *planstate,
                                                                                
                                 int part_prune_index,
                                                                                
                                 Bitmapset *relids,
                                                                                
                                 Bitmapset **initially_valid_subplans);
+extern bool ExecPartitionPruneParamsChanged(PartitionPruneState *prunestate,
+                                                                               
        Bitmapset *chgParam);
 extern Bitmapset *ExecFindMatchingSubPlans(PartitionPruneState *prunestate,
                                                                                
   bool initial_prune,
                                                                                
   Bitmapset **validsubplan_rtis);
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index b0bb9123ffd..987e664ab7e 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2204,6 +2204,7 @@ PartitionMap
 PartitionPruneCombineOp
 PartitionPruneContext
 PartitionPruneInfo
+PartitionPruneParam
 PartitionPruneState
 PartitionPruneStep
 PartitionPruneStepCombine
-- 
2.50.1 (Apple Git-155)

Attachment: partprune-benchmark.pdf
Description: Adobe PDF document

Reply via email to