Skip to content

Speed up Map key lookup for LowCardinality keys - #120453

Merged
fm4v merged 7 commits into
masterfrom
map-key-lookup-problem
Sep 25, 2026
Merged

fm4v merged 7 commits into
masterfrom
map-key-lookup-problem

Conversation

@Avogar

@Avogar Avogar commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Closes: #120340
Related: #111246

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, reached by optimize_functions_to_subcolumns, which is on by default) has no LowCardinality specialization and falls back to the generic matcher, which goes through virtual compareAt into a dictionary lookup and a string comparison for every entry. FunctionArrayElement already 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:

lookup before after
c3['k00'] (1st of 20) 6.23 s 5.51 s
c3['k09'] 12.77 s 5.60 s
c3['k17'] 18.85 s 5.72 s
c3['kb'] (20th) 20.36 s 5.79 s

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 compareAt per 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 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.

While extending the dispatch, the generic matcher turned out to be asking compareAt with a nan_direction_hint of zero. That hint is the answer compareAt gives when exactly one side is a NaN, or a NULL of a Nullable nested 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:

CREATE TABLE t (id UInt64, m Map(LowCardinality(Float64), String)) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, map(nan, 'nan-hit', 1.5, 'one-five')), (2, map(2.5, 'other'));
SELECT id, `m.key_1.5`, `m.key_nan` FROM t ORDER BY id;
-- 1  nan-hit  nan-hit      <- 1.5 finds the nan entry
-- 2  (empty)  other        <- nan finds the 2.5 entry

The hint is now 1, so only a NaN is equal to a NaN and only a NULL to a NULL, and the specialized matcher 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 keep the same comparison they had. This is also what the new BFloat16 key dispatch needs: on the specialized path a raw == would never find a stored nan, which Map(BFloat16, ...) used to find.

Changelog category (leave one):

  • Performance Improvement

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

Speed up extracting a value from a Map with LowCardinality keys. The key is now resolved to its dictionary position once instead of being compared against every entry of a row, so the cost of m[key] no longer grows with the position of the key in the row. Also fix extracting a value from a Map whose key is a NaN, 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

  • Merged into: 26.10.1.662-master (included in 26.10 and later)
  • Backported to: 26.9.3.37, 26.8.11.52

Avogar and others added 2 commits September 16, 2026 18:15
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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [529f321]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
05227_ast_fuzzer_no_profile_events_leak FAIL cidb IGNORED
Stress test (arm_debug) FAIL
Segmentation fault (STID: 1635-49b2) FAIL cidb IGNORED

AI Review

Summary

