Repository navigation
Speed up Map key lookup for LowCardinality keys - #120453
Conversation
Extracting a value from a Map with LowCardinality keys compared the key values for every entry of a row until the key was found, so the cost grew with the position of the key in the row. The subcolumn path (findKeyPositionsDispatch in DataTypeMapHelpers.cpp) has no LowCardinality specialization and falls back to the generic matcher, which goes through virtual compareAt into a dictionary lookup and a string comparison per entry. On a 20-key `Map(LowCardinality(String), String)` this made a lookup of the last key more than three times as expensive as a lookup of the first one. Resolve the requested key to its dictionary position once and compare the dictionary positions instead, which is what FunctionArrayElement already did on the arrayElement path. A key that is not in the dictionary cannot be in any row, so it is now answered without looking at the rows at all. The first-match semantics restored by #111203 are untouched: every row is still scanned left to right and the first match is taken. Only the cost of a single comparison changes, so no position-prediction shortcut comes back. The shared helper is also used by FunctionArrayElement, which compared dictionary positions through ColumnLowCardinality::getIndexAt and so repeated the index type dispatch for every entry. Also close the dispatch gaps that sent whole type families to the generic per-row fallbacks: UUID, IPv4, IPv6, the wide integers and BFloat16 as keys and as values, the Decimal, DateTime64 and Time64 types as values, and the same as keys, which are reachable through the subcolumn name even though m[key] rejects them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The stateless test covers what the dictionary lookup can get wrong that a value comparison cannot: a key absent from the dictionary, a key present in the dictionary but absent from a row, the empty string in the reserved default position, and a dictionary position too large for the index type of a block, which a shared dictionary makes possible. Every case is asserted under both optimize_functions_to_subcolumns settings so the two paths must agree, and the key and value type matrices cover the types that used to go through the generic fallbacks. The performance test uses a 20-key map, where the cost of a lookup used to grow with the position of the key, and looks up the first, a middle, the last and an absent key. The existing get_map_value.xml only covers a three-key `Map(String, String)`, which is why this never showed up in CI. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [529f321] Summary: ❌
AI ReviewSummaryThis PR resolves constant Final Verdict
LLVM Coverage ReportMeasured on commit 529f321.
Changed lines: Changed C/C++ lines covered: 131/161 (81.37%) · Uncovered code |
|
Maybe related? #107434 -- or maybe more a follow-up |
I will take a look whan I have time. |
`KeyMatcherGeneric` asked `compareAt` with a `nan_direction_hint` of zero. That hint is what
`compareAt` answers with when exactly one side is a `NaN`, so it reported equality: a row holding a
`nan` key matched every requested key, and a requested `nan` matched every key. On master,
`m.key_1.5` over `Map(LowCardinality(Float64), String)` and `{nan: 'nan-hit', 1.5: 'one-five'}`
returns `nan-hit`, and `m.key_nan` over `{2.5: 'other'}` returns `other`.
The hint is now `1`, so only a `NaN` is equal to a `NaN`, and `KeyMatcherVector` goes through
`CompareHelper` to say the same thing. `CompareHelper` is a plain `==` for every type but the
floating point ones, so the integer, `UUID`, `IPv4`, `IPv6` and `Decimal` key families are
unchanged; `BFloat16`, `Float32` and `Float64` keys now agree with the generic matcher.
This is what the new `BFloat16` dispatch of the previous commit needed: it would otherwise have
taken the specialized path, where a raw `==` never finds a stored `nan`.
Co-Authored-By: Claude Opus 5 <[email protected]>
The direction hint `compareAt` was asked with also decides where a NULL goes, so the same zero hint
made a NULL element of a composite key equal to every other value: on master, `m.key_(5,1)` over
`Map(Tuple(Nullable(UInt8), UInt8), String)` and `{(NULL,1): 'null-hit', (5,1): 'five'}` returns
`null-hit`. A `Map` key cannot itself be `Nullable`, but a `Tuple` it is made of can.
Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120453&sha=55665cd2b1d2025bb8bb763e655457febfba7982&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. It is not this pull request: the only change here is
at 01:33:49 and then prints nothing more — in particular never One candidate worth checking first: in
|
|
Measured on that head. Two things, and the first one changes how to read the log. That job predates three hung-check fixes. Why the log stops where it does. In
Your candidate, as master stands. The probe is interval-gated at 10 s and, once a silent stretch has started, runs one attempt per call ( What I think actually loses these runs. I am opening a separate PR for that collision and for the unflushed verdict, and will link it here. Already open on the opaque row itself: #114029 (report why the stress script failed, not only its exit code) and #113428 (embed the head of |
|
Answering the ask directly: the mechanism is already fixed, by #120303, which you merged on 2026-09-19T09:12Z. That job ran on 2026-09-16T22:20Z and What actually happened. One premise in the ask does not hold, and neither did two claims in my earlier comment here. The parent did leave the pool loop, so the worker had exited, and it did reach On master that log now prints: the So I am not opening the separate PR I promised above, and promising it was premature. I have no failure on a tree carrying #120303 that any further change would have prevented. Of the 19 One thing the fix does not reach: release branches.
|
|
📊 Cloud Performance Report ✅ AI verdict: This PR speeds up Map key lookup for LowCardinality keys (and widens the specialized key/value dispatch to Decimal, wide integers, UUID/IP types) in DataTypeMapHelpers.cpp and arrayElement.cpp; it also fixes a NaN/NULL key-matching correctness bug. None of the three flagged ClickBench queries use Map subscript or arrayElement on LowCardinality columns — Q28 is a regexp aggregate, Q30/Q31 are ResolutionWidth arithmetic and grouping — so the changed code path is never hit. The Q30/Q31 deltas were correctly kept as not_sure inside master's current variance band, and CPU time is essentially unchanged across base and source, consistent with run-to-run noise rather than a real PR effect. Net: no plausible query-execution regression from this change; the new coverage is exercised only by the added performance test map_lowcardinality_key_lookup.xml. clickbenchFlagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120453&sha=529f321a1b01d44a3ba4c01b2bb8fbad189677f6&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.
The other red, |
|
Investigated. The defect is in master's fuzzer, not in this PR.
Fixing PR: #115786 (mine, open). Commit f76a05a adds that check at the three sites and stops a throwing mutation from discarding the query's remaining fuzz runs. Master still has the bare It has had no review since I opened it, and its head is from 2026-09-14. I can refresh it onto master and re-run CI, or split the three-site guard out into its own small PR so it lands sooner. Tell me which you prefer and I will do it. The |
|
🕵 @groeneai, thanks. Please split the three-site |
|
Will do. I am splitting the three-site |
|
The guard is split into its own PR off current master, as asked: #121747 |
|
Status update on the split I linked above: @ PedroTadim closed #121747 in favour of #121762, which is a test-side |
|
Update on the split above: #121747 is reopened, and its regression test is dropped on review request, so the three-site guard is landing there as the src change alone. |
…ST fuzzer
`{name:Identifier}` in a table position parses to an `ASTTableIdentifier` whose
`name_parts` are empty strings, carrying one `ASTQueryParameter` child per empty
part, so `ASTIdentifier::isParam` is true. `ASTTableIdentifier::getTableId`
builds a `StorageID` from those parts unconditionally, and `StorageID`'s
constructor runs `assertNotEmpty` and throws `UNKNOWN_TABLE, "Both table name
and UUID are empty"`.
`fuzzTableName`, `wrapTableAsDistributed` and `wrapTableAsMerge` checked only the
node type and then tested the result of that call for emptiness. Those emptiness
tests were dead code on this input: `getTableId` cannot return an empty
`StorageID`, and `StorageID::getTableName` asserts as well, so the read throws
before the test runs. The precondition has to be checked before the read, which
is what `callTableAsParameterizedView` in the same file already does.
The placeholder is produced by the fuzzer itself, in
`makeParameterizedIdentifier` (7cc8d90, ClickHouse#116689), and a successful fuzzed
AST is promoted to the next round's seed, so a later round reads it back as a
name. `fuzzMain` is called with no try/catch, so the exception escapes
`executeASTFuzzerQueries` and is logged by `tryLogCurrentException("ASTFuzzer")`
on the outer query's thread group; that streams it to the client's stderr and
`clickhouse-test` fails the test on non-empty stderr.
19 CIDB rows over 12 pull requests and 7 check flavours between 2026-09-04 and
2026-09-23, none on master. Per site: `fuzzTableName` 17 rows,
`wrapTableAsMerge` 2, `wrapTableAsDistributed` 0 (latent, identical ordering
behind a 1-in-40 gate).
The guard also stops the fuzzer silently de-parameterizing a reference whose
database part is a placeholder. `{pdb:Identifier}.src` is `isParam` but does not
throw, and `fuzzTableName` used to rewrite it to a plain name while the wrappers
substituted `currentDatabase()` for the parameter, producing a query that means
something different from the seed.
The regression test drives the same mutations from SQL through `fuzzQuery`, which
parses its argument and calls `fuzzMain` on it with no parameter substitution in
between. Its seed is chosen by measurement so that all three guarded helpers are
reached within 20 rows (`fuzzTableName` 30 entries, `wrapTableAsDistributed` 2,
`wrapTableAsMerge` 1, the last two behind a 1-in-40 gate each), and reverting any
one of the three guards on its own reds the test. The oracle matches the
parameter name rather than the whole `{name:Type}` text, because the fuzzer
rewrites a placeholder's declared type but never its name, and it requires every
row to keep the placeholder, because an unguarded wrapper rewrites the expression
part way through the sequence and each fuzzed AST becomes the next row's seed.
Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/35802239304/job/107027400109
Split out of ClickHouse#115786 as requested in
ClickHouse#120453 (comment)
Co-Authored-By: Claude Opus 5 <[email protected]>
Backport #120453 to 26.8: Speed up Map key lookup for LowCardinality keys
Backport #120453 to 26.9: Speed up Map key lookup for LowCardinality keys
…rdinality keys
…rdinality keys

Closes: #120340
Related: #111246
Extracting a value from a
MapwithLowCardinalitykeys compared the key values for every entry of a row until the key was found, so the cost grew with the position of the key in the row. The subcolumn path (findKeyPositionsDispatchinDataTypeMapHelpers.cpp, reached byoptimize_functions_to_subcolumns, which is on by default) has noLowCardinalityspecialization and falls back to the generic matcher, which goes through virtualcompareAtinto a dictionary lookup and a string comparison for every entry.FunctionArrayElementalready resolved the key to a dictionary position once and compared integers, so the non-default path was the fast one.This is what #111246 made visible. That change removed a cross-row position-prediction shortcut, correctly, because it could return a later duplicate key instead of the first one (#111203). The prediction had been hiding the cost of a comparison by making roughly one comparison per row; without it a wide map pays that cost per entry.
The fix is to make a comparison cheap rather than to make fewer of them. The requested key is resolved to its dictionary position once, and matching an entry becomes an integer comparison of dictionary positions. A key that is not in the dictionary cannot be in any row, so it is answered without looking at the rows at all. First-match semantics are untouched: every row is still scanned left to right and the first match is taken, so no prediction shortcut comes back and the regression test from #111246 is unchanged.
On the 20-key
Map(LowCardinality(String), String)from the issue, 20M rows, single thread, the cost of a lookup no longer depends on the position of the key:c3['k00'](1st of 20)c3['k09']c3['k17']c3['kb'](20th)These are from a debug build, so a release build will show smaller absolute numbers; the shape, flat rather than linear in the position of the key, is the point. The remaining time is reading and decompressing the column. This should be faster than the version before the regression rather than only restoring it, because the prediction path still paid one virtual
compareAtper row.While here, the same dispatch is extended to the type families that were also falling through to the generic per-row fallbacks:
UUID,IPv4,IPv6, the wide integers andBFloat16as keys and as values, theDecimal,DateTime64andTime64types as values, and the same as keys, which are reachable through the subcolumn name even thoughm[key]rejects them.While extending the dispatch, the generic matcher turned out to be asking
compareAtwith anan_direction_hintof zero. That hint is the answercompareAtgives when exactly one side is aNaN, or a NULL of aNullablenested in the key, so zero reported them as equal: a row holding such a key matched every requested key, and requesting such a key matched every key. On master:The hint is now
1, so only aNaNis equal to aNaNand only a NULL to a NULL, and the specialized matcher goes throughCompareHelperto say the same thing.CompareHelperis a plain==for every type but the floating point ones, so the integer,UUID,IPv4,IPv6andDecimalkey families keep the same comparison they had. This is also what the newBFloat16key dispatch needs: on the specialized path a raw==would never find a storednan, whichMap(BFloat16, ...)used to find.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up extracting a value from a
MapwithLowCardinalitykeys. The key is now resolved to its dictionary position once instead of being compared against every entry of a row, so the cost ofm[key]no longer grows with the position of the key in the row. Also fix extracting a value from aMapwhose key is aNaN, or holds a NULL inside a composite key: such a key used to compare equal to every other key.Workflow [PR]
Sync PR [sync-upstream/pr/120453]
Version info
26.10.1.662-master(included in26.10and later)26.9.3.37,26.8.11.52