Repository navigation
Report a lossy constant normalization as an inexact atom - #118957
Conversation
Index analysis normalizes a comparison constant into the type the key
expression reads before applying the key transform, and
`castColumnWithoutNulls` accepted that cast as exact whenever it
produced no `NULL`s. A cast can lose information without producing a
`NULL`: `accurateCastOrNull` from `DateTime64(6)` to `DateTime64(3)`
truncates the sub-millisecond digits instead of answering `NULL`. The
truncated constant is then the exact preimage of a real key point, so
the `notEquals` atom excluded that point and the granule - or, with a
partition key of the same shape, the whole partition - holding a live
row was pruned:
CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY toString(d);
INSERT INTO t VALUES (toDateTime64('2023-02-01 12:00:00.000', 3, 'UTC'));
SELECT count() FROM t WHERE d != toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC');
-- 0, the truth is 1
The cast now reports whether it was lossless, by casting back and
comparing. A lossy normalization leaves the atom relaxed - the key point
it names has more than one preimage, exactly as a non-injective
transform does - so `notEquals` no longer excludes it while `equals`
keeps its pruning. The set-index path has no relaxed form for a single
element (`notIn` would exclude the same point), so a lossy
normalization declines index analysis there.
|
Workflow [PR], commit [17c7c2b] Summary: ✅
AI ReviewSummaryThis PR fixes exactness tracking when constants and set elements are normalized into key space before pruning. On the current head, the follow-up fixes for Final Verdict
LLVM Coverage ReportMeasured on commit 17c7c2b.
Changed lines: Changed C/C++ lines covered: 150/153 (98.04%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
It is pedantic, but ok.
The exactness probe already had the forward cast: the `accurateOrNull` probe that proved every value fits is that cast, and its null map was just shown to be empty, so its nested column is what a second `castColumnAccurate` would return. Read that column back instead of casting again. The probe moves into `castKeptEveryValue`, so the set path can ask the same question about a set element. `'007'` read as `7` was the wrong example for the comment. A comparison against a `String` constant converts the spelling into the type of the other side with `convertFieldToType`, which refuses `'007'` for a numeric target - `SELECT 7 = '007'` raises `TYPE_MISMATCH` - so such a constant never reaches index analysis.
`tryPrepareSetColumnsForIndex` normalizes every set element into the type of the key column and
dropped only the elements the cast turned into a `NULL`. A truncated element is not a `NULL`: a
`DateTime64(6)` element of a subquery set becomes the exact preimage of a `DateTime64(3)` key point,
and the set atom then names a point the predicate does not. On a key that needs no transform at all:
```sql
CREATE TABLE t (d DateTime64(3, 'UTC')) ENGINE = MergeTree ORDER BY d;
INSERT INTO t VALUES (toDateTime64('2023-02-01 12:00:00.000', 3, 'UTC'));
SELECT count() FROM t WHERE d NOT IN (SELECT toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC'));
-- 0, the truth is 1: `notIn` excluded the point the element was truncated to
SELECT count() FROM t WHERE d IN (SELECT toDateTime64('2023-02-01 12:00:00.000001', 6, 'UTC'));
-- 1, the truth is 0: `in` was read as certainly true over that point, so the count came from the
-- part without filtering its rows
```
A literal set hides both, because the literal is coerced to the type of the left argument before the
index sees it, which makes the index and the rows agree by construction.
A set atom does have a relaxed form - `out.relaxed`, which the non-injective transform path already
uses - so a lossy normalization now relaxes the atom instead of being reported as exact. The element
itself stays: a relaxed atom is a superset of the predicate, so the points the set does not hold still
prune. That also lets the transform path keep its index analysis, which the previous commit of this
pull request declined outright for a lossy element.
…son uses A `String` constant does not name a value in its own domain: the comparison converts the spelling into the type of the other side and compares there (`executeWithConstString` in `FunctionsComparison.h`), so it is that conversion, not the spelling, that the predicate is about. Rendering the normalized constant back into a string judged the spelling instead - `'2023-02-01 12:00:00'` comes back as `'2023-02-01 12:00:00.000'` - and relaxed an atom that names exactly the point the predicate asks for, so `ORDER BY toString(d)` lost the `!=` pruning it had before this pull request. Ask `convertFieldToType`, the conversion the comparison itself performs, whether the normalized constant is the value the predicate names. The two answers can differ only where the comparison raises - `'007'` against a numeric column, a date-time string against a `Date` column - and then no pruning decision matters, because the query does not produce a result at all. A string-ish key column is left to the round trip: two string-ish types are compared as bytes (`executeString`), where the padding a `FixedString` target adds really does change the compared value.
The set arms run literal `NOT IN`, subquery `NOT IN`, `NOT has` and `IN` against the `toString(d)` key and against a bare `ORDER BY d` key, each next to its `countIf` twin. The bare-key subquery arms are the ones that answered 1 against 2 for `NOT IN` and 1 against 0 for `IN` before the set path reported a lossy element; the literal arms agree by construction, because a literal set is coerced to the type of the left argument before the index sees it, and they are here to pin that difference. Over-reporting a normalization as lossy would silently disable pruning, which no answer can show, so a new block pins the lossless directions with `max_rows_to_read`: a lost pruning becomes a `TOO_MANY_ROWS` failure. The statistics pruner, the query condition cache and parallel replicas are pinned off there, so the granule mask under test is the key condition's own. The lossy constant is pinned the other way round, as `serverError TOO_MANY_ROWS`.
`castColumnAccurateOrNull` reports a value that does not fit by wrapping its target in `Nullable`, so the nested column the exactness probe reads back carries the target *without* that `Nullable` - and for a target that is itself `Nullable` the probe was handed the nested column next to the wrapped type, which `columnGetNested` refuses: ```sql SELECT count() FROM test_table_72265_1 WHERE (a > 100) AND ((a % 2) = toUInt128(0)); -- Code: 44. DB::Exception: Illegal column Nullable(Int8) Int8(size = 1) for DataTypeNullable ``` Every `Nullable` key column read through a deterministic transform raised it: `01739_index_hint`, `03311_issue_72265`, `03727_tolowcardinality_nullable_cast`, `04006_nullable_partition_minmax_merge`, `04237_104840_partition_pruner_floor_null_nullable_key` and `04401_low_cardinality_fixed_string_partition_pruning`. A `Dynamic` element lost its exact atom for a different reason: `accurateOrNull` cannot wrap a type that carries its own NULLs, so the probe declined to answer and `05055_not_has_tuple_layout_and_variant_key_condition` stopped pruning. A `Dynamic` cannot refuse a value either, though - every value fits one - so there the plain accurate cast is total and its result answers the question directly.
…-constant-118691 # Conflicts: # src/Storages/MergeTree/KeyCondition.cpp
…xact `05055_not_has_tuple_layout_and_variant_key_condition` lost a granule of pruning on this branch: `notHas(CAST([2], 'Array(Dynamic)'), k)` over an `Int64` key answered `Granules: 4/4` instead of `3/4`. A `Dynamic` keeps the type each value was inserted with, so the element `2` is held as a `UInt8` there, the cast to the key type makes it an `Int64`, and the reverse cast returns a `Dynamic` holding `Int64(2)`. `Field::operator==` answers only for values carried the same way and reported `UInt64(2) != Int64(2)`, so an exact cast was called lossy and the atom was relaxed for nothing. Compare two numeric `Field`s the way the comparison functions compare them, across carriers, and leave every other pair of carriers to the strict answer - `accurateEquals` cannot compare those at all. A `DateTime64(6)` constant truncated to `DateTime64(3)` is still reported as lossy: both sides are carried as a `Decimal64` and the strict comparison already accounts for the scale. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Merged Conflict resolution (
Locally against this build: The |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
tiandiwonder
left a comment
There was a problem hiding this comment.
Two blockers; the core change looks right to me otherwise. I checked that the relaxation is applied before the NOT_IN_RANGE / NOT_IN_SET negation in both evaluators, so the widened can_be_false really does become a widened can_be_true and != / NOT IN stop excluding the point — the mechanism does what the description says.
The blockers are the Dynamic equality below, and the new test failing deterministically on the private sync CI: 20 of the 22 new failures on sync-upstream/pr/118957 are 05164_key_condition_lossy_constant_not_equals.
…-constant-118691 # Conflicts: # src/Storages/MergeTree/KeyCondition.cpp
`IN` asks the `Set`, which hashes and compares the type each `Dynamic` value carries before the value, and `Set::execute` casts the key into the set's type with the key column's type as its carrier. The round trip in `castKeptEveryValue` compares `Field`s, which cannot see a `UInt8` versus a `UInt64` carrier, so `k IN (SELECT CAST(toUInt8(2), 'Dynamic'))` over an `Int64` key was reported exact: `IN` answered 1 instead of 0 and `NOT IN` pruned a live row. `tryPrepareSetColumnsForIndex` now reports such a set as inexact for `IN`; `has` keeps the round trip, since it compares by value. Test changes in `05164_key_condition_lossy_constant_not_equals`: - drop the literal-set `NOT IN` arms: the literal set is coerced to the key type before the index sees it, so they do not exercise this change, and their row-level answer depends on randomized settings (they failed in private CI); - pin a `String` subquery element staying inexact for `notIn`; - pin the `Dynamic` subquery element for `IN` and `NOT IN` (control build without the check answers 1 and 1 instead of 0 and 2). Also note why the `String` rehabilitation uses strict `Field` equality. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A `Set` over `Variant` is discriminator-sensitive just like one over `Dynamic`: `Set::execute` casts the key into the set's type, and `ColumnVariant` hashes and compares the active discriminator before the value. A `Variant` element usually fails the round trip in `castKeptEveryValue` already, because a `Variant` cannot be inside `Nullable`, but `canBeSafelyCast` takes a `Variant` to a `Nullable(String)` key without any round trip. So `k IN (SELECT CAST(toUInt8(2), 'Variant(UInt8, String)'))` over a `Nullable(String)` key was reported exact: `IN` answered 1 instead of 0 and `NOT IN` pruned a live row (1 instead of 2). The carrier guard in `tryPrepareSetColumnsForIndex` now also covers a set element type containing a `Variant` anywhere, besides the types with dynamic subcolumns. Added the `Variant` arm next to the `Dynamic` one in `05164_key_condition_lossy_constant_not_equals`; a control build with the old `hasDynamicSubcolumns` guard answers 1 1 1 instead of 0 2 2. #118957 (review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tring` key `IN` over a subquery casts the key into the set's type, so for a string-ish column it parses the key and many spellings match one element: `s IN (SELECT toUInt8(2))` matches both `'2'` and `'02'`. The index renders the element into a single spelling and read every other one as certainly not in the set, pruning rows the predicate keeps. Relaxing the atom does not help because a relaxed atom still prunes on the points it holds, so such a set is not used by the index at all. This is pre-existing, but it is the mirror of the scalar `String` case this PR handles. Also adapt the new `applyDeterministicDagToColumn` call for zero probing that came with the merge of `master` to the extended signature. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The fix is #124342 (test-only). The failing tables |
… from the `String` key bailout
A top-level `Dynamic`, `Variant` or `JSON` set element over a `String` / `FixedString` key was
exempt from the bailout for non-`String` elements, so the index was built from the element's
rendered string. But `Set::execute` converts the key into the element type, which is not total
and not a byte comparison: `s IN (SELECT CAST(toDate('2024-01-01'), 'Variant(Date)'))` raises
`CANNOT_CONVERT_TYPE` in the full scan, and `s IN (SELECT CAST('{"a":1}', 'JSON'))` matches
`'{"a" : 1}'` as well. Pruning from the rendered string hid the error or dropped the matching
row. `Dynamic` parses the key as well under `cast_string_to_dynamic_use_inference`. Do not use the
index for such sets, and pin both shapes in the test.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The only red check is
There are no unresolved review threads. |
Master's ClickHouse#118957 made `tryPrepareSetColumnsForIndex` report an inexact set itself, through `out_is_exact` and a value-level round trip of every element, which is what this branch's own type-level `set_is_approximate` flag did more coarsely. The conflict is resolved by taking master's version of that plumbing (signature, both callers, the relaxation conditions and their comments) and keeping only the decline for a key-to-set cast that can merge two distinct keys, which master still answers with missing rows (Decimal / DateTime64 scale loss, a temporal target dropping a component, a collapsing text element inside a Tuple). Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Stress test runs the server-side AST fuzzer on every successful statement, DDL included (`ast_fuzzer_runs = 5`, `ast_fuzzer_any_query = true`). After `CREATE TABLE reader ... disk(readonly = true, ...)` it creates `reader__fuzz_N`: more readonly tables over the same `table_disk` root, each attached with the writer's parts of that moment, and nothing drops them. The test's `DROP TABLE writer SYNC` then deletes the objects of those parts, and later reads of the clones in the kept stress database (fuzzed reads, 02046's `merge(currentDatabase(), '') FINAL`) fail with `S3_ERROR The specified key does not exist` on `data.packed`, which the stress `No such key` check reports (PR ClickHouse#118957, Stress test (arm_release)). 05227 and 05228 build the same readonly reader over a writer they drop. In 05228 the reader `DROP` also runs after the writer's drop has finished, so a reader `DROP` ignored by `ignore_drop_queries_probability` (it becomes a TRUNCATE of a read-only table and fails with TABLE_IS_PERMANENTLY_READ_ONLY) leaves a stale reader as well, and an ignored background writer `DROP` makes the test wait forever in `SYSTEM WAIT FAILPOINT ... PAUSE`. In 05104 and 05227 both drops share one multi-statement block, so an ignored reader `DROP` stops the block before the writer drop; the pin there keeps the block's drops. Pin `ast_fuzzer_any_query = 0` in the sessions that create the tables and `ignore_drop_queries_probability = 0` in the sessions that drop them. Only the SELECTs of those sessions stay fuzzed; the ALTERs and OPTIMIZE of 05104 run in other sessions and stay fuzzed too. Measured locally with the Stress fuzzer settings and one fixed database per run: 05104 left fuzzer clones in 13 of 87 databases before (816 fuzzed clone CREATEs, the CI error reproduced by the 02046-style read in 4), none after (0 fuzzed CREATEs in 80 runs); 05228 likewise. In 05227 a clone survives only when the fuzzer drops the copied UUID clause (19 of 414 reader attempts in 05104 did); none of its 47 did in 10 runs, and after the change it makes no fuzzed CREATE in 10 runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#118957, `toString(k) IN (SELECT <integers>)` over an integer key `k` no longer uses the primary key (ClickHouse#130315): `EXPLAIN indexes = 1` shows `Condition: true` and every granule is read, where 26.8 pruned with `toString(k) in N-element set`. The same holds for `CAST(k AS String)`, `k::String`, a `String ALIAS k` column (`_CAST`), `Nullable`/`LowCardinality` integer keys and a `Date` key with a `Date` set. ClickHouse#118957 made `tryPrepareSetColumnsForIndex` decline a non-`String` set element over a string predicate column, because `Set::execute` casts the column into the element type by parsing, where many spellings name one value (`'02'` and `'2'`), while the index renders the element into a single spelling. That premise does not hold when the string column is the text of a native integer (or of a `Date`) that the key's monotonic chain itself computes: the column then holds only canonical numerals, `accurateOrNull` of a canonical numeral into a native integer type gives that number or NULL, and an integer element renders to the canonical numeral of its own value, so the set and the index agree exactly. Keep the decline, except when the chain ends with `toString`/`CAST`/`_CAST` to `String` of a native integer and the element is a native integer, or both are `Date`. Types with a custom serialization are excluded on either side: `Bool` is a `UInt8` that renders as `true` while the key's `'1'` parses to `true` (also inside `SimpleAggregateFunction(any, Bool)`, which keeps `SerializationBool` under another name). A `String` key, `FixedString` targets, `DateTime` and the other types keep the decline. Reverting ClickHouse#118957 would bring back the wrong results it fixed (for example `s IN (SELECT toUInt8(2))` over a `String` key holding `'02'`). Closes ClickHouse#130315 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Index analysis normalizes a comparison constant into the type the key expression reads before applying the key transform, and
castColumnWithoutNullsaccepted that cast as exact whenever it produced noNULLs. A cast can lose information without producing aNULL:accurateCastOrNullfromDateTime64(6)toDateTime64(3)truncates the sub-millisecond digits instead of answeringNULL. The truncated constant is then the exact preimage of a real key point, so thenotEqualsatom excluded that point and the granule - or, with a partition key of the same shape, the whole partition - holding a live row was pruned:The cast now reports whether it was lossless, by casting back and comparing. A lossy normalization leaves the atom relaxed - the key point it names has more than one preimage, exactly as a non-injective transform does - so
notEqualsno longer excludes it whileequalskeeps its pruning.The set path normalizes its elements the same way, and had the same hole with no key transform involved at all, in both directions (found in review):
A lossy element now relaxes the set atom -
out.relaxed, the mechanism the non-injective transform path already uses - instead of being reported as exact, so neither exclusion survives. The element itself stays in the set: a relaxed atom is a superset of the predicate, so the points the set does not hold still prune. A literal set hides the defect, because a literal is coerced to the type of the left argument before the index sees it, which makes the index and the rows agree by construction.A
Stringconstant does not go through the round trip: the comparison converts the spelling into the type of the other side and compares there (executeWithConstString), so exactness is decided against that conversion rather than against the spelling.'2023-02-01 12:00:00'renders back as'2023-02-01 12:00:00.000'while naming exactly the same key point, and keeps its pruning.Closes: #118691
Related: #118688
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed rows silently dropped, or counted without being filtered, when a
DateTime64constant of a finer scale than the column is compared with!=,NOT INorIN: index analysis truncated the constant and treated the truncated value as the exact point the query asked for, pruning the granule or partition that held a matching row.Workflow [PR]
Sync PR [sync-upstream/pr/118957]
Version info
26.10.1.1893-master(included in26.10and later)