Hi Jian, Shihao, hackers,

I have revised the statistics lookup change to prefer exact expression
statistics, while retaining top-level RelabelType stripping as a fallback
when no exact statistics tuple is available.  This also addresses the
fallback cases Shihao reported: either the query expression or the
statistics expression can have the top-level relabeling.

This v7 includes the PHV/relabel normalization previously posted as
CF 7730 [1, 2], so it can be applied as one patch to the master base used
for this revision.  That normalization has not yet received sufficient
review; I describe its role below.

The motivation is that a RelabelType can carry more than a binary-compatible
type change.  It can represent COLLATE, and preserving the same stored
values does not imply preserving their equality semantics or number of
distinct values.  Stripping it unconditionally can both hide useful exact
statistics and incorrectly carry uniqueness across a collation or type
change.  On the other hand, requiring exact matches everywhere would lose
useful column and expression statistics in cases that worked previously.

There is an important representation difference between the three kinds
of expression involved in examine_variable():

* The input expression and an extended-statistics expression keep COLLATE
  in the expression tree.  The catalog stores the latter in
  pg_statistic_ext.stxexprs.  Planner simplification normally represents a
  necessary COLLATE as RelabelType, and can eliminate redundant relabels.
  Extended expression statistics use exprCollation(expr) when comparing
  sampled values, and occupy entries in pg_statistic_ext_data.stxdexpr.

* For an expression index, ComputeIndexAttrs() first obtains the expression's
  type and collation, then removes top-level CollateExpr nodes before
  storing indexprs.  An index-key COLLATE specification can also override
  the collation.  The effective index collation is recorded separately in
  pg_index.indcollation and loaded into rd_indcollation.  Binary-compatible
  casts can still leave RelabelType nodes in the index expression.

  During ANALYZE, the expression in indexprs supplies the sampled values.
  examine_attribute() in commands/analyze.c uses the expression's result
  type and typmod, and preferentially uses rd_indcollation for comparing
  those values, falling back to exprCollation(index_expr) when necessary.
  Thus both indexprs and the external collation matter.  The external
  collation governs result-value comparisons; it does not replace the
  collations of operations inside indexprs.  Expression-index statistics
  are stored in pg_statistic under the index OID and index column number.

  A key such as a COLLATE "abc" that reduces to a plain Var is recorded
  as an ordinary index column.  Statistics lookup for the underlying
  table column uses its column statistics, collected under the column's
  declared collation.  The examples below use genuine expression keys.

The lookup now has two stages.

First, retain top-level RelabelType nodes and look for exact statistics,
with the existing index-before-extended-statistics priority.  For extended
statistics, compare the expression trees with equal().  Index matching
also accounts for the external collation:

    if (indexcollation == exprCollation(indexkey))
        exact_match = equal(node, indexkey);
    else
        exact_match =
            exprCollation(node) == indexcollation &&
            exprType(node) == exprType(indexkey) &&
            exprTypmod(node) == exprTypmod(indexkey) &&
            equal(strip_top_relabel(node), strip_top_relabel(indexkey));

Here strip_top_relabel() is explanatory shorthand for looking through
one top-level RelabelType.  The second branch aligns the two storage
representations of the result collation while retaining the type and
typmod checks.  Matching collation OIDs are required; separate collation
objects with the same settings are still separate objects for matching.

While searching, record possible fallback candidates and their expression
positions, but defer loading their statistics.  If no exact statistics
tuple is found, use column statistics when stripping exposes a simple Var.
Otherwise, try the recorded index candidates, then extended-statistics
candidates, in their original order until usable statistics are found.
Recording multiple candidates allows a later source to supply statistics
when an earlier partial index or statistics object has none.  Fallback
comparisons remove top-level relabeling symmetrically.  An index can also
be a fallback candidate when neither tree has a RelabelType, because its
external collation can differ from the query's collation.

The comparison expressions have outer-join nulling relids removed in both
stages.  The expression returned in vardata retains them.  Only exact
index matches can newly establish uniqueness, including an applicable
partial unique index that supplies no whole-table statistics.  A fallback
index match only supplies statistics.  Ordinary-column uniqueness is
considered when actually falling back to that column, with matching
collation and default equality operator, and is combined with any existing
exact uniqueness information.  Fallback therefore remains an approximate
reuse of statistics rather than a new proof of equivalent equality
semantics.

Some examples from the regression tests illustrate these choices.  The
SQL excerpts below use the data and setup in the corresponding tests.

1. Exact expression statistics before column fallback
   (collate.icu.utf8.sql).

   The relabel_stats test has a primary-key text column under "C", with
   52 values generated by chr(65 + g), g = 0..51.  This particular set has
   32 groups under the test's nondeterministic case_insensitive collation.

       CREATE STATISTICS relabel_expr
         ON (a COLLATE case_insensitive) FROM relabel_stats;
       ANALYZE relabel_stats;

       EXPLAIN SELECT count(*) FROM relabel_stats
         GROUP BY a COLLATE case_insensitive;

   With exact expression statistics, the estimate is 32 groups.  GROUP BY a
   still estimates 52.  After DROP STATISTICS relabel_expr, the collated
   query falls back to column statistics and estimates 52, while the actual
   result still has 32 groups.  This deliberately shows the approximation
   in fallback and why exact statistics should take precedence.  The
   column's uniqueness under "C" must not imply uniqueness under the
   case-insensitive collation.

