Optimize mergejoinscansel() by avoiding redundant computations
Optimize mergejoinscansel() by avoiding redundant computations
От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi While working on https://commitfest.postgresql.org/patch/7302/, I noticed another potential optimization, so I'm starting a separate thread to discuss it. I've been looking into potential optimizations in mergejoinscansel() and would appreciate feedback on whether this approach is worth pursuing. 1. Potential optimization In mergejoinscansel(), when left and right are base simple Vars referring to the same attribute of the same base relation, it may be possible to avoid the second call to examine_variable() and reuse the first VariableStatData. Furthermore, under suitably strict conditions, the second calls to get_variable_range() and scalarineqsel() may also be avoidable by reusing the results of the corresponding first calls. My initial focus is on this straightforward base-simple-Var case, where the equivalence conditions are relatively easy to establish. 2. Motivation The relevant call stack is: initial_cost_mergejoin() --> cached_scansel() --> mergejoinscansel() In initial_cost_mergejoin(), the comments for non-full joins with merge clauses describe mergejoinscansel() as a fairly expensive computation and explain that its results are cached in the merge clause's RestrictInfo. This caching avoids repeating the computation for the same merge clause. However, there may still be opportunities to eliminate redundant work within an individual call to mergejoinscansel(). 3. A common use case Consider the following query: ```SQL SELECT a.reltype FROM pg_class_1 a, pg_class_1 b WHERE a.reltype = b.reltype; Equality conditions between corresponding columns of two aliases of the same table are a common query pattern. I would like to explore whether optimizing the internal calls to examine_variable(), get_variable_range() and scalarineqsel() can further reduce planning overhead in such cases. 4. Preliminary implementation and performance results I've put together a small proof of concept targeting the case where both operands are simple Vars, and performed preliminary performance measurements. I added timing output to mergejoinscansel() to measure its contribution directly. The execution plans produced by the planner were identical between master and the patch. The following results were obtained from 128 consecutive measurements for each case: | Metric | Master | Patch | Improvement | | mergejoinscansel() | 0.117 ms | 0.064 ms | 45.03% | | Planning Time | 1.880 ms | 1.835 ms | 2.39% | For each set of 128 measurements, I excluded the first measurement, removed the maximum and minimum values from the remaining measurements, and calculated the arithmetic mean of the rest. DEBUG instrumentation also confirmed that, in this base-simple-Var case, the number of calls to each of the targeted functions (examine_variable(), get_variable_range() and scalarineqsel()) was reduced by approximately half. The reduction in mergejoinscansel() execution time is consistent with the reduced number of function calls, while the overall planning-time improvement is smaller. 5. Further cases The current implementation focuses on direct base-Var operands. Other cases may offer additionaloptimization opportunities, but they could be more complicated and would need careful analysis. For example: ```SQL SELECT oid FROM pg_catalog.pg_class WHERE oid IN (SELECT oid FROM pg_catalog.pg_class LIMIT 1); I have not yet investigated these cases in detail. I've attached the SQL and shell scripts used for testing (not_same_var.sql, not_same_var.sh, same_var.sql and same_var.sh), along with base_var_perf_test_data_analyze.xlsx, which includes the shell commands used to extract the performance metrics. I'd appreciate feedback on the approach, particularly on the correctness of the proposed reuse conditions, other cases worth considering, and whether the measured improvement justifies pursuing this optimization. If others find this direction promising, I'll continue investigating it and work on a more complete patch. Thanks for your time and feedback. regards, -- ZizhuanLiu (X-MAN) 44973863@qq.com
Re: Optimize mergejoinscansel() by avoiding redundant computations
От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Hi,
Sorry, I forgot to include the initialization SQL.
drop table if exists pg_class_1;
drop table if exists pg_class_2;
select max(oid) from pg_catalog.pg_class;
create table pg_class_1 as select * from pg_catalog.pg_class where oid < 13673 WITH DATA;
create table pg_class_2 as select * from pg_class_1 WITH DATA;
analyze pg_class_1, pg_class_2;
select count(*) from pg_class_1;
select count(*) from pg_class_2;
explain (summary) select a.reltype from pg_class_1 a, pg_class_1 b where a.reltype = b.reltype;
explain (summary) select a.reltype from pg_class_1 a, pg_class_2 b where a.reltype = b.reltype;
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Re: Optimize mergejoinscansel() by avoiding redundant computations
От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Optimize mergejoinscansel() by avoiding redundant computations
0. Add a call to is_same_simple_base_var() at the beginning of the function. If the left and right
nodes of the clause are Vars, and their top-level semantics are identical except for varno, varattno,
varnosyn, varattnosyn, and location, and their underlying references point to the same column of
the same table, with all semantics identical except for varnosyn, varattnosyn, and location, the function returns true.
1. If is_same_simple_base_var() returns true, the two calls to examine_variable() will obtain the same
statistics, if available. We can call examine_variable() first on the node that is already a simple base Var,
and reuse its results for the second call.
2. If is_same_simple_base_var() returns true, and lstatop == rstatop in the "Try to get ranges of both inputs" logic,
the two calls to get_variable_range() will return the same MIN/MAX values. We can avoid the second call and
reuse the results of the first call.
3. If is_same_simple_base_var() returns true, and leop == revleop && rightmax == leftmax && op_righttype == op_lefttype,
the inputs to the first and second calls to scalarineqsel() are identical, so both calls return the same selec. We can
avoid the second call and reuse the result of the first call.
After these two calls, because leftend == rightend, the subsequent logic sets leftend = rightend = 1.0.
4. If is_same_simple_base_var() returns true, and ltop == revltop && rightmin == leftmin && op_righttype == op_lefttype,
the inputs to the third and fourth calls to scalarineqsel() are identical, so both calls return the same selec. We can
avoid the fourth call and reuse the result of the third call.
After these two calls, because leftstart == rightstart, the subsequent logic sets leftstart = rightstart = 0.0.
(For points 3 and 4, MIN/MAX are compared directly using Datum values, rather than extracting and comparing the underlying values, which would be a more expensive operation. This is done to keep the implementation simple.)
5. If all the conditions in points 0/1/2/3/4 are satisfied, skip the checks in points 3 and 4 after obtaining the maximum
and minimum values. Since all these conditions are satisfied, the logic following the two pairs of scalarineqsel() calls
would check whether the returned values are equal and then perform the following assignments:
If leftend == rightend, set leftend = rightend = 1.0.
If leftstart == rightstart, set leftstart = rightstart = 0.0.
Both outcomes are equivalent to the default values set at the beginning of the function.
Based on the design above, run some tests covering the following scenarios:
EQ:
explain (summary) select a.reltype from pg_class_1 a, pg_class_2 b where a.reltype = b.reltype; --not sme base var
explain (summary) select a.reltype from pg_class_1 a, pg_class_1 b where a.reltype = b.reltype; --sme base var
IN:
explain (summary) select a.reltype from pg_class_1 a where a.reltype in (select b.reltype from pg_class_2 b); --not sme base var
explain (summary) select a.reltype from pg_class_1 a where a.reltype in (select b.reltype from pg_class_2 b); --sme base var
IN_LIMIT:
explain (summary) select a.relname from pg_class_1 a where a.relname in (select b.relname from pg_class_2 b limit 1); --not sme base var
explain (summary) select a.relname from pg_class_1 a where a.relname in (select b.relname from pg_class_1 b limit 1); --sme base var
Based on the test output:
0. The execution plans shown by EXPLAIN are identical.
1. The estimated selectivity values returned by mergejoinscansel(), as shown in the log output, are as follows:
EQ & IN:
master v2
leftstart leftend rightstart rightend leftstart leftend rightstart rightend
not sme base var 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0
sme base var 0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0
------------------------------------------------------------------------------------------------
IN_LIMIT:
master v2
leftstart leftend rightstart rightend leftstart leftend rightstart rightend
not sme base var 0.0001 0.9999 0.0001 0.9999 0.0001 0.9999 0.0001 0.9999
sme base var 0.0001 0.9999 0.0001 0.9999 0.0 1.0 0.0 1.0
------------------------------------------------------------------------------------------------
The returned values are consistent. However, in the IN_LIMIT case, the V2 output differs in the “same base Var” scenario.
For IN_LIMIT, both master and V2 treat the “not same base Var” case as not involving the same base Var. When calling:
selec = scalarineqsel(root, revleop, isgt, true, collation, &rightvar, leftmax, op_lefttype);
selec = scalarineqsel(root, revltop, isgt, false, collation, &rightvar, leftmin, op_lefttype);
the Var in rightvar corresponds to a Var in a sub-join of a semi-join that has been pulled up. When ineq_histogram_selectivity()
calls get_actual_variable_range(), the RelOptInfo corresponding to rightvar->var has no index, so get_actual_variable_range()
returns false. Consequently, ineq_histogram_selectivity() adjusts the result as follows:
{
double cutoff = 0.01 / (double) (sslot.nvalues - 1);
if (hist_selec < cutoff)
hist_selec = cutoff;
else if (hist_selec > 1.0 - cutoff)
hist_selec = 1.0 - cutoff;
}
The same adjustment also exists in the other branch of ineq_histogram_selectivity(), namely "else if (sslot.nvalues > 1)".
(Could this issue be addressed as follows? get_actual_variable_range() matches vardata->rel and vardata->var against
indexes to retrieve the index's minimum and maximum values. If semantic equivalence is established, we could look up
the indexes using the underlying vardata->rel and vardata->var and attempt to find a match to retrieve the index's
minimum and maximum values. If this approach works, we could start a separate thread to discuss it.)
3. Performance results are shown below.
master(ms) v2(ms) Improvement%
mergejoinscansel() Planning Time mergejoinscansel() Planning Time mergejoinscansel() Planning Time
eq_not_same_var 0.118 2.012 0.119 2.008 -1.21% 0.20%
eq_same_var 0.117 2.027 0.024 1.933 79.84% 4.61%
in_not_same_var 0.120 3.070 0.119 3.024 0.22% 1.49%
in_same_var 0.118 3.045 0.025 2.909 78.84% 4.48%
in_limit_not_same_var 0.362 1.992 0.352 1.955 3.01% 1.84%
in_limit_same_var 0.356 1.959 0.024 1.629 93.35% 16.80%
Based on the test results, my observations are as follows:
- In all not_same_var scenarios, V2 shows no performance regression.
- In all same_var scenarios, at the function level, master remains relatively stable at 0.118 ms and 0.360 ms,
while V2 remains stable at 0.025 ms, delivering a performance improvement of over 78%.
- In the in_limit_same_var scenario, there are substantial performance improvements both at the function level and in planning time.
(For each set of 128 measurements, I excluded the first measurement, removed the maximum and minimum values from the remaining measurements, and calculated the arithmetic mean of the rest.)
I've attached the corresponding test shell script and analysis results in an XLS file. The XLS file also contains the shell commands used to extract the data, making it easier to aggregate and analyze the results.
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Re: Optimize mergejoinscansel() by avoiding redundant computations
Hi
Build on v2 by adding checks in the recursive calls to find_relation_rte() to ensure that
the relevant Var properties match, as shown below:
/*
* We can only recurse through a simple Var of the subquery's query
* level, and only if its varattno, vartype, vartypmod, varcollid, and
* varreturningtype properties match those of the upper Var.
*/
if (tmpvar && IsA((tmpvar), Var) &&
tmpvar->varlevelsup == 0)
{
if (tmpvar->varattno <= 0 ||
tmpvar->vartype != (*var)->vartype ||
tmpvar->vartypmod != (*var)->vartypmod ||
tmpvar->varcollid != (*var)->varcollid ||
tmpvar->varreturningtype != (*var)->varreturningtype)
goto fail;
/* OK, recurse into the subquery. */
*var = tmpvar;
return find_relation_rte(subroot, var);
}
Also, revise the comments in find_relation_rte() and simplify its implementation, using examine_simple_variable() as a reference.
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Re: Optimize mergejoinscansel() by avoiding redundant computations
Hi hackers,
Attached is v4. Compared with v3, it takes a simpler approach. v3
traced Vars through subqueries and CTEs (is_same_simple_base_var())
and reused intermediate results step by step. v4 calls
examine_variable() on both inputs as before and compares what it
returns. v4 also adds an assert-only cross-check, and the numbers
below come from release builds and include EXPLAIN planning time.
What the patch does
-------------------
When both inputs of a merge clause are the same column (or
expression) of the same relation, as in self-joins or joins against
pulled-up subqueries and views, every get_variable_range() and
scalarineqsel() call in mergejoinscansel() gets identical inputs for
the two sides. The existing "exactly equal estimates" rules then
discard the results, so the answer is always the default (start =
0.0, end = 1.0, plus stanullfrac for nulls-first). Getting there can
be costly, since scalarineqsel() may probe an index through
get_actual_variable_range().
The new mergejoin_vardata_equivalent() detects this case after
examine_variable(), and mergejoinscansel() then returns the same
answer without doing that work. Calls per merge clause when the
inputs are equivalent:
master v4
examine_variable() 2 2
get_variable_range() 2 0 (1 for nulls-first)
scalarineqsel() 4 0
The inputs are treated as equivalent only if:
- they use the same statistics tuple (same pointer);
- vartype and acl_ok are equal;
- both are plain relations with the same relid and inh flag;
- for Vars, varattno is equal and varnullingrels is empty on both
sides or nonempty on both (match_index_to_operand() only checks
emptiness);
- for other expressions, they are equal() after mapping one varno to
the other.
The operator must also not be cross-type. The pointer test errs on
the safe side: unequal pointers (e.g. copies from a stats hook or
extended statistics) only mean the shortcut is not taken.
For nulls-first, master adds stanullfrac only if get_variable_range()
succeeds. To keep that behavior, the shortcut calls it once with NULL
min/max, which get_variable_range() now accepts and which only checks
whether a range is available.
The equivalence rules depend on what scalarineqsel() and
get_variable_range() look at, so they could drift if those functions
change. To catch that, the body of mergejoinscansel() moves to
mergejoinscansel_internal(), and in assert-enabled builds the full
computation is repeated whenever the shortcut is taken, with an
Assert that both give the same results. This follows the pattern of
verify_compact_attribute() and have_unsafe_outer_join_ref(). Release
builds do not contain this code.
Correctness
-----------
- 29 merge join cases (test.sql in the attachment) give identical
EXPLAIN output, plans and costs included, on master and v4.
- With assertions enabled, the regression suite (setup, regress)
passes and the cross-check never fires.
- To make sure the cross-check works, I injected a bug (adding
stanullfrac without checking get_variable_range()); the RLS case
with a non-leakproof operator then failed the Assert.
- On a release build, meson test including TAP passed everything it
ran: regress, isolation, ecpg, postgres_fdw, test_decoding,
pg_upgrade, recovery (59) and subscription (39). I stopped the run
after 409 of 422 tests, with no failures (365 ok, 40 skipped,
4 interrupted by the stop, 13 not run).
Performance
-----------
Release build (-O3, cassert=false), Intel i7-5500U, 4 cores, 15 GB,
WSL1, default statistics target. Each version is built twice: once
with temporary timing code around mergejoinscansel(), and once
without it, which is used for planning time. All four builds share
one instance and one set of statistics. Values are means after
dropping the minimum and maximum. The three columns are three
separate runs on an idle machine; their summaries are in the
attachment (results/runN/summary.txt).
Scenario 1: cold connections. The 29 cases run once per server
start, 12 starts per version, master and v4 alternating.
run 1 run 2 run 3
planning time, shortcut taken (18) -12.7% -12.8% -12.5%
planning time, shortcut not taken (10) +6.1% +11.7% +9.1%
same, without case 17 (9) -0.3% +3.9% +4.1%
Most of the increase in the second row comes from case 17, which
takes about 0.3 ms longer on v4 (0.27-0.37 ms in the three runs). On
a cold connection, master warms the catalog cache and the index of
column c while planning cases 3-5. v4 skips that work there, so the
first index probe moves to case 17, the next query that needs it.
Without case 17 the group changes by -0.3% to +4.1%, about 0.01 ms
per statement, which is within the run-to-run scatter of single cases
(up to +/-13%). This explanation is inferred from the per-case
numbers; I have not verified it separately. Scenario 2 below shows
no change for these cases in steady state. (In summary.txt these
rows are "fast", "slow" and "slow-17" under "Scenario 1 summary".)
Scenario 2: steady state. Each case runs 128 times in one session.
run 1 run 2 run 3
mergejoinscansel(), shortcut (18) -95.9% -95.9% -95.7%
mergejoinscansel(), no shortcut (10) -4.4% -6.1% +1.0%
planning time, shortcut (18) -22.2% -18.6% -21.3%
planning time, no shortcut (10) -0.7% +4.5% +0.5%
When the shortcut applies, planning time goes from about 0.245 ms to
about 0.195 ms per statement, which matches the time saved in
mergejoinscansel() itself. When it does not apply,
mergejoinscansel() takes about 0.013 ms on both master and v4, and
both rows change sign from run to run, i.e. the extra equivalence
check is lost in the noise. (In summary.txt these rows are
"slow+fast" and "slow+slow" under "Scenario 2 summary".)
In short: estimates are unchanged; when the shortcut applies,
mergejoinscansel() is about 96% faster and planning time for simple
queries drops by about 20% in steady state and about 13% on cold
connections; other queries show no measurable change.
Reproducing the numbers
-----------------------
mergejoinscansel-perf.tar.gz contains the scripts (perf/scripts) and
the summaries of the three runs above (perf/results/run1..3, each
with summary.txt and env.txt). It needs a Linux machine with git,
meson, ninja, python3 and stdbuf. Start from a clean master checkout
that the patch applies to.
# paths; adjust to your setup
P=/path/to/perf # extracted from the tarball
SRCDIR=/path/to/postgresql # clean master checkout
BUILD=/path/to/build_release
PATCH=/path/to/v4-0001-Skip-redundant-work-in-mergejoinscansel-for-equiv.patch
SRC=$SRCDIR/src/backend/utils/adt/selfuncs.c
# 0. release build directory, assertions off
meson setup $BUILD $SRCDIR --prefix=/tmp/pg-perf-prefix \
-Dbuildtype=release -Dcassert=false
# 1. generate four selfuncs.c variants: master and v4, each with
# and without the timing wrapper
cp $SRC /tmp/master.c
git -C $SRCDIR apply $PATCH
cp $SRC /tmp/v4.c
mkdir -p $P/bin/src
python3 -I $P/scripts/make_variants.py /tmp/master.c /tmp/v4.c $P/bin/src
# 2. build and install each variant under $P/bin/
# (this overwrites selfuncs.c in the tree; it is restored to v4)
for v in master_notiming master_timing v4_notiming v4_timing; do
cp $P/bin/src/$v.c $SRC
ninja -C $BUILD || break
rm -rf $P/bin/$v
DESTDIR=$P/bin/$v meson install -C $BUILD --no-rebuild --quiet || break
done
cp /tmp/v4.c $SRC
# 3. run both scenarios (about 5 minutes). The first run creates a
# test instance in $P/data (port 54330, socket in /tmp; override
# with PORT and SOCKDIR) and loads it with init.sql; later runs
# reuse it, so all results share the same statistics.
cd $P && ROUNDS=2 S1REP=12 SLEEP=5 BUILD=$BUILD ./scripts/run_all.sh
grep ERROR results/run.log # should print nothing
# 4. summarize into results/summary.txt
python3 -I scripts/summarize.py
Before rerunning, move away master/, v4/ and results/; summarize.py
reads every output file it finds there.
Attachments
-----------
- v4-0001-Skip-redundant-work-in-mergejoinscansel-for-equiv.patch
- mergejoinscansel-perf.tar.gz
Comments and reviews are welcome.
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com