Skip to content

Fix missing rows in EmbeddedRocksDB, KeeperMap and Redis key lookups for a FixedString, Variant or Dynamic constant - #127676

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-kv-key-filter-fixed-string-variant-constant
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-kv-key-filter-fixed-string-variant-constant

Conversation

@groeneai

@groeneai groeneai commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125880

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed EmbeddedRocksDB, KeeperMap and Redis tables returning fewer rows than = matches when the primary key is compared with a FixedString, Variant or Dynamic constant, for example WHERE key = toFixedString('V0', 3) on a String key, or a DateTime key compared with a Dynamic value holding a Date. Closes #125880.

Description

On 26.8.18.2, SELECT count() FROM t WHERE key = toFixedString('V0', 3) on an EmbeddedRocksDB table with a String key 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's NOT(NOT p) oracle on a KeeperMap table: 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:

  • the constant is FixedString and the key is String: the comparison is zero-padded, so the constant matches an unbounded family of keys;
  • the constant is Variant or Dynamic: it was converted with the wrapper as its source type, so an Enum alternative became its number and a Date alternative's day number was read as seconds;
  • the key column is a Tuple, Array or Map, whose elements are converted without their own types.

The key filter now converts the constant with the type of the value it holds (for Variant and Dynamic, the active alternative read from the column). When the converted constant still cannot be the only key = matches (a FixedString constant against a String key, 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 (a Dynamic holding a String or a tuple, a composite key with matching, Date/Date32, DateTime64 or FixedString element types, a text constant such as '[1,2]' against a composite key) still read by key; the test asserts ReadType: GetKeys.

Validation: the new test fails on master and passes with the fix, 50/50 with randomized settings; the existing EmbeddedRocksDB, KeeperMap and KV key filter tests pass.


Workflow [PR]
Sync PR [sync-upstream/pr/127676]

groeneai and others added 3 commits October 24, 2026 01:40
… 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, HEAD 675ecdf) - 3 agreed and fixed, 2 noted
  • ❌ AGREE, fixed: the test did not assert that a safe Variant (non-first alternative), Dynamic(max_types = 0) or Array constant keeps its key lookup; ReadType: GetKeys lines added.
  • ❌ AGREE, fixed: the composite-key tuple branch's Variant/Dynamic element handling had no test; added (d, x) = (SELECT (CAST(toDate('2020-01-01') AS Dynamic), 1)) (0 rows before the fix, 1 after, with GetKeys).
  • 💡 AGREE, fixed: a redundant tuple-type variable removed.
  • 💡 DISAGREE (out of scope): a Float key compared with zero looks up one sign of zero while = matches both; a different cause, not part of this change.
  • 💡 DISAGREE: the active-alternative lookup is local because the shared helper is file-private and being reworked in Render a typed constant converted to String with its own text serialization #118372.

Round 2 re-review of the fixes: no new findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test against a master server fails at default settings on every count line except one preservation control (key = toFixedString('V0', 3) returns 1, a full scan 3; Dynamic holding a Date on a DateTime key returns 0, a full scan 1). Also on official 26.8.18.2.
b Root cause explained? The KV key filter probes one converted constant, but = can match more keys: String vs FixedString compares zero-padded; a Variant/Dynamic constant was converted with the wrapper as its source type; composite key elements are converted without their types.
c Fix matches root cause? Yes. The constant is converted with the type of the value it holds; when the converted value is not the only matching key, the atom is not a key filter (full scan). No comparison or conversion semantics change.
d Test intent preserved / new tests added? New 05447_kv_key_filter_fixed_string_and_variant_constant: FixedString with wrappers, Variant/Dynamic (incl. max_types = 0, Enum and Date alternatives), composite primary key, Tuple/Array/Map key columns, the KeeperMap shape the fuzzer found, plus ReadType: GetKeys lines for lookups that must be kept.
e Both directions demonstrated? Yes. Fails on a master build with exactly the expected diffs, passes with the fix; 50/50 with randomized settings.
f Fix is general across code paths? Both equals branches (single key and composite-key tuple). AND/OR recurse into them; IN builds its set with the element types and compares exactly (unchanged). All three engines share getFilterKeys.
g Fix generalizes across inputs (params/datatypes/wrappers)? Constant wrappers Nullable, LowCardinality, LowCardinality(Nullable), Variant, Dynamic, JSON path; keys String, LowCardinality(String), FixedString, composite, Tuple/Array/Map; NULL constant. 19 lookup shapes measured to keep GetKeys exactly as on master.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Affected queries now return all matching rows; String key = FixedString-valued constant becomes a full scan.
i Invariants and contracts preserved? The looked-up keys contain every stored key the condition can be true for. Every new exit is the function's existing "not a key filter" return, and the condition is re-applied to the rows read, so a result can only gain the missing rows.