2. An index whose result collation is stored outside indexprs
   (collate.icu.utf8.sql).

   The relabel_index_stats test contains A..Z and a..z, repeated 20 times:

       CREATE INDEX relabel_index_ci ON relabel_index_stats
         ((left(a, 1) COLLATE case_insensitive));
       CREATE STATISTICS relabel_index_expr
         ON (left(a, 1)) FROM relabel_index_stats;
       ANALYZE relabel_index_stats;

       EXPLAIN SELECT left(a, 1) FROM relabel_index_stats
         GROUP BY left(a, 1);
       EXPLAIN SELECT left(a, 1) COLLATE case_insensitive
         FROM relabel_index_stats
         GROUP BY left(a, 1) COLLATE case_insensitive;

   The first query estimates 52 groups using exact extended expression
   statistics under "C".  The second estimates 26 using the expression
   index's statistics under case_insensitive.  The stored index expression
   is left(a, 1), with its original "C" collation, while indcollation is
   case_insensitive.  Comparing only indexprs would wrongly accept the
   index as an exact match for the first query and fail to recognize the
   representation of the second query's exact match.

3. Fallback from either side, and continuing past unavailable statistics
   (stats_ext.sql).

   For 5,200 rows containing each of 52 initial characters 100 times,
   the tests estimate and return 100 rows in each of these cases:

       -- Only the statistics expression has top-level COLLATE.
       CREATE STATISTICS relabel_expr
         ON (left(a, 1) COLLATE "POSIX") FROM relabel_stats;
       -- After ANALYZE:
       SELECT * FROM relabel_stats WHERE left(a, 1) = 'A';

       -- A separate test puts COLLATE only on the query expression,
       -- with statistics on the uncollated left(a, 1).
       SELECT * FROM relabel_stats
         WHERE left(a, 1) COLLATE "POSIX" = 'A';

   The plain-column case a COLLATE "POSIX" = 'A', with only column
   statistics collected under "C", likewise estimates and returns 100.
   Further tests put an unusable partial index or an empty expression-
   statistics entry before a usable fallback source.  Those still produce
   100/100.  An exact partial unique expression-index match followed by
   column-statistics fallback preserves the 1/1 estimate.

4. Binary compatibility does not make statistics interchangeable
   (stats_ext.sql).

   With alternating 'A' and 'A ' values, the test creates:

       CREATE INDEX relabel_cast_idx ON relabel_cast
         ((left(a, 3)::pg_catalog.bpchar COLLATE "POSIX"));
       CREATE STATISTICS relabel_cast_stats
         ON (left(a, 3) COLLATE "POSIX") FROM relabel_cast;
       ANALYZE relabel_cast;

       EXPLAIN SELECT left(a, 3) COLLATE "POSIX" FROM relabel_cast
         GROUP BY left(a, 3) COLLATE "POSIX";

   text and bpchar are binary-compatible here, but bpchar ignores trailing
   spaces in equality.  The text query has two groups and must use the
   exact text statistics, rather than treating the bpchar index's one-group
   statistics as exact after stripping a relabel.  The test estimates and
   returns two groups.  Related tests ensure that unique text expressions
   do not imply unique bpchar results, and distinguish different typmods
   when aligning an external collation.

The main additional cost is in planning.  Normalization adds checks within
the existing recursive PHV-removal walk; the lightweight PHV-presence
check still avoids that copying walk when no PHVs are present.
Each visited expression during statistics lookup can
require an extra equal() comparison, and matching fallback candidates
allocate list entries for the source and its position.  Memory use is
proportional to the number of recorded candidates.  A relabeled simple
Var can now search expression indexes and extended statistics before
falling back to column statistics, whereas unconditional stripping used
to reach the column fast path immediately.  Exact-match priority can
also require searching farther than accepting the first approximate
match.  If exact lookup fails, trying candidates adds catalog/cache or
statistics-hook accesses, including unsuccessful attempts.

The fallback stage visits the recorded candidates, so it avoids another
full expression-list scan and another PHV-stripping pass.  Looking through
a top-level relabel uses an existing child pointer.  The bare-Var fast
path remains.  The implementation also adds review and maintenance work:
the two lookup stages, paired candidate lists, index collation alignment,
and the distinction between statistics reuse and uniqueness inference all
need to stay consistent.  I have not measured planning-time overhead for
this revision, so I cannot yet quantify that tradeoff.  The patch changes
statistics selection; catalog formats and ANALYZE's collection rules stay
the same.

The included normalization was previously posted as "Normalize RelabelTypes
after stripping PlaceHolderVars", CF 7730 [1], discussed in [2].  It
normalizes adjacent or redundant RelabelType nodes that PHV stripping can
expose at any depth, preserving necessary outer relabeling.  Together with
the existing planner simplification of index and statistics expressions,
this permits the lookup code to strip a single top-level RelabelType.
CF 7730 is currently Needs review and has not yet received sufficient
review.  I originally split it out to make that component easier to
review.  This v7 includes it with the lookup change, and its correctness
still needs review as part of this patch.

The PHV/adjacent-relabel tests in join.sql cover the normalization portion.
The exact/fallback lookup tests are in stats_ext.sql and
collate.icu.utf8.sql.  The current combined branch passes the debug/assert
build, pgindent --check, git diff --check, and all six relevant regression
tests including setup dependencies: test_setup, create_misc, create_index,
join, stats_ext, and collate.icu.utf8.

I would appreciate feedback on the matching policy and whether the added
planning and maintenance costs are justified by these cases, particularly
the search before falling back to a relabeled simple Var.

[1] https://commitfest.postgresql.org/patch/7730/
[2] 
https://www.postgresql.org/message-id/flat/[email protected]
[3] Original 
discussion:https://www.postgresql.org/message-id/flat/cacjufxglciyhm+p0gxesg2x--ptrmy3pszqsqoq_h4qs_oq...@mail.gmail.com


regards,
--
ZizhuanLiu (X-MAN) 
[email protected]

Attachment: v7-0001-Prefer-exact-expression-statistics-before-stripping-top-level-relabels.patch
Description: Binary data

Reply via email to