Skip to content

Fix map[key] returning a later duplicate key instead of the first - #111246

Merged
Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-111203-map-duplicate-key-first-match
Aug 12, 2026
Merged

Avogar merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-111203-map-duplicate-key-first-match

Conversation

@groeneai

@groeneai groeneai commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

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 map[key] returning the value of a later duplicate key instead of the first one. When a Map column contained duplicate keys, the result of map[key] could depend on preceding rows in the same block and on the optimize_functions_to_subcolumns setting, so a SELECT and a WHERE over the same row could disagree.

Description

m[key] must return the value of the FIRST occurrence of the key in a row. Two key-lookup loops used a cross-row position-prediction shortcut: if the previous row's first match was at relative offset K, offset K was tried first in the current row and accepted if it matched, without checking for an earlier occurrence. With duplicate keys the prediction could land on a later duplicate, and because the predicted offset depended on preceding rows, the result was block- and setting-dependent (see the count() mismatch in the issue).

Fix: drop the prediction and scan each row left to right, taking the first match. The prediction only saved work when the match was at a non-first position, which is exactly the unsafe case; when the match is at position 0 the scan finds it in one comparison, so no correctness-preserving shortcut is faster than the scan.

Both affected paths are fixed so the setting stays semantics-preserving:

  • findKeyPositions in DataTypeMapHelpers.cpp (the optimize_functions_to_subcolumns subcolumn path).
  • executeMatchKeyToIndex in arrayElement.cpp (the arrayElement/m[key] path).

New stateless test 04546_map_element_duplicate_keys_first_match asserts the first-match value is returned with the setting on and off, with and without a filter, and across value types (String, Nullable, LowCardinality, LowCardinality(Nullable), UInt64, Array) and key types (String, LowCardinality(String), UInt64), on both wide and compact parts.

Closes #111203

m[key] must return the value of the first occurrence of the key in a row.
Two key-lookup loops used a cross-row position-prediction shortcut: if the
previous row's first match was at relative offset K, offset K was tried first
in the current row and accepted if it matched, without ruling out an earlier
occurrence. With duplicate keys the prediction could land on a later
duplicate, and because the predicted offset depended on preceding rows in the
same block, the result was block- and setting-dependent (a SELECT and a WHERE
over the same row could disagree, and optimize_functions_to_subcolumns=0 vs 1
could return different values).

Drop the prediction and scan each row left to right, taking the first match.
The prediction only saved work when the match was at a non-first position,
which is exactly the unsafe case; a position-0 match is found by the scan in
one comparison, so no correctness-preserving shortcut is faster than the scan.

Both paths are fixed so optimize_functions_to_subcolumns stays
semantics-preserving: findKeyPositions (the subcolumn path) and
executeMatchKeyToIndex (the arrayElement path).

Closes: ClickHouse#111203

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent second model reviewed this diff before the PR was opened.

Findings: 0 (no blockers, majors, or nits).

  • ❌ Blockers: none
  • ⚠️ Majors: none
  • 💡 Nits: none

The reviewer had no objections to the approach (drop the cross-row position-prediction shortcut; forward-scan first-match in both findKeyPositions and executeMatchKeyToIndex) or the diff.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT m[''] FROM t WHERE id=2 SETTINGS optimize_functions_to_subcolumns=1 returns SECOND every time on the pre-fix binary; =0 returns FIRST. Table primes the key at relative position 1 in row 1, duplicate '' at positions 0 and 1 in row 2.
b Root cause explained? Two key-lookup loops used a cross-row position-prediction shortcut: they tried the previous row's match offset first and accepted it without ruling out an earlier occurrence. With duplicate keys the prediction lands on a later duplicate, so the result depends on preceding rows in the block and on the setting.
c Fix matches root cause? Yes. Removes the prediction; each row is forward-scanned and the first match taken. Not a band-aid (no widened bound, tag, or reduced data).
d Test intent preserved / new tests added? New test 04546_map_element_duplicate_keys_first_match added; no existing test weakened or removed.
e Both directions shown? Yes. Test output differs from .reference in 14 lines on the pre-fix binary (all subcolumns=1 -> SECOND, count(first)=0); identical to .reference on the fixed binary.
f General, not a narrow patch? Yes. grep confirms the prediction pattern exists in exactly two copies (findKeyPositions, executeMatchKeyToIndex); both fixed. The const-map path (executeMatchConstKeyToIndex) is already a clean first-match scan. Fixing only the subcolumn path would leave the arrayElement path (and the unfiltered case) wrong.
g Generalizes across inputs/wrappers? Yes. Test matrix covers value types String, Nullable(String), LowCardinality(String), LowCardinality(Nullable(String)), UInt64, Array(String); key types String, LowCardinality(String), UInt64; wide and compact parts; filter and no-filter; setting on and off. All return first-match.
h Backward compatible? Yes. Bug fix making results correct (first occurrence) regardless of setting. No setting default change, no on-disk/wire format change.
i Invariants/contracts preserved? Yes. Matched-index encoding unchanged (position+1, 0 = not found; KEY_NOT_FOUND sentinel unchanged). offsets[ssize_t(i)-1] for i=0 is offsets[-1] == 0 by the ColumnArray::Offsets left-pad convention (same idiom the original row-0 branch used). Value-extraction phase unchanged; empty-map and zero-row cases behave as before.

