Repository navigation
Fix vacuous truth for x op ALL (empty subquery) - #106373
mohhddhassan wants to merge 34 commits into
Conversation
x op ALL (empty set) should return TRUE per SQL standard. The singleValueOrNull rewrite returned NULL for empty sets, making x IN (NULL) = FALSE incorrectly. Fix by wrapping the rewrite as: (SELECT count() FROM subquery) = 0 OR x IN (singleValueOrNull subquery) Fixes ClickHouse#105957
|
Workflow [PR], commit [59c9fbc] Summary: ❌
|
|
Duplicating the subquery looks risky. |
|
When it contains non-deterministic functions. |
|
@alexey-milovidov, I used subquery_node->clone() to duplicate the subquery, one copy for count() to detect the empty case, and another for singleValueOrNull(*) and yeah your correct this is risky when the subquery contains non-deterministic functions like rand() since both executions may return different results. So would it be better to avoid duplication entirely by introducing a new aggregate function that can distinguish between an empty set and a multi-value set returning a sentinel value for empty instead of NULL? That way the subquery only runs once. Happy to rework the approach based on your guidance. |
…ery-vacuous-truth
The vacuous-truth change altered the early-return condition in `modifyAST` from `(type == ANY && function_equals)` to `type == ANY`, which made `x != ANY (subquery)` and `x != SOME (subquery)` rewrite to a plain `notIn` instead of `notIn (SELECT singleValueOrNull(*) FROM subquery)`. That broke the semantics: `x != ANY (S)` must be TRUE when some element of `S` differs from `x`, but plain `x NOT IN S` only tests set membership. For example `SELECT 1 != ANY (SELECT number FROM numbers(10))` returned `0` instead of `1`, failing `02007_test_any_all_operators` and `04042_some_keyword`. Restore the original condition so `= ANY` and `!= ALL` still early-return as `in`/`notIn`, while `= ALL` and `!= ANY` continue to the `singleValueOrNull` rewrite. The vacuous-truth `ALL` wrapping is unaffected and still applies to `= ALL`, `>= ALL`, `> ALL`, `<= ALL`, `< ALL`. Fixes the Fast test failures at https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106373&sha=614d7555da0d6593743fb2385e38c70f0c100d68&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ery-vacuous-truth
…ery-vacuous-truth
…ery-vacuous-truth
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 36/36 (100.00%) · Uncovered code |
…ery-vacuous-truth
The vacuous-truth fix for `x op ALL (subquery)` used to `clone` the
right-hand side and build the `count` emptiness check from the copy, so
the subquery was executed twice. For a non-deterministic right-hand side
the two executions can disagree, and the rewrite could return a result
that no single evaluation could produce: with the old rewrite,
`SELECT 1 = ALL (SELECT 1 FROM numbers(1) WHERE rand() % 2 = 0)`
returned the wrong answer `0` in 48 out of 200 runs, because the `count`
branch saw a row while the `singleValueOrNull` branch saw none.
Instead of two different subqueries, `count` and the aggregate are now
computed by a single `SELECT` producing a tuple, and the two values are
taken apart with `tupleElement`:
x op ALL (S) -->
tupleElement(SQ, 1) = 0 OR x op tupleElement(SQ, 2)
where SQ = (SELECT (count(*), aggregate_function(*)) FROM S)
Both occurrences of `SQ` are textually identical, and scalar subqueries
are cached by the hash of the subquery - `ExecuteScalarSubqueriesVisitor`
for the old analyzer and `evaluateScalarSubqueryIfNeeded` for the new one
- so `S` is evaluated exactly once and both `tupleElement` calls observe
the same evaluation. This is visible in `ProfileEvents` for
`SELECT 1 = ALL (SELECT number FROM numbers(1000000))`:
`ScalarSubqueriesCacheMiss: 1`, `ScalarSubqueriesGlobalCacheHit: 1` and
`SelectedRows: 1000001` - one scan, not two.
The rewrite keeps the `in` / `notIn` and `min` / `max` shapes, so the
result for a non-empty right-hand side is unchanged, with both analyzers.
Added a regression test that would fail if the right-hand side is cloned
again, as requested in the review.
|
🕵 While verifying the SELECT 1 != ANY (SELECT 1 WHERE 0); -- returns 1, should be 0
SELECT 1 >= ANY (SELECT 1 WHERE 0); -- returns 1, should be 0
SELECT 1 = ANY (SELECT 1 WHERE 0); -- returns 0, correct
The same |
…ery-vacuous-truth
…ery-vacuous-truth
…rite fixes The comment claimed `x op ALL (empty set)` is TRUE for every operator, but `!= ALL` returns early as a plain `notIn`, so `NULL != ALL (empty subquery)` still returns NULL. State the covered operators explicitly and document the `!= ALL` NULL case. The PR description and changelog entry were narrowed the same way.
…ery-vacuous-truth
…p the old-analyzer mention The review asked to either prove or fix the claim that `NULL != ALL (empty subquery)` returns NULL: the empty-set shortcut in `FunctionIn` returns a constant `1` for `notIn`, so it looked like NULL could never come out. It does: under the default `transform_null_in = 0` the NULL left-hand side is handled by the default implementation for nulls before the set is looked at, so a literal NULL, a constant of a Nullable type and a NULL value inside a Nullable column all give NULL. Only `transform_null_in = 1` turns an empty right-hand side into TRUE for NULL as well. These cases are now pinned in `05045_notequals_all_single_evaluation`, together with the contrasting `NULL = ALL (empty subquery)` = 1 of the aggregate-based rewrite, and the comment in `modifyAST` spells the rule out. The comment also referred to `ExecuteScalarSubqueriesVisitor` for `enable_analyzer = 0`. That path is gone: the analyzer is mandatory since 26.9 and `enable_analyzer = 0` is rejected, so the only scalar subquery cache is the one in `evaluateScalarSubqueryIfNeeded`, and no paired old-analyzer run of `04759_all_subquery_single_evaluation` is possible. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Address review: the emptiness check needed for vacuous truth and the compared value must come from one evaluation of the right-hand side, which an `IN` set cannot carry; document the resulting distributed behaviour. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The operator docs and the banner comment of `modifyAST` still described `a = ALL (subquery)` as `a IN (SELECT singleValueOrNull(*) FROM subquery)`. Describe the actual rewrite, the evaluation on the initiator in distributed queries, and the vacuous truth for an empty subquery. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ery-vacuous-truth
…arison The `= ALL` rewrite still compares with `in`, not `equals`, against `tupleElement(SQ, 2)`. This is intentional: when the subquery returns a NULL or several distinct values, `singleValueOrNull` gives NULL, and `x IN NULL` is 0 as before, while `x = NULL` would be NULL. Fix the comment and the docs that described it as `=`, and add a regression test pinning this. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ery-vacuous-truth
… a missing aggregate row as empty The previous rewrite referenced the scalar subquery `(SELECT (count(*), agg(*)) FROM subquery)` twice. Nested `ALL` quantifiers then duplicated the already rewritten inner expressions on every level, so the query grew exponentially with the nesting depth (30 nested `1 = ALL (...)` took a minute and failed with "Query tree is too big"). Now each operand occurs exactly once: - `<`, `<=`, `>`, `>= ALL` use a lexicographic tuple comparison, `(0, x) < ifNull(SQ, (1, NULL))` where `SQ = (SELECT (count(*) = 0, min(*)) FROM subquery)`, and symmetrically for `>` with `max`. The first elements differ exactly when the right-hand side is empty, which makes the result TRUE. - `= ALL` takes the tuple apart inside a lambda: `arrayMap((_rhs, _lhs) -> ifNull(tupleElement(_rhs, 1), 1) OR _lhs IN tupleElement(_rhs, 2), [SQ], [x])[1]`. A missing aggregate row (`empty_result_for_aggregation_by_empty_set = 1`, or a correlated subquery for a missing group) makes the scalar subquery NULL; it is now recognized as an empty right-hand side. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
…y key and conversions
The previous rewrite of `x = ALL (subquery)` passed the scalar subquery and `x` through
`arrayMap` with a lambda, and `x < ALL` etc. compared tuples `(flag, x)`. Neither is visible
to the primary key analysis, so selective `ALL` filters scanned the whole table, and inside the
lambda `in` was not a comparison with a constant, so `'01' = ALL (SELECT 1)` became 0.
Now the scalar subquery `SQ = (SELECT (count(*) = 0, aggregate(*)) FROM subquery)` occurs once,
under an alias derived from its hash, and is referenced by that alias:
x op ALL S --> ifNull(tupleElement(SQ AS _a, 1), 1) OR x op tupleElement(_a, 2)
x = ALL S --> ifNull(tupleElement(SQ AS _a, 1), 1)
OR (x = tupleElement(_a, 2) AND isNotNull(tupleElement(_a, 2)))
`x` is compared with a constant, so the primary key is used and the conversions are those of a
comparison with a constant. The right-hand side is still evaluated once, and the parsed query
stays linear in the nesting depth.
Also reduce the nesting depth in `05448_all_subquery_missing_row_and_nesting`: 30 levels of
nested subqueries exceeded the stack under TSan (`TOO_DEEP_RECURSION`).
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106373&sha=latest&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
PR: ClickHouse#106373
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…LL`; drop `getTreeHash` from the parser `x = ALL (subquery)` with a non-empty right-hand side is now rewritten to `if(isNull(x), x IN v, ifNull(x = v, 0))`, where `v` is the value from the scalar subquery. This gives the same results as the former `x IN (SELECT singleValueOrNull(*) FROM subquery)`: - a NULL `x` follows `transform_null_in` again; - the result is `UInt8` for a non-nullable `x`, so for example a table with `ORDER BY flag` created from `number = ALL (SELECT 1) AS flag` works again; - the comparison of a non-NULL `x` with a constant keeps its conversions and stays visible to the primary key analysis. The alias of the scalar subquery was derived from `IAST::getTreeHash`. That call kept every implementation of `updateTreeHashImpl` in the WebAssembly parser build, and the `no-formatting-no-dcl` build went 177009 bytes over its size ceiling. The alias is now a hash of the aggregate function name and the text of the subquery. Built locally in `clickhouse/wasm-builder`, the no-formatting/no-DCL `parser.wasm` is 832427 bytes, 42573 under the ceiling. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106373&sha=latest&name_0=PR&name_1=Build%20(wasm_parser) PR: ClickHouse#106373 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…result The previous rewrite of `x = ALL (subquery)` compared `x` with the constant `tupleElement(_a, 2)` through `if(isNull(x), x IN ..., ifNull(x = ..., 0))`. That had three problems, reported in the review: - `x` was copied three times, so quantifiers nested in the left-hand side grew the parsed query exponentially (`TOO_BIG_AST` at a depth of 7). It was also a use after move, which failed the `clang-tidy` build: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106373&sha=86b804c12c21de545aeee10e815660f6dfd6d830&name_0=PR&name_1=Build%20%28arm_tidy%2C%204%2F4%29 - A comparison with a constant is not the set comparison of `IN`: `(1, NULL) = ALL (SELECT (1, NULL))` became 0, and `NULL = ALL (SELECT (1, 2))` threw `ILLEGAL_TYPE_OF_ARGUMENT`. - For a `Nullable` key `isNull(x)` is not a constant, so the `if` hid the comparison from the primary key analysis. Now the rewrite is x = ALL S --> ifNull(tupleElement(SQ AS _a, 1), 1) OR x IN (SELECT tupleElement(_a, 2)) where SQ = (SELECT (count(*) = 0, singleValueOrNull(*)) FROM S) For a non-empty right-hand side this is the former `x IN (SELECT singleValueOrNull(*) FROM S)` with the value taken from the scalar subquery, so tuples, NULLs, `transform_null_in`, conversions, the result type and the primary key (also a `Nullable` one) behave as `IN` with a subquery does. `x` occurs once, and the right-hand side is still evaluated once. As on master, a correlated subquery is not supported in `= ALL`, because `IN` does not support it; the correlated case of `05448_all_subquery_missing_row_and_nesting` keeps `<` and `>` only. PR: ClickHouse#106373 Co-Authored-By: Claude Fable 5.2 <[email protected]>
x op ALL (empty set)should return TRUE per SQL standard (vacuous truth).ClickHouse was returning FALSE because the
= ALLrewrite usessingleValueOrNull,which returns NULL for empty sets, making
x IN (NULL) = FALSEincorrectly. Themin/maxrewrites used for the other comparison operators have the same problem,because they return the default value of the type for an empty set.
Fixed in
modifyASTby also computing whether the right-hand side is empty. The emptiness flag and theaggregate are computed by a single scalar subquery
SQ = (SELECT (count(*) = 0, aggregate(*)) FROM S)returning atuple. SQ occurs once in the rewritten expression, under an alias derived from a hash of the aggregate function name and the subquery text (not
IAST::getTreeHash, which would keep everyupdateTreeHashImplin the WebAssembly parser build), and other places referto it by that alias. The left-hand side
xalso occurs once. So the right-hand side is evaluated once (observable when it is non-deterministic) and theparsed query stays linear in the nesting depth of
ALLquantifiers, on both sides:A NULL scalar is treated as an empty right-hand side. This happens when the
aggregation produces no row: with
empty_result_for_aggregation_by_empty_set = 1, or for a missing group of acorrelated subquery.
For a non-empty right-hand side the results are unchanged. For
<,<=,>,>= ALL,xis compared with aconstant after the scalar subquery is evaluated, so the primary key is still used. For
= ALLthe rewrite is the formerx IN (SELECT singleValueOrNull(*) FROM S), only the single row of theINsubquery takes its value from SQinstead of computing it again. So everything
INwith a subquery does is kept: the set comparison of tuples(
(1, NULL) = ALL (SELECT (1, NULL))is 1), a NULLxfollowingtransform_null_in, FALSE rather than NULL whenthe subquery returns a NULL or several distinct values, conversions (
'01' = ALL (SELECT 1)is 1), theUInt8result type for a non-nullable
x, and the use of the primary key, also aNullableone(
id = ALL (SELECT 12345)reads one granule). As on master, a correlated subquery is not supported in= ALL(
INdoes not support it); it is supported for the other operators. In a distributed query the right-hand sideis evaluated once, on the initiator. The operator documentation is updated accordingly.
Tests:
04759_all_subquery_single_evaluationfails if the right-hand side is evaluated twice.05448_all_subquery_missing_row_and_nestingcovers the missing aggregate row, correlated subqueries and quantifiers nested in the right-hand and in the left-hand side.05493_all_subquery_primary_key_and_conversionscovers primary key usage (also withallow_nullable_key) and conversions.05621_equals_all_transform_null_in_and_result_typechecks that= ALLkeeps thetransform_null_inbehaviour, the comparison of tuples and the result type of the formerINrewrite.Scope: the fix covers the aggregate-based rewrites, that is
= ALL,< ALL,<= ALL,> ALLand>= ALL.!= ALLis deliberately left as a plainnotIn, which alreadyreturns TRUE on an empty right-hand side for a non-NULL left-hand side; only
NULL != ALL (empty subquery)keeps returning NULL, following the NULL semantics ofnotInand mirroring the untouchedNULL = ANY (empty subquery): under the defaulttransform_null_in = 0a NULL left-hand side (a literal NULL, a constant of a Nullabletype, or a NULL value inside a Nullable column) yields NULL before the emptiness of the
set is looked at, and only
transform_null_in = 1makes an empty right-hand side TRUEfor NULL as well. Making the empty-set NULL semantics standard-conforming belongs in
Set/FunctionIn, not in the parser rewrite, and is a separate decision.05045_notequals_all_single_evaluationpins that shape, so the!= ALLright-hand sidealso stays evaluated exactly once, and pins the NULL results above.
Closes #105957
Changelog category :
Changelog entry (a user-readable short description):
Fixed
= ALL,< ALL,<= ALL,> ALLand>= ALLon an empty subquery incorrectly returning FALSE instead of TRUE (vacuous truth).NULL != ALL (empty subquery)still follows the existingnotInNULL semantics.Workflow [PR]
Sync PR [sync-upstream/pr/106373]