Session id: cron:clickhouse-impl-slot-4:20261024-020800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @KochetovNicolai, could you review this and add the can be tested label so CI runs? The KV key filter looked up only the one converted constant, so a FixedString constant on a String key (zero-padded =) or a Variant/Dynamic constant (converted with the wrapper as its source type) missed matching keys; it now converts with the active alternative's type and falls back to a full scan when the converted value is not the only key = can match.

@clickhouse-gh

clickhouse-gh Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e09d97a]

Summary: ✅


AI Review

Summary

The PR corrects incomplete key lookups for FixedString, Variant, and Dynamic constants in EmbeddedRocksDB, KeeperMap, and Redis. At head e09d97abd6a54abc213fc29400cb1f1def51d485, two previously reported regressions remain: safe comparisons lose their point lookups and scan the entire table. Changes are still required.

Findings

⚠️ Majors

  • src/Storages/KVStorageUtils.cpp:414–426, 450–457: Shared-storage Dynamic tuples still lose exact lookups. For an outer Dynamic(max_types = 0), selecting the active variant returns a ColumnString containing the serialized tuple. Consequently, value_tuple_column is null, and a nested Dynamic element reaches getConstantValueType without its column and rejects the lookup. On an EmbeddedRocksDB table with primary key (a String, b UInt64), this previously exact predicate selects FullScan:

    WHERE (a, b) = CAST((CAST('x' AS Dynamic), toUInt64(1))
                       AS Dynamic(max_types = 0))

    A two-row table with one matching row exceeds max_rows_to_read = 1; larger tables incur a full scan. Normalize the outer constant to its active typed column, including decoding shared storage, before resolving its elements. Keep type and column extraction together so every supported representation follows the same path. Existing thread; the remaining shared-storage case is already reported there.

  • src/Storages/KVStorageUtils.cpp:171–173: Safe Time64 element rescaling still becomes a full scan. For an Array(Time64(3)) key, comparing with [toTime64('00:00:00.123000', 6)] fails the new allowlist: the scales differ, isNumber excludes Time64, and only DateTime64 has an explicit scale-conversion allowance. The Decimal64 field carries its scale, so the existing conversion can still produce the exact lookup key. This changes GetKeys into FullScan, reading every row and failing a one-row read limit on a two-row fixture. Preserve the safe Time64 pair in the common conversion rule, including its use in Tuple and Map elements. Existing thread.

Tests
  • ⚠️ Add ReadType: GetKeys assertions and matching-row checks for an outer Dynamic(max_types = 0) tuple with a nested Dynamic element, and for a composite key column containing Time64 values compared across scales. The new stateless test does not cover either remaining regression.
Missing context / blind spots
  • ⚠️ No local build or executable was available, so these findings were verified by tracing the current source and revisiting the existing repros, without rerunning them. Current-head execution of the focused stateless cases would close this validation gap.
Final Verdict

Status: ⚠️ Request changes. Preserve both exact lookup cases and add the focused regression assertions above. Both findings already have open inline threads; no duplicate comments were posted.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). labels Oct 24, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a029664

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable, published 2026-10-24 04:17Z, ships use_query_condition_cache_for_time_conditions = false after #127632, while master's settings history still says its default became true in 26.10. Every PR whose Upgrade check started after 04:17Z reports the same 1 / 0 row #127687 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127687 (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261024-063004

Comment thread src/Storages/KVStorageUtils.cpp Resolved
`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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/Storages/KVStorageUtils.cpp Resolved
…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]>
Comment thread src/Storages/KVStorageUtils.cpp Resolved
…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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e09d97abd with master 1d4ff1539 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.62, programs/clickhouse-keeper ×0.59 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.4 s 10.1 s +6.2 s (+155%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.4 s +5.1 s (+227%)
Compile time of recompiled translation units

7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1db6d63

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Received signal 6 (internal) (STID: 1202-2b88) not from this PR: libc++ hardening abort in DB::highlight via ClientBase::echoQuery in the embedded client, the same STID on master and on 21 other PRs in 2 days #127906 (mine, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this PR: all 100 flagged lines are Code: 153 Division by zero in intDiv(100, x) While executing TTL, the deliberately failing merge of the 05073_column_ttl_recompute_materialized fixture that outlives the test; same error on 14 other PRs since 2026-10-24 #127731 (mine, open)
Fast test (arm_darwin) / 05397_clickhouse_local_locked_path_untouched not from this PR: the test holds the lock with flock(1), which macOS does not have, so it fails on every PR that has merged master since #116042 (11 other PRs today) #128088 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #127906, #127731, #128088 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

EmbeddedRocksDB/KeeperMap lose rows on String key = FixedString lookup

2 participants