This PR resolves constant Map lookups on LowCardinality(String) and LowCardinality(FixedString) keys through dictionary positions instead of repeated value comparisons, extends the specialized extraction paths to several key and value types that previously fell back to the generic slow path, and fixes the compareAt(..., 0) bug that made NaN or nested NULL key components compare equal to unrelated keys. I reviewed the current diff, the full prior discussion, and the current arrayElement / DataTypeMapHelpers code paths against the new focused stateless tests and the now-green PR CI; I did not find an unresolved correctness issue or missing material evidence.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 529f321.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 131/161 (81.37%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 16, 2026
Comment thread src/DataTypes/DataTypeMapHelpers.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-map-datatype Map datatype implementation and semantics. label Sep 16, 2026
@Avogar

Avogar commented Sep 17, 2026

Copy link
Copy Markdown
Member Author
Screenshot 2026-09-17 at 14 58 59

@EmeraldShift

Copy link
Copy Markdown
Contributor

Maybe related? #107434 -- or maybe more a follow-up

@Avogar

Avogar commented Sep 17, 2026

Copy link
Copy Markdown
Member Author

Maybe related? #107434 -- or maybe more a follow-up

I will take a look whan I have time.

alexey-milovidov and others added 4 commits September 21, 2026 16:12
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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 Map key matching, and the job died in the stress harness after the test suite was already over.

stress.py runs the hung check as clickhouse-test --hung-check ... 00001_select_1 and gives it hung_check.wait(timeout=600). In hung_check.log that run reaches

[1 / 1] 00001_select_1: [ OK ] 0.49 sec.
1 tests passed. 0 tests skipped. 0.54 s elapsed (Process-3).

at 01:33:49 and then prints nothing more — in particular never Checking the hung queries: , which main prints right after do_run_tests returns. So clickhouse-test wedged between the worker finishing its only test and the parent leaving the pool loop, and 600 s later stress.py raised subprocess.TimeoutExpired, killed the group, and the surviving writer turned into Some hung check process survived the kill. The job is then reported only as the catch-all Test script failed, script exit code: 1.

One candidate worth checking first: in do_run_tests the while processes: loop calls hung_check_monitor.is_hung() before it reaps the finished workers, and a failing liveness probe spends its whole ~165 s retry budget inside that call, so an unresponsive server there stalls the loop instead of letting it exit. Also worth checking whether the worker had really exited, or was itself stuck in its post-test cleanup against a server that stopped answering.

Test script failed in Stress test (*) has fired 59 times in the last 21 days across every sanitizer and both architectures, always as this one opaque row, so whatever the mechanism is it is not specific to a pull request. The other red job, Build profile diff, is the known #120462 (No connection to LogCluster).

@groeneai

Copy link
Copy Markdown
Collaborator

Measured on that head. Two things, and the first one changes how to read the log.

That job predates three hung-check fixes. Stress test (arm_tsan) on 55665cd2 ran 2026-09-16 22:20:02Z to 23:47:33Z. None of these is an ancestor of it: #120303 (merged 09-19), #115403 (09-20), #114272 (09-20).

Why the log stops where it does. In do_run_tests the verdict is printed and then both stack collections run before anything flushes:

print("Hung check failed: server liveness check failed")
try_claim_stop_cause(...)
print_sql_stacktraces(args)   # HTTP aggregate over system.stack_trace
print_c_stacktraces(args)     # lldb over the server process

stress.py pipes that stdout into tee, so it is block-buffered, and at 600 s it does os.killpg(hung_check.pid, SIGKILL). A verdict printed at the start of a collection that outlasts the remaining budget dies in the buffer. The worker's 1 tests passed line survives because a worker flushes when it exits. So the missing Checking the hung queries: does not locate the wedge on this head: the parent's own account of it was destroyed with the buffer. #120303 added the flush at the sibling site only (the post-loop processlist failure); the in-loop verdict above is still unflushed in master today.

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 (max_retries=1 if self.unresponsive_since else 10), so only the first failed probe of a stretch spends the ~165 s ladder: one stall in the loop, not one per iteration. The reap-after-probe ordering you point at is still there, and #112393 (open since 07-29, not reviewed yet) removes the in-loop ladder entirely and adds a drain for a death after the last probe.

What I think actually loses these runs. HungCheckMonitor.GRACE_WITH_LIVE_PROCESS = 600.0 against stress.py's hung_check.wait(timeout=600). When the server stops answering but still holds its listening socket, the monitor deliberately waits up to 600 s for it to recover before calling it a hang. That grace can start no earlier than the process itself, so it expires at or after the SIGKILL, never before it: a stalled-but-alive server can only ever end as the kill plus Some hung check process survived the kill, never as a hang verdict. One budget that cannot fit inside the other, independent of the pull request under test, which fits 59 rows across every sanitizer.

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 hung_check.log rather than its tail).

@groeneai

Copy link
Copy Markdown
Collaborator

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 compare/ed879671cddf3...bc90ac7819ad10edf3f7c379b2af2d902b2cc407 is diverged, so it ran without the fix.

What actually happened. get_processlist_with_stacktraces passed timeout=120 and no max_http_retries, so it inherited clickhouse_execute's default of 5. http.client's timeout is per socket operation, the system.processes JOIN system.stack_trace aggregate with addressToLine/demangle never answered, and the call therefore cost 5 * 120 + (1 + 2 + 3 + 3) = 609s against hung_check.wait(timeout=600). The server log has exactly five arrivals of that query, at 01:35:19, 01:37:20, 01:39:22, 01:41:26 and 01:43:29, with gaps of 121.1/122.1/123.1/123.1s. The kill always landed inside attempt five. #120303 limits the collector to one attempt, so it now fails at 120s with the rest of the budget left to report in.

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 Checking the hung queries: . query_log holds exactly one SELECT 1 /*liveness check*/, at 01:33:49, finishing in 12ms, so the monitor never failed a probe and never blocked. The server was healthy throughout: about 20k log lines per minute until 01:44, and SYSTEM STOP DISTRIBUTED SENDS answered on the first try at 01:44:48, immediately after the kill. The line is missing only because that region printed 26 + 2497 * 2 = 5020 bytes with end="", which is below Python's 8192-byte block buffer on a pipe, and the SIGKILL took the buffer with it. So the silence was not the unflushed in-loop liveness verdict, and the GRACE_WITH_LIVE_PROCESS versus wait(timeout=600) collision, real though it is, is not what lost this run.

On master that log now prints: the sys.stdout.flush() #120303 added before the stack collections empties the same buffer, so the next occurrence carries Checking the hung queries: , its dots, the failure line and both dumps.

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 Test script failed artifacts still on S3, 11 are this mechanism (7 whose hung_check.log ends at the worker summary, 4 that end in dots because the buffer happened to overflow) and every one of them predates the merge; the 3 after it are a dead server refusing connections, twice, and one backport run whose base lacks the fix. The grace collision stays latent, and the arithmetic I sketched for it double-counted the elapsed silence, so it would have shortened the grace rather than fitted it. I would rather leave a deliberate recovery policy alone than change it with no failure behind it.

