Re: Prove a NOT IN's left-hand expressions non-nullable from quals

Поиск
Список
Период
Сортировка
Искать

Re: Prove a NOT IN's left-hand expressions non-nullable from quals

От:
Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Дата:
Вложения:
Hi,

On Fri, 19 Jun 2026 at 06:43, Richard Guo <guofenglinux@gmail.com> wrote:
383eb21eb teaches the planner to convert "x NOT IN (SELECT ...)" to an
anti-join when both sides of the comparison are known to be non-null.
On the outer side we currently get that only from NOT NULL constraints
and the outer-join-aware-Var infrastructure.

That misses a case: the left-hand column has no NOT NULL constraint,
but a qual forces it non-null anyway, as in "x IS NOT NULL AND x NOT
IN (...)" or "x > 0 AND x NOT IN (...)".  We leave those as SubPlan
filters today, even though x clearly can't be NULL where the NOT IN is
evaluated.

The attached patch proves the left-hand Var non-null from such a qual.
pull_up_sublinks_jointree_recurse collects the quals at or below the
NOT IN's jointree node (only those on rels not below the nullable side
of an outer join, so they really do filter the rows) and hands them to
convert_ANY_sublink_to_join, which checks them with
find_nonnullable_vars.

Quals above the NOT IN's node could help in some cases too, but that's
a separate extension and I've left it as a follow-up.  See the details
in the draft commit message.

Thanks for the patch!

I did see one issue in this here's a statement for repro:

CREATE TEMP TABLE outer_t (x int);
CREATE TEMP TABLE inner_t (y int NOT NULL);

INSERT INTO outer_t VALUES (NULL), (1);
INSERT INTO inner_t VALUES (2);

SELECT x
FROM outer_t
WHERE NOT (x = ANY('{}'::int[]))
  AND x NOT IN (SELECT y FROM inner_t);

SQL semantics return only 1. With the patch, the planner
produces a hash anti-join and also returns the NULL row: the
first qual admits it, and the anti-join preserves it, whereas the
original NOT IN evaluates to NULL and filters it out.

This helper weakness also affects the existing inner-query
proof path, but the patch creates a new regression surface.

I've posted a likely fix in [1].

Apart from the above, your patch looked good to me.

Regards,
Ayush

[1]  PostgreSQL: [PATCH] SAOP nullability analysis below NOT/BooleanTest
 

Re: Prove a NOT IN's left-hand expressions non-nullable from quals

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Вложения:
Hi Richard,

v1 applies to today's master and make check is green with it.  Three things
and a comment nit.

1) +1 on the varlevelsup check Ayush proposed.  Since make check passes on v1
as posted, nothing in the suite reaches the case; 0001 attached is his
one-liner plus a test that fails without it.

2) The same collision has a second instance, on the sub-select output side, and
this patch makes it reachable from an ordinary qual.  With v1:

    \pset null ''
    CREATE TEMP TABLE output_outer_t (a int);
    CREATE TEMP TABLE output_local_t (a int);
    CREATE TEMP TABLE output_inner_t (a int);
    INSERT INTO output_outer_t VALUES (NULL), (10);
    INSERT INTO output_local_t VALUES (1);
    INSERT INTO output_inner_t VALUES (1);

    SELECT o.a,
           ARRAY(SELECT l.a
                 FROM output_local_t l
                 WHERE l.a IS NOT NULL
                   AND l.a NOT IN (SELECT o.a
                                   FROM output_inner_t i
                                   WHERE i.a IS NOT NULL)) AS vals
    FROM output_outer_t o
    ORDER BY o.a NULLS FIRST;
       a    | vals
    --------+------
      | {1}
         10 | {1}
    (2 rows)

and master:

       a    | vals
    --------+------
      | {}
         10 | {1}
    (2 rows)

For o.a = NULL the inner sub-select returns one NULL, so the NOT IN is NULL and
vals is empty.  The sub-select's output o.a is an upper-level Var, and
query_outputs_are_not_nullable() looks it up with

if (!mbms_is_member(var->varno,
var->varattno - FirstLowInvalidHeapAttributeNumber,
nonnullable_vars))

which finds i.a there: same varno and varattno, different varlevelsup.  That
fallback is on master already; what the patch adds is the proof for l.a, and
that is what brings the conversion within reach here.  0001 doesn't cover it --
l.a is a Var of its own level, so the check there has nothing to say about it.
I've posted that one separately, with a fix [1].

3) Planning cost.  N conjuncts of the form

    t.cK NOT IN (SELECT s.dK FROM s)

with t's columns nullable and s's NOT NULL, so the sub-select side is provable
and the outer side never is.  Same configure for every build.

The "control" column below is not a fix, it's an attribution check: the v1
binary again, but with every left-hand side written as (t.cK + 0), so that

if (nonnullable_quals != NIL && IsA(expr, Var))

is false and the new fallback is never entered.  If the cost were coming from
somewhere else in the patch it would still be there.  It also means no NOT IN
can be converted, which is why it isn't a way out.

