[PROPOSAL] Canonicalize BooleanTest(NOT x, t) to BooleanTest(x, flip(t))

From: ZizhuanLiu X-MAN <44973863(at)qq(dot)com>
To: pgsql-hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Cc: zsolt(dot)parragi <zsolt(dot)parragi(at)percona(dot)com>, ilya(dot)evdokimov <ilya(dot)evdokimov(at)tantorlabs(dot)com>, solai(dot)cdac <solai(dot)cdac(at)gmail(dot)com>, pierre(dot)forstmann <pierre(dot)forstmann(at)gmail(dot)com>
Subject: [PROPOSAL] Canonicalize BooleanTest(NOT x, t) to BooleanTest(x, flip(t))
Date: 2026-12-06 14:55:20
Message-ID: tencent_95F696A8D4098D29F08E6DE3B41813B5DF08@qq.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi all,

The test SQL Zsolt posted in [2] made me notice a more general, and I think
more fundamental, equivalence that could be normalized early in the planner.
I'd like to hear what others think.

Observation
===========
When the argument of a BooleanTest is a NOT, the NOT can be folded into the
booltesttype:

BooleanTest(BoolExpr(NOT, [x]), IS_TRUE) -> BooleanTest(x, IS_FALSE)
BooleanTest(BoolExpr(NOT, [x]), IS_FALSE) -> BooleanTest(x, IS_TRUE)
BooleanTest(BoolExpr(NOT, [x]), IS_NOT_TRUE) -> BooleanTest(x, IS_NOT_FALSE)
BooleanTest(BoolExpr(NOT, [x]), IS_NOT_FALSE) -> BooleanTest(x, IS_NOT_TRUE)
BooleanTest(BoolExpr(NOT, [x]), IS_UNKNOWN) -> BooleanTest(x, IS_UNKNOWN)
BooleanTest(BoolExpr(NOT, [x]), IS_NOT_UNKNOWN) -> BooleanTest(x, IS_NOT_UNKNOWN)

The only fact needed is that NOT swaps TRUE and FALSE but leaves NULL
unchanged. I verified all six rules against the three-valued logic
(TRUE / FALSE / NULL); they hold for an arbitrary boolean expression x as
well, e.g. (a > 0). Just to confirm: BoolExpr(NOT) is unary by construction
(make_notclause() uses list_make1(), and get_notclausearg() simply takes
linitial()), so args[0] can be used directly.

Why this also fixes the estimates
=================================
When booltestsel() cannot find statistics for the argument, it estimates
IS_FALSE / IS_NOT_TRUE as "1 - clause_selectivity(arg)". That complement is
valid only under two-valued logic: with NULLs, 1 - P(TRUE) is actually
P(FALSE) + P(NULL), i.e. it degenerates into the semantics of IS NOT TRUE.
When arg is itself NOT x, another layer of error is added on top.

The reason master happens to get (NOT deleted) IS FALSE right (400 rows) is
that the "NOT ignores NULL" error and the "BooleanTest complement" error
cancel out exactly. Once v2 fixes NOT, the cancellation is broken and the
error surfaces as 9900. After normalizing to x IS TRUE / x IS FALSE,
booltestsel() takes the branch that has statistics and reads
freq_true/freq_false/freq_null directly, which is exact and no longer relies
on two bugs cancelling each other.

Suggested location
==================
Rather than special-casing "arg is a NOT" inside booltestsel() (which is what
v3 does), I'd suggest performing this normalization once, in the T_BooleanTest
case of eval_const_expressions_mutator():

* it covers every expression that goes through eval_const_expressions:
target list, WHERE, JOIN/ON, HAVING, RETURNING, ON CONFLICT, etc.
preprocess_expression() runs it for both EXPRKIND_TARGET and EXPRKIND_QUAL;
* it does not rewrite stored view/rule text (it is planner-time), so
existing views benefit on every replan and pg_dump output is unaffected.
Doing it in transformBooleanTest() at parse time would change the stored
view definition, which seems undesirable for dump/upgrade compatibility;
* after this, the is_notclause branch added to booltestsel() by v3 would no
longer trigger on the normal path; it could be kept as defense in depth,
or dropped to simplify the patch.