One thing the fix does not reach: release branches. 4939d20ffff2 (#121085) is diverged from it, so release-branch stress jobs still carry the 5-attempt collector. v*-must-backport on #120303 would close that, if you think it is worth it.

Build profile diff on that head is #120462, fixed by #121048.

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1104 1046 -5.3% <0.0001 cpu: Q28 (regexp on Referer, aggregate) is a −5.3% shift with mixed signals from the two tests and no history baseline; it does not touch Map/LowCardinality key lookup, so treat as noise, not a PR effect.
⚠️ 30 not_sure 224 272 +21.2% <0.0001 cpu: Q30/Q31 are the ResolutionWidth SUM-arithmetic and GROUP BY queries; neither uses Map key lookup or arrayElement on LowCardinality, so this +21.2% sits inside master's current variance band and is not attributable to this diff.
⚠️ 31 not_sure 265 320 +20.9% <0.0001 cpu: Same reasoning as Q30: no Map/LowCardinality path is exercised here, CPU time is essentially flat (base vs source), and the +20.9% stays within master's current-era band, so it is deterministically suppressed.

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
  • StressHouse run: 098cee71-3aca-4880-bcf3-cac9ad7dcbbd
  • MIRAI run: 89c0f243-6aed-4bf1-b2ff-dcaae2617a3b
  • PR check IDs:
    • clickbench_1404457_1790122700
    • clickbench_1404477_1790122701
    • clickbench_1404662_1790122721
    • tpch_adapted_1_official_1404777_1790122779
    • tpch_adapted_1_official_1404950_1790122842
    • tpch_adapted_1_official_1405052_1790122851

@alexey-milovidov alexey-milovidov added pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed v26.6-must-backport v26.7-must-backport v26.8-must-backport labels Sep 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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.

05227_ast_fuzzer_no_profile_events_leak fails with having stderror: the server-side ASTFuzzer logs <Error> ... Both table name and UUID are empty. (UNKNOWN_TABLE) from QueryFuzzer::fuzzTableName -> ASTTableIdentifier::getTableId. It is failing across the fleet: 14 failures in the last 3 days, on PRs 121248, 120973, 120906, 109696, 119229, 106823, 121629, 121520, 120659 and this one. This PR does not touch the fuzzer.

The other red, Stress test (arm_debug) Segmentation fault (STID: 1635-49b2) in StorageDistributed::getOptimizedQueryProcessingStageAnalyzer (reached from a scalar subquery via InterpreterCreateQuery), is the crash that #121418 fixes. That PR is still open. This PR only changes the Map key lookup.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. The defect is in master's fuzzer, not in this PR.

QueryFuzzer::fuzzTableName reads the name through getTableId() and only then tests it for emptiness, and one branch earlier in the same function it rewrites the name to {fuzz_param_N:Identifier} (1 in 200), whose ASTTableIdentifier has empty name parts. The next mutation of that AST hits the ordering and throws UNKNOWN_TABLE. wrapTableAsDistributed and wrapTableAsMerge are written the same way; callTableAsParameterizedView is the in-file sibling that already checks isParam().

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 if (!identifier) guard, so every carrier reds. So there is no new PR from me for this one.

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 arm_debug Stress test segfault is mine as well: #121418, open.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, thanks. Please split the three-site isParam guard in QueryFuzzer::fuzzTableName / wrapTableAsDistributed / wrapTableAsMerge out into its own small PR off current master, so the fleet-wide 05227_ast_fuzzer_no_profile_events_leak red can land independently of #115786's larger change. Link it here when it is open. This PR will pick up both that fix and #121418 by merging master once they land.

@groeneai

Copy link
Copy Markdown
Collaborator

Will do. I am splitting the three-site isParam guard (fuzzTableName, wrapTableAsDistributed, wrapTableAsMerge) out into its own PR off current master, and I will link it here when it is open. #115786 keeps the remainder.

@groeneai

Copy link
Copy Markdown
Collaborator

The guard is split into its own PR off current master, as asked: #121747

@groeneai

Copy link
Copy Markdown
Collaborator

Status update on the split I linked above: @ PedroTadim closed #121747 in favour of #121762, which is a test-side send_logs_level = 'fatal' on 05227, so the three-site getTableId guard is currently not landing anywhere. I asked him there whether he still wants it as its own PR: #121747 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator

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.

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 24, 2026
…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]>
@fm4v
fm4v added this pull request to the merge queue Sep 25, 2026
Merged via the queue into master with commit 0334846 Sep 25, 2026
174 of 177 checks passed
@fm4v
fm4v deleted the map-key-lookup-problem branch September 25, 2026 11:27
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 25, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 25, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #120453 to 26.8: Speed up Map key lookup for LowCardinality keys
fm4v added a commit that referenced this pull request Sep 26, 2026
Backport #120453 to 26.9: Speed up Map key lookup for LowCardinality keys
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
zvonand pushed a commit to zvonand/ClickHouse that referenced this pull request Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-map-datatype Map datatype implementation and semantics. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

7 participants