From af2876571011f51bce8fe4d240df9aa038229814 Mon Sep 17 00:00:00 2001 From: Matheus Alcantara 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 = ¶mvals[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 = ¶mvals[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)