Repository navigation
Fix missing rows in EmbeddedRocksDB, KeeperMap and Redis key lookups for a FixedString, Variant or Dynamic constant - #127676
Conversation
… constant `EmbeddedRocksDB`, `KeeperMap` and `Redis` turn `key = <constant>` into a point lookup of the one converted constant and re-apply the condition to the rows read, so the looked-up keys must include every stored key `=` can match. They did not: - `equals(String, FixedString)` compares zero-padded (ClickHouse#104858), so a `FixedString` constant equals every `String` key that differs from it in trailing zero bytes, an unbounded family, while only its exact bytes were looked up; - a `Variant` or `Dynamic` constant hands out the value of its active alternative, but was converted with the wrapper as the source type, so the `FixedString` case was invisible and the source-typed conversion branches (ClickHouse#118689) were missed: an `Enum` alternative became its number, a `Date` alternative's day number was read as seconds, and the lookup probed a key that does not exist; - a key column of type `Tuple`, `Array` or `Map` converts its elements without their own types (`convertFieldToType`), with the same two problems per element. Both `equals` branches of `getFilterKeys` now convert the constant with the type of the value it holds (for `Variant`/`Dynamic`, the alternative read from the column; the scalar-subquery tuple column is `Nullable(Tuple)`, so it is unwrapped first), and return "not a key filter" (a full scan) when the converted constant is not the only key `=` can match. Inside a composite only elements whose conversion does not depend on their type keep the lookup; any other type with subtypes fails closed. `IN`, `AND` and `OR` are unchanged. Found by the AST fuzzer's `NOT(NOT p)` oracle on a `KeeperMap` table with a `LowCardinality(String)` key: the lookup returned 1 row, the full scan 3. Present on 26.8.18.2. Closes ClickHouse#125880 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…constants
Cover the paths of the key filter fix that no test reached:
- a `Variant` constant whose active alternative is not the first one,
`Dynamic(max_types = 0)`, and an `Array` key keep `ReadType: GetKeys`;
- the composite-key tuple branch resolves a `Dynamic` element to its active
alternative: `(d, x) = (SELECT (CAST(toDate('2020-01-01') AS Dynamic), 1))` on a
`(DateTime, UInt64)` key returned 0 rows before the fix and now returns 1 with a
key lookup.
Also drop a redundant tuple-type variable: `recursiveRemoveLowCardinality` does not
enter `Variant`, and `getConstantValueType` strips the other wrappers itself, so the
element type of the stripped tuple type is the same one.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the fail-closed narration in isCompleteKeyLookup, merge its doc into two lines, and drop the Variant sentence that repeats getConstantValueType's doc. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review (2 rounds, HEAD 675ecdf) - 3 agreed and fixed, 2 noted
Round 2 re-review of the fixes: no new findings. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261024-020800 |
|
cc @alexey-milovidov @KochetovNicolai, could you review this and add the |
|
Workflow [PR], commit [e09d97a] Summary: ✅
AI ReviewSummaryThe PR corrects incomplete key lookups for Findings
Tests
Missing context / blind spots
Final VerdictStatus: |
CI finish ledger - a029664Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261024-063004 |
…ixed-string-variant-constant
`isCompleteKeyLookup` rejected every structural mismatch between a composite
key type (`Tuple`, `Array`, `Map`) and the constant's type, so a `String`
literal such as `key = '[1,2]'` against an `Array(UInt32)` key turned the
point lookup into a full scan (`max_rows_to_read = 1` now threw
`TOO_MANY_ROWS`). Master looks those keys up.
The lookup is exact for such a literal: `=` with a constant `String` or
`FixedString` (`executeWithConstString`) parses the text into the key type
with `convertFieldToType`, and the KV storages convert the literal through
the same string-parsing branch, so the converted key is the only one `=` can
match. This also holds for a text element inside a composite constant
(`key = ('[1, 2]', 'a')` for a `Tuple(Array(UInt32), String)` key) and for a
composite primary key column, which call the same predicate.
Measured on Array, Tuple, Map, nested Tuple(Array) and two-column keys,
and for String, FixedString and LowCardinality(Nullable(String)) literals:
master GetKeys, previous head FullScan, now GetKeys, same counts everywhere.
The test gains GetKeys assertions for these cases.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (element_type) | ||
| element_type = getConstantValueType(element_column, element_type); | ||
| if (!element_type) | ||
| return false; |
There was a problem hiding this comment.
[P2] Resolve the active tuple type before extracting its elements
When the whole tuple constant is wrapped in Dynamic or Variant, value_tuple_type is null because it is derived from the wrapper's result_type. Consequently element_type remains null and this new return turns a previously exact composite-key lookup into a full scan. For example:
CREATE TABLE t (a String, b UInt64, value String)
ENGINE = EmbeddedRocksDB PRIMARY KEY (a, b);
INSERT INTO t VALUES ('x', 1, 'found'), ('y', 2, 'other');
SELECT value FROM t
WHERE (a, b) = CAST(('x', toUInt64(1)) AS Dynamic)
SETTINGS max_rows_to_read = 1;Before the PR this returns found using GetKeys; with the new guard it throws TOO_MANY_ROWS after reading both rows. Variant(Tuple(String, UInt64), String) regresses in the same way. On larger tables these point queries now scan the entire table. Resolve the whole constant's active tuple type and backing tuple column before extracting element types, then apply the per-element safety checks. Please cover both wrapper forms with GetKeys assertions.
There was a problem hiding this comment.
Fixed in 391b8b0: the composite-key branch now resolves the type of the value a Dynamic or Variant constant holds before reading its elements, and the test asserts GetKeys for both wrapper forms.
There was a problem hiding this comment.
391b8b099956 resolves the outer type, but src/Storages/KVStorageUtils.cpp:398-403 still unwraps only ColumnConst and ColumnNullable, leaving the outer ColumnDynamic or ColumnVariant in place. Thus value_tuple_column is null, and a nested wrapped element reaches getConstantValueType(nullptr, element_type) at line 418 and returns false at line 420. On the table from this thread:
SELECT value FROM t
WHERE (a, b) = CAST((CAST('x' AS Dynamic), toUInt64(1)) AS Dynamic)
SETTINGS max_rows_to_read = 1;This still loses the previously exact lookup: master returns found with GetKeys, whereas the remaining guard selects FullScan and the query exceeds the read limit. The same column-extraction gap affects an outer Variant containing a tuple with a Variant element. Please extract the backing tuple column together with its active type before resolving the element types.
There was a problem hiding this comment.
Fixed in 1db6d63: the tuple column is now read from the active alternative of an outer Dynamic or Variant, and the test asserts GetKeys for both forms.
There was a problem hiding this comment.
The shared-storage representation still leaves this column-extraction gap in 1db6d63faceb. At src/Storages/KVStorageUtils.cpp:402-410, an outer Dynamic(max_types = 0) selects its shared ColumnString, containing the serialized tuple. The cast at line 414 therefore yields no tuple column, and the nested Dynamic element reaches getConstantValueType(nullptr, element_type) at line 429 and returns false at line 431.
On the table from this thread, the remaining case is:
SELECT value FROM t
WHERE (a, b) = CAST((CAST('x' AS Dynamic), toUInt64(1)) AS Dynamic(max_types = 0))
SETTINGS max_rows_to_read = 1;The base lookup returns found; the remaining guard forces a full scan and exceeds the one-row limit. Please decode the shared value into its typed tuple column before resolving its elements, and cover this representation with a GetKeys assertion.
…32 elements
A composite-key equality whose whole tuple constant is a `Dynamic` or `Variant`
(`(a, b) = CAST(('x', 1) AS Dynamic)`) resolved no element types, so it fell back
to a full scan. Resolve the type of the value the constant holds first, as the
single-column branch does; the per-element checks then apply to the resolved
elements (a wrapped `FixedString` element still scans, a wrapped `Date` element
against a `DateTime` key now converts with its type and is looked up).
A `Date32` element against a `Date` key element (and the reverse) was rejected,
although both are day numbers and the element conversion without a source type is
range-checked: an out-of-range day is not converted and the condition is evaluated
over a full scan.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…4 and FixedString elements The composite-key equals branch now reads the tuple column of a constant wrapped in Dynamic or Variant from its active alternative, so a Dynamic or Variant element of that tuple resolves to the value it holds instead of turning the lookup into a full scan. A Dynamic element holding a FixedString still forces the full scan (String keys compare zero-padded). DateTime64 elements of different scales and FixedString elements of different widths convert without the element source type exactly: the Decimal field carries its scale, and a FixedString constant is zero-padded or truncated to the key width, which is how `=` compares them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| return false; | ||
|
|
||
| return !is_element || value->equals(*key) || isString(value) || isNumber(value) || isNothing(value) | ||
| || (isDateOrDate32(value) && isDateOrDate32(key)) || (isDateTime64(value) && isDateTime64(key)) |
There was a problem hiding this comment.
[P2] Preserve exact lookups across Time64 scales
The new allowlist still rejects Time64 elements with another scale: isNumber excludes Time64, and equals compares the scales. This turns an existing point lookup into a full scan:
SET enable_time_time64_type = 1;
CREATE TABLE t (key Array(Time64(3)), value String)
ENGINE = EmbeddedRocksDB PRIMARY KEY key;
INSERT INTO t VALUES (['00:00:00.123'], 'found'), (['00:00:01.123'], 'other');
SELECT value FROM t WHERE key = [toTime64('00:00:00.123000', 6)]
SETTINGS max_rows_to_read = 1;The base version uses GetKeys and returns found; this guard rejects the element pair and selects FullScan, so the query exceeds the read limit. Without that limit it reads the entire table. Like DateTime64, the Time64 field carries its scale, so this conversion does not need an element source hint. Please retain the safe Time64 pair too and add a GetKeys assertion for it.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 1db6d63Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261028-213004 |
…ixed-string-variant-constant Resolve the conflict in src/Storages/KVStorageUtils.cpp with master's float/Decimal key checks (ClickHouse#128086): keep master's floatValuesMissKeyValues checks before the constant-type resolution, and extend master's tuple column extraction with the Dynamic/Variant unwrapping of this PR. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #125880
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
EmbeddedRocksDB,KeeperMapandRedistables returning fewer rows than=matches when the primary key is compared with aFixedString,VariantorDynamicconstant, for exampleWHERE key = toFixedString('V0', 3)on aStringkey, or aDateTimekey compared with aDynamicvalue holding aDate. Closes #125880.Description
On 26.8.18.2,
SELECT count() FROM t WHERE key = toFixedString('V0', 3)on anEmbeddedRocksDBtable with aStringkey holding'V0','V0\0'and'V0\0\0'returns 1, while=matches all 3 (a full scan returns 3). Found on master by the AST fuzzer'sNOT(NOT p)oracle on aKeeperMaptable: CI report.The KV storages turn
key = <constant>into a lookup of the one converted constant and re-apply the condition to the rows read, so the looked-up keys must include every stored key=matches. They did not when:FixedStringand the key isString: the comparison is zero-padded, so the constant matches an unbounded family of keys;VariantorDynamic: it was converted with the wrapper as its source type, so anEnumalternative became its number and aDatealternative's day number was read as seconds;Tuple,ArrayorMap, whose elements are converted without their own types.The key filter now converts the constant with the type of the value it holds (for
VariantandDynamic, the active alternative read from the column). When the converted constant still cannot be the only key=matches (aFixedStringconstant against aStringkey, or a composite element converted without its type), the condition is not used as a key filter and is evaluated over a full scan. Other lookups (aDynamicholding aStringor a tuple, a composite key with matching,Date/Date32,DateTime64orFixedStringelement types, a text constant such as'[1,2]'against a composite key) still read by key; the test assertsReadType: GetKeys.Validation: the new test fails on master and passes with the fix, 50/50 with randomized settings; the existing
EmbeddedRocksDB,KeeperMapand KV key filter tests pass.Workflow [PR]
Sync PR [sync-upstream/pr/127676]