EXPLAIN (SUMMARY ON, COSTS OFF), Planning Time, median of 10, in ms:

    N     master       v1    v1 control    v1 + 0002
    20      0.7       0.9       0.7           0.7
    40      1.5       2.3       1.4           1.5
    80      3.3       6.6       3.5           3.5
    160     8.8      21.4       8.6           9.0
    320    32.6     102.3      32.9          33.7

Memory is where it shows up worst.  EXPLAIN (MEMORY), used, in kB:

    N     master       v1    v1 control    v1 + 0002
    20      642      1235       659           671
    40     1263      3628      1297          1322
    80     2506     11951      2574          2624
    160    4993     42743      5128          5229
    320    9970    160911     10240         10442

master doubles with N; v1 goes up by 2.9x, 3.3x, 3.6x, 3.8x.  At N=320 that is
10MB against 157MB, for one statement's planning.  The control column tracks
master throughout, so the extra is that block and nothing else.

It's this, in sublink_testexpr_is_not_nullable():

if (!computed_nonnullable_vars)
{
List    *flat_quals;

flat_quals = (List *)
flatten_join_alias_vars(root, root->parse,
(Node *) nonnullable_quals);
nonnullable_vars = find_nonnullable_vars((Node *) flat_quals);
computed_nonnullable_vars = true;
}

guarded by a flag that is declared in that same function:

bool computed_nonnullable_vars = false;

so it lives for one call and the work is redone for the next NOT IN.
nonnullable_quals is the node's whole WHERE clause, sublinks and their
subqueries included, and flatten_join_alias_vars() copies all of it; nothing
frees the copies and prepjointree doesn't run in a context of its own, so all N
are live until the statement is done planning.  Dropping just that one call
takes N=320 from 102ms back to 36ms, and the memory all the way back to
master's 9970kB; the 3.6ms left over is find_nonnullable_vars() walking the
same list N times.

It doesn't take hundreds of NOT INs once the sub-selects aren't trivial.  Same
measurement, with the conjuncts instead of the form

    t.cK NOT IN (SELECT s.dK FROM s WHERE s.dK <> 0 AND s.dK <> 1 AND ...)

The <> terms are only there to grow the sub-select's qual tree without adding
anything else to plan; the flatten happens before preprocess_expression, so
they are still all there when the copy is made.

    shape                          master        v1     v1 + 0002
    10 NOT INs, 50 quals each      1166kB    2431kB       1292kB
    10 NOT INs, 400 quals each     6887kB   15886kB       7787kB
    40 NOT INs, 100 quals each     7909kB   45811kB       8856kB

0002 attached passes the quals in a small struct and derives the Var set on
first use, so every SubLink at one jointree node shares one derivation.  It
also tests the sub-select's output columns before the outer expressions, since
that is only a scan of its target list -- it doesn't help the shapes above,
where the cheap test passes, but it skips the work entirely for a NOT IN whose
sub-select outputs are nullable and which therefore could never have been
converted.  What is left over above master in the last column is the one
derivation 0002 still has to do.  Both patches are on top of v1, and make check
is green with them.

A comment thing.  The JOIN_LEFT branch already says

     * safe for this node's own quals, since a sublink pulled up
     * here goes into the right side.

which is the right reason, but stops just short of it: going into the right
side is what puts the ON quals above the anti-join rather than below it as in
the FromExpr and JOIN_INNER cases, and that is the argument from quals above
which the commit message defers -- one step from the case it rules out.  What
makes it sound here is which side the anti-join lands on, so maybe

  * safe for this node's own quals, since a sublink pulled up
  * here goes into the right side.
+ *
+ * The ON quals then end up above the anti-join rather than
+ * below it, unlike the FromExpr and JOIN_INNER cases.  That
+ * is sound because the anti-join is on the nullable side: a
+ * row it lets through with a NULL left-hand side fails the
+ * ON qual and joins with nothing, which is what the original
+ * NOT IN did with it.
  */

and the mirror of it in JOIN_RIGHT.  Incidentally that case is the only thing
the new traversal buys over find_subquery_safe_quals(), which collects the same
quals under the same rules everywhere else.

[1] https://postgr.es/m/CAHWVJhGuaFFRpmq4j%2BmcMcm_HC5QOT7LZsC9bf9b7BCBmvbfMA%40mail.gmail.com

Thanks,
Rui

Re: Prove a NOT IN's left-hand expressions non-nullable from quals

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
Вложения:
Thanks all for the reviews!  Both points regarding the upper-level Var
and the planning cost make sense.  Attached is an updated patch fixing
both, following the approach discussed here.

- Richard

Re: Prove a NOT IN's left-hand expressions non-nullable from quals

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Вложения:
Hi Richard,

v2 applies to master (d29d469bece), builds warning-free and make check is
green, and both of last round's items are fixed.

I diffed v2's results against master's on generated 2-3 rel jointrees, 1377
of which convert where master doesn't, and on partitioned and inheritance
parents, views, UNION ALL, CTEs, UPDATE and DELETE.  No differences in what
I ran.  Three things, none of them about correctness.

1) One shape the sharing doesn't reach.  A node's SafeQualsInfo carries every
safe qual at or below it:

    passquals = list_concat(leftsafequals, rightsafequals);
    if (j->quals)
        passquals = lappend(passquals, j->quals);

and the derivation flattens that whole list, once per node:

    flat_quals = (List *)
        flatten_join_alias_vars(root, root->parse, (Node *) sqinfo->quals);
    sqinfo->nonnullable_vars = find_nonnullable_vars((Node *) flat_quals);
    sqinfo->computed = true;

For example, with N joins each carrying one NOT IN:

    SELECT count(*) FROM t
      JOIN j1 ON (t.c1 NOT IN (SELECT s.d1 FROM s
                               WHERE s.filler = 0 OR s.filler = 1 OR ...))
      JOIN j2 ON (t.c2 NOT IN (SELECT s.d2 FROM s
                               WHERE s.filler = 0 OR s.filler = 1 OR ...))
      ...

t's columns are nullable and no qual proves otherwise, so nothing is converted;
the s.filler terms are padding, 400 per sub-select, to make each copied qual
big enough to measure.  EXPLAIN (MEMORY) used, in kB:

    N     master        v2    v2+0001    v2-master    v2+0001-master
    1        751       841        841           90             90
    4       2989      3889       3350          900            361
    6       4653      6543       5194         1890            541
    8       6402      9641       7122         3239            720
    10      7886     12835       8786         4949            900

One flattened copy of one such ON clause -- one sub-select with its 400
s.filler terms -- is 90 kB, which the N=1 row measures on its own; the last
two columns are then 90 kB * N(N+1)/2 and 90 kB * N, to within a kB.  With a
couple of small NOT INs this is negligible; the concern is that it grows as
N(N+1)/2 in their number and linearly in their size, and none of it is freed
until planning is done.

0001 attached keeps each node's own qual and a list of its children instead:

     typedef struct SafeQualsInfo
     {
    -    List       *quals;      /* qual clauses, with implicit-AND semantics */
    +    Node       *quals;      /* this node's own WHERE or ON qual, or NULL */
    +    List       *children;   /* child SafeQualsInfos whose quals apply */
         List       *nonnullable_vars;   /* multibitmapset; valid if computed */
         bool        computed;
     } SafeQualsInfo;

so the same place now reads

    sqinfo = make_safe_quals_info(j->quals,
                                  safe_quals_children(leftsafequals,
                                                      rightsafequals));

and derives bottom-up, cached per node.  Same Vars proven, same conversions:
the 1377 plans above are identical to v2's, and make check is green.

2) The two tests run in the wrong order for the usual case:

    if (under_not &&
        /* flattens the whole node's clause, once per node */
        (!sublink_testexpr_is_not_nullable(root, sublink, sqinfo) ||
         /* flattens this sub-select's quals, once per NOT IN */
         !query_outputs_are_not_nullable(subselect)))
        return NULL;

With the small sub-selects most NOT INs have, the first is the more expensive
of the two.  || short-circuits left to right, so it always runs first,
including when the second one was going to fail anyway.  For example:

    SELECT * FROM ot
     WHERE ot.c1 IS NOT NULL
       AND ot.c1 NOT IN (SELECT os.d1 FROM os WHERE os.filler = 0 OR ...);

os.d1 is nullable and no qual proves otherwise, so the second test fails and
this can never become an anti-join.  But ot.c1 IS NOT NULL satisfies the
first, so the derivation runs in full before the second rejects it.  Below is
the same measurement with the two tests swapped: N=40 such conjuncts in one
WHERE clause, sub-selects of Q quals each, EXPLAIN (MEMORY) used in kB, and no
conversion possible in any row.

     Q     master    before swap    after swap    saved
     2        690            822           730       92    69%
    10       1204           1542          1377      165    48%
    50       3709           5052          4534      518    38%
    400     25689          35843         32233     3610    35%

So query_outputs_are_not_nullable is the one that should run first in almost
every query -- which is what the 0002 I posted last round did.  It only loses
where the left-hand side isn't a plain Var: there the first test fails without
ever touching the quals, so v2 costs nothing over master and the swap is what
adds.  The same 40 conjuncts with the left-hand sides written (ot.c1 + 0):

     Q     master    before swap    after swap    cost
     2        723            723           755      32
     10      1238           1238          1402     164
     50      3743           3743          4560     817
    400     25723          25723         32258    6535

But (ot.c1 + 0) is rare -- a NOT IN's left-hand side is a column in almost
everything I've seen.  The swap changes nothing observable either way: same
rows and same plans as v2 on the generated queries above, and make check is
green.

3) No test reaches this:

    while (IsA(expr, RelabelType))
        expr = ((RelabelType *) expr)->arg;

make check is green with those two lines removed.  They aren't dead code
though:

    CREATE TABLE tv (a varchar);
    CREATE TABLE sv (b varchar NOT NULL);
    SELECT * FROM tv WHERE a IS NOT NULL AND a NOT IN (SELECT b FROM sv);

gives a Hash Anti Join on v2, and a SubPlan with the two lines taken back
out; a domain over int behaves the same.

Thanks,
Rui
FAQ