Additional benefits
===================
1) One fewer NOT node at execution time (boolean filters run per row).
2) A single canonical form helps equal()-based matching and deduction:
predicate implication in predtest, expression indexes, equivalence
classes, and expression matching in extended statistics no longer split
on two syntactically different but semantically equal predicates.
3) It aligns with prepqual's existing negation logic, which already flips
booltesttype when pushing down NOT (x IS t), reducing the number of
coexisting equivalent representations.
4) When x is provably non-null, normalizing first lets the existing
non-nullable shortcut in T_BooleanTest (clauses.c around line 4405) act
on the simpler x, instead of producing NOT (NOT x).

Questions
=========
1) Do others agree that this normalization belongs in the T_BooleanTest case
of eval_const_expressions_mutator(), or would parser / prepqual be
preferred?
2) Would anyone object that eval_const_expressions should do constant folding
only and not this kind of rewrite? My view is that it already performs
semantic simplifications for NOT/BooleanTest, so this fits.
3) Should we also handle BooleanTest over BooleanTest (e.g.
(x IS TRUE) IS FALSE)? That is a separate equivalence class and could be
left for a follow-up.

Note that this changes the expression shown in EXPLAIN
((NOT x) IS FALSE -> x IS TRUE), so affected regression test baselines would
need updating.

[1] https://commitfest.postgresql.org/patch/7514/
[2] https://www.postgresql.org/message-id/CAN4CZFN3tmHepFU1n_6Yoj%2BESda78BNbEi-%2BnpC-KRFRTkgO7w%40mail.gmail.com

The following SQL is used to verify that the target-list in the select statement and
the conditions in the where clause can be equivalently normalized:

with t1(deleted) as (values (null),(false),(true))
select case when deleted is null then 'unknown' else deleted::text end as deleted
,concat((not deleted) is true::text, ' ', deleted is false::text) as "(not) is true --> is false"
,concat((not deleted) is false::text, ' ', deleted is true::text) as "(not) is flase --> is true"
,concat((not deleted) is not true::text, ' ', deleted is not false::text) as "(not) is not true --> is not false"
,concat((not deleted) is not false::text, ' ', deleted is not true::text) as "(not) is not false --> is not true"
,concat((not deleted) is unknown::text, ' ', deleted is unknown::text) as "(not) is unknown --> is unknown"
,concat((not deleted) is not unknown::text, ' ', deleted is not unknown::text) as "(not) is not unknown --> is not unknown"
from t1 \gx

CREATE TABLE t2 (id int, deleted boolean) WITH (autovacuum_enabled = off);
INSERT INTO t2
SELECT i, CASE WHEN i <= 9500 THEN NULL WHEN i <= 9900 THEN true ELSE false END
FROM generate_series(1, 10000) AS g(i);
ANALYZE t2;
CREATE VIEW v AS SELECT id, NOT deleted AS active FROM t2;

-- (not) is true --> is false
explain analyze select * from v where active is true ; -- 100 100
explain analyze select * from t2 where (not deleted) is true ; -- 100 100
explain analyze select * from t2 where deleted is false; -- 100 100

-- (not) is flase --> is true
explain analyze select * from v where active is false ; -- 9900 400
explain analyze select * from t2 where (not deleted) is false ; -- 9900 400
explain analyze select * from t2 where deleted is true; -- 400 400, Correction evaluation

-- (not) is not true --> is not false
explain analyze select * from v where active is not true ; -- 9900 9900
explain analyze select * from t2 where (not deleted) is not true ; -- 9900 9900
explain analyze select * from t2 where deleted is not false; -- 9900 9900

-- (not) is not false --> is not true
explain analyze select * from v where active is not false ; -- 100 9600
explain analyze select * from t2 where (not deleted) is not false ; -- 100 9600
explain analyze select * from t2 where deleted is not true; -- 9600 9600 ,Correction evaluation

-- (not) is unknown --> is unknown
explain analyze select * from v where active is unknown; --50 9500
explain analyze select * from t2 where (not deleted) is unknown; --50 9500
explain analyze select * from t2 where deleted is unknown; --9500 9500 ,Correction evaluation

-- (not) is not unknown --> is not unknown
explain analyze select * from v where active is not unknown; --9950 500
explain analyze select * from t2 where (not deleted) is not unknown; --9950 500
explain analyze select * from t2 where deleted is not unknown; --500 500 ,Correction evaluation

regards,
--
ZizhuanLiu (X-MAN) 
44973863(at)qq(dot)com

Browse pgsql-hackers by date

  From Date Subject
Next Message Tomas Vondra 2026-12-06 15:11:59 BRIN re-summarization is not properly logging snapshotConflictHorizon / wrong results on hot standby
Previous Message Rui Zhao 2026-12-06 14:48:46 Add missing source files and gettext triggers to nls.mk