From e9a77de3adf857c6af46e3d106ec354e150bcfd9 Mon Sep 17 00:00:00 2001 From: Chengpeng Yan Date: Sat, 5 Dec 2026 13:08:52 +0800 Subject: [PATCH v3 1/2] Refactor make_sort_input_target() to separate phases and reuse costs Store per-column state in a workspace struct and finish deciding which columns to postpone (and pulling out their inputs) before building the sort-input PathTarget, so additional postponement rules can be layered in cleanly. Also extract add_pathtarget_expr_cost_width() so target construction can reuse the per-column eval costs already computed for the expensive-expression check, instead of recomputing them with set_pathtarget_cost_width(). --- src/backend/optimizer/path/costsize.c | 43 +++++++----- src/backend/optimizer/plan/planner.c | 97 +++++++++++++++++---------- src/include/optimizer/cost.h | 3 + src/tools/pgindent/typedefs.list | 1 + 4 files changed, 92 insertions(+), 52 deletions(-) diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c index f760ef9aa3a..ea4af820447 100644 --- a/src/backend/optimizer/path/costsize.c +++ b/src/backend/optimizer/path/costsize.c @@ -6625,33 +6625,46 @@ set_rel_width(PlannerInfo *root, RelOptInfo *rel) PathTarget * set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target) { - int64 tuple_width = 0; ListCell *lc; - /* Vars are assumed to have cost zero, but other exprs do not */ target->cost.startup = 0; target->cost.per_tuple = 0; + target->width = 0; foreach(lc, target->exprs) - { - Node *node = (Node *) lfirst(lc); + add_pathtarget_expr_cost_width(root, target, (Node *) lfirst(lc), + NULL); - tuple_width += get_expr_width(root, node); + return target; +} - /* For non-Vars, account for evaluation cost */ - if (!IsA(node, Var)) - { - QualCost cost; +/* + * add_pathtarget_expr_cost_width + * Add one column's estimated eval cost and output width to a PathTarget. + * + * If 'cost' isn't NULL, it is the expression's eval cost as already computed + * by cost_qual_eval_node(). + */ +void +add_pathtarget_expr_cost_width(PlannerInfo *root, PathTarget *target, + Node *expr, const QualCost *cost) +{ + /* Vars are assumed to have cost zero, but other exprs do not */ + if (!IsA(expr, Var)) + { + QualCost exprcost; - cost_qual_eval_node(&cost, node, root); - target->cost.startup += cost.startup; - target->cost.per_tuple += cost.per_tuple; + if (cost == NULL) + { + cost_qual_eval_node(&exprcost, expr, root); + cost = &exprcost; } + target->cost.startup += cost->startup; + target->cost.per_tuple += cost->per_tuple; } - target->width = clamp_width_est(tuple_width); - - return target; + target->width = clamp_width_est((int64) target->width + + get_expr_width(root, expr)); } /* diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 568a1b2a346..bcb7a720b49 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -6654,6 +6654,17 @@ make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, return window_pathkeys; } +/* Per-column workspace for make_sort_input_target() */ +typedef struct SortInputCol +{ + Expr *expr; + Index sortgroupref; + bool is_srf; + bool postpone; + bool have_cost; /* whether cost below is populated */ + QualCost cost; +} SortInputCol; + /* * make_sort_input_target * Generate appropriate PathTarget for initial input to Sort step. @@ -6727,9 +6738,8 @@ make_sort_input_target(PlannerInfo *root, { Query *parse = root->parse; PathTarget *input_target; + SortInputCol *cols; int ncols; - bool *col_is_srf; - bool *postpone_col; bool have_srf; bool have_volatile; bool have_expensive; @@ -6747,15 +6757,18 @@ make_sort_input_target(PlannerInfo *root, /* Inspect tlist and collect per-column information */ ncols = list_length(final_target->exprs); - col_is_srf = palloc0_array(bool, ncols); - postpone_col = palloc0_array(bool, ncols); + cols = palloc0_array(SortInputCol, ncols); have_srf = have_volatile = have_expensive = have_srf_sortcols = false; i = 0; foreach(lc, final_target->exprs) { + SortInputCol *col = &cols[i]; Expr *expr = (Expr *) lfirst(lc); + col->expr = expr; + col->sortgroupref = get_pathtarget_sortgroupref(final_target, i); + /* * If the column has a sortgroupref, assume it has to be evaluated * before sorting. Generally such columns would be ORDER BY, GROUP @@ -6764,7 +6777,7 @@ make_sort_input_target(PlannerInfo *root, * only be Vars anyway. There don't seem to be any cases where it * would be worth the trouble to double-check. */ - if (get_pathtarget_sortgroupref(final_target, i) == 0) + if (col->sortgroupref == 0) { /* * Check for SRF or volatile functions. Check the SRF case first @@ -6774,13 +6787,13 @@ make_sort_input_target(PlannerInfo *root, expression_returns_set((Node *) expr)) { /* We'll decide below whether these are postponable */ - col_is_srf[i] = true; + col->is_srf = true; have_srf = true; } else if (contain_volatile_functions((Node *) expr)) { /* Unconditionally postpone */ - postpone_col[i] = true; + col->postpone = true; have_volatile = true; } else @@ -6790,18 +6803,17 @@ make_sort_input_target(PlannerInfo *root, * when set_pathtarget_cost_width() just did it. Refactor to * allow sharing the work? */ - QualCost cost; - - cost_qual_eval_node(&cost, (Node *) expr, root); + cost_qual_eval_node(&col->cost, (Node *) expr, root); + col->have_cost = true; /* * We arbitrarily define "expensive" as "more than 10X * cpu_operator_cost". Note this will take in any PL function * with default cost. */ - if (cost.per_tuple > 10 * cpu_operator_cost) + if (col->cost.per_tuple > 10 * cpu_operator_cost) { - postpone_col[i] = true; + col->postpone = true; have_expensive = true; } } @@ -6839,47 +6851,58 @@ make_sort_input_target(PlannerInfo *root, */ *have_postponed_srfs = postpone_srfs; - /* - * Construct the sort-input target, taking all non-postponable columns and - * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in - * the postponable ones. - */ - input_target = create_empty_pathtarget(); + /* Collect postponable columns */ postponable_cols = NIL; - - i = 0; - foreach(lc, final_target->exprs) + for (i = 0; i < ncols; i++) { - Expr *expr = (Expr *) lfirst(lc); + SortInputCol *col = &cols[i]; - if (postpone_col[i] || (postpone_srfs && col_is_srf[i])) - postponable_cols = lappend(postponable_cols, expr); - else - add_column_to_pathtarget(input_target, expr, - get_pathtarget_sortgroupref(final_target, i)); - - i++; + if (postpone_srfs && col->is_srf) + col->postpone = true; + if (col->postpone) + postponable_cols = lappend(postponable_cols, col->expr); } /* - * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in - * postponable columns, and add them to the sort-input target if not - * already present. (Some might be there already.) We mustn't - * deconstruct Aggrefs or WindowFuncs here, since the projection node - * would be unable to recompute them. + * Pull out all the Vars, PlaceHolderVars, Aggrefs, GroupingFuncs, and + * WindowFuncs mentioned in postponable columns. We mustn't deconstruct + * Aggrefs or WindowFuncs here, since the projection node would be unable + * to recompute them. */ postponable_vars = pull_var_clause((Node *) postponable_cols, PVC_INCLUDE_AGGREGATES | PVC_INCLUDE_WINDOWFUNCS | PVC_INCLUDE_PLACEHOLDERS); - add_new_columns_to_pathtarget(input_target, postponable_vars); + + /* Construct sort-input target, accumulating cost and width as we go */ + input_target = create_empty_pathtarget(); + + for (i = 0; i < ncols; i++) + { + SortInputCol *col = &cols[i]; + + if (col->postpone) + continue; + add_column_to_pathtarget(input_target, col->expr, col->sortgroupref); + add_pathtarget_expr_cost_width(root, input_target, (Node *) col->expr, + col->have_cost ? &col->cost : NULL); + } + + foreach(lc, postponable_vars) + { + Node *var = (Node *) lfirst(lc); + + if (list_member(input_target->exprs, var)) + continue; + add_column_to_pathtarget(input_target, (Expr *) var, 0); + add_pathtarget_expr_cost_width(root, input_target, var, NULL); + } /* clean up cruft */ list_free(postponable_vars); list_free(postponable_cols); - /* XXX this represents even more redundant cost calculation ... */ - return set_pathtarget_cost_width(root, input_target); + return input_target; } /* diff --git a/src/include/optimizer/cost.h b/src/include/optimizer/cost.h index 19f8753e2d8..baf39399ae3 100644 --- a/src/include/optimizer/cost.h +++ b/src/include/optimizer/cost.h @@ -221,6 +221,9 @@ extern void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *re extern void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel); extern void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel); extern PathTarget *set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target); +extern void add_pathtarget_expr_cost_width(PlannerInfo *root, + PathTarget *target, + Node *expr, const QualCost *cost); extern double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 278b2f3194b..1145df6437e 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2947,6 +2947,7 @@ SortByNulls SortCoordinate SortCoordinateData SortGroupClause +SortInputCol SortItem SortPath SortShimExtra -- 2.50.1 (Apple Git-155)