Session id: cron:clickhouse-author-slot-3:20260721-140500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antonio2368 @Ergus - could you review this? It fixes m[key] returning a later duplicate key's value instead of the first: two key-lookup loops (findKeyPositions for the optimize_functions_to_subcolumns subcolumn path, executeMatchKeyToIndex for the arrayElement path) used a cross-row position-prediction shortcut that could accept a later duplicate at the predicted offset, making the result block- and setting-dependent. Both now forward-scan and take the first match.

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cdf7228]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
01661_extract_all_groups_throw_fast FAIL cidb IGNORED
Stress test (arm_release) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR removes the cross-row match-position prediction from both Map lookup implementations that could return a later duplicate key instead of the first one. I traced the regular arrayElement path, the optimize_functions_to_subcolumns key-subcolumn path, and the unchanged sibling const-map/const-key paths, and I did not find a remaining correctness gap or a missing contract on the touched surfaces.

Final Verdict

✅ No blockers or majors found.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 21, 2026
@Avogar Avogar self-assigned this Jul 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.00% -0.10%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 18/18 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cdf7228

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 01661_extract_all_groups_throw_fast trunk flake under host memory pressure, not caused by this PR: Code: 241 where 128 was expected, 36 hits across 35 unrelated PRs in the 30 days before this run, and the in-job rerun passed 21/21 with the same randomized settings. #111513 (ours, merged 2026-07-24). Not yet on this branch, so this build predates the fix; a master merge will pick it up. Since that merge the test has 0 failures anywhere in CIDB.
Stress test (arm_release) / Hung check failed, possible deadlock found chronic trunk hung-check class, not caused by this PR: 454 hits across 294 PRs including 90 master runs in 30 days. The busy thread here is throwing out of QueryAnalyzer::resolveArrayJoin under the AST fuzzer, which is a different sub-signature from the one merged #111909 addressed. a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

This PR touches only DataTypeMapHelpers.cpp, arrayElement.cpp and its own new test
04546_map_element_duplicate_keys_first_match, so it cannot cause either failure. The other 155
completed check-runs are green and 18 are skipped by configuration; Config Workflow and
Finish Workflow both succeeded.

Session id: cron:our-pr-ci-monitor:20260801-190047

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Correction + fixing-PR link for the Stress test (arm_release) hung check

My earlier ledger line on this commit attributed the hung check to a QueryAnalyzer::resolveArrayJoin
throw. That was wrong, and I want to correct it rather than leave it standing. I had read the stack out
of the CIDB test_context_raw, which keeps only the trailing 32 KiB of the report; the stacktraces
field sits earlier than that cut, so the frames I quoted were not the hung thread's.

Reading the actual hung_check.log artifact, the busy thread (6116) is in the MergeTree part writer,
and two independent samples taken minutes apart by different mechanisms agree:

  • system.stack_trace: escapeForFileName <- getNameForSubstreamPath <- getFileNameForStream
    <- MergeTreeDataPartWriterWide::getStreamName <- writeSingleGranule's callback
    <- SerializationString/Variant/Dynamic/Object::enumerateStreams <- writeColumn
    <- MergeTreeDataWriter::writeTempPart <- MergeTreeSink::consume
  • lldb (thread #596 'QueryCompPipeEx'): sipHash128Keyed <- replaceFileNameToHashIfNeeded
    <- getStreamName <- the same callback and chain

Different frames, same call path, two mechanisms, so the thread was running rather than parked. The
query is insert into test select ... toJSONString(map(...)) ... from numbers(4) mutated by the
server-side AST fuzzer, with elapsed: 1365.7, is_cancelled: 1 and max_execution_time: 60 -
i.e. cancellation was requested and could not take effect, because writeColumn has no cancellation
point and MergeTreeSink::consume only enforces query limits between blocks.

Owner for this line: #108357 ("Make column data write during INSERT respond to query
cancellation"), which adds a per-granule cancellation check to
MergeTreeDataPartWriterWide::writeColumn and MergeTreeDataPartWriterCompact::writeDataBlock via a
shared MergeTreeDataPartWriterOnDisk::checkWriteCancellation. That is this exact code path, so the
line is now owned by a fixing PR rather than by an internal fix task.

One caveat I should state rather than imply: that PR is still open, and this commit predates it, so
this occurrence carries no information about whether the fix holds.

@Avogar
Avogar added this pull request to the merge queue Aug 12, 2026
Merged via the queue into ClickHouse:master with commit b450d17 Aug 12, 2026
176 of 179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants