Skip to content

Read LowCardinality dictionary keys in batches instead of allocating for the key count read from the stream - #128366

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:lc-dictionary-keys-batched-read
Oct 31, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:lc-dictionary-keys-batched-read

Conversation

@groeneai

@groeneai groeneai commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117385

Changelog category (leave one):

  • Improvement

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

Reading a malformed LowCardinality column (for example from Native input) whose dictionary declares more keys than the data contains now fails with CANNOT_READ_ALL_DATA instead of a LOGICAL_ERROR or an attempt to allocate terabytes of memory.

Description

Found by serialization_lowcardinality_fuzzer in the master NightlyFuzzers libFuzzer tests job: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=9f79cc172306dbf177534ef194cafc034a598a33&name_0=NightlyFuzzers&name_1=libFuzzer%20tests

SerializationLowCardinality reads the dictionary size from the stream and passes it as limit to the keys' deserializeBinaryBulk, which reserves (String) or resizes (numbers, UUID, IPv4, IPv6) the column for limit before reading anything. A 51-byte Native block is enough:

SELECT * FROM format(Native, 'x LowCardinality(String)', unhex('01010178164c6f7743617264696e616c69747928537472696e672901000000000000000002000000000000000000000000001d'))

On 26.3 and 26.8 this throws LOGICAL_ERROR (Too large size passed to allocator; debug and sanitizer builds abort), and with a key count of 2^40 it asks for a 16 TiB allocation.

The three places that read a dictionary (the single-dictionary prefix read, the shared dictionary, the additional keys) now share one helper that reads keys in batches of at most DEFAULT_BLOCK_SIZE and throws CANNOT_READ_ALL_DATA when the stream ends before the declared count. The nullable null map is sized by the keys actually read. A dictionary of up to 65409 keys is still read by one call with the same arguments, so valid data is read exactly as before.

The new test covers String and Nullable(UInt64) keys and a 200000-key block that spans several batches. Locally, the whole LowCardinality test family also passes with the batch size set to 3.


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

Version info

  • Merged into: 26.11.1.978-master (included in 26.11 and later)

groeneai and others added 2 commits October 31, 2026 11:17
`SerializationLowCardinality` read the dictionary size from the stream and
passed it as `limit` to the keys' `deserializeBinaryBulk`, which reserves
(`String`) or resizes (numbers, `UUID`, `IPv4`, `IPv6`) the column for `limit`
before reading. A malformed block with a huge key count (a 51-byte `Native`
input, or the serialization_lowcardinality_fuzzer crash input) made the
allocator throw `LOGICAL_ERROR` ("Too large size passed to allocator"), and a
count of 2^40 requested 16 TiB.

The single-dictionary prefix read, the shared dictionary read and the
additional keys read now use one helper that reads keys in batches of at most
`DEFAULT_BLOCK_SIZE` and throws `CANNOT_READ_ALL_DATA` when the stream ends
before the declared count. The check also ends the loop at end of stream,
and the nullable null map is sized by the keys actually read. A dictionary of
up to 65409 keys is read by one call with the same arguments as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the deserializeDictionaryKeys comment to one line.

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

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

Pre-publication review by an independent model (engine: codex; 0 findings) plus a separate cold review (0 blockers, 0 majors).

# Sev Finding Verdict Evidence / action
1 💡 The SQL test reaches only the additional-keys read; the single-dictionary prefix read and the shared-dictionary read are MergeTree-only Noted, not blocking Native rejects a global dictionary, so those two sites need a fabricated part. Checked locally instead: the CI fuzzer input replayed through the fuzzer harness calls (base aborts at the CI frame, fix gives CANNOT_READ_ALL_DATA), and the whole LowCardinality test family with a batch size of 3.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261031-111900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The format(Native, ...) query in the description aborts a debug build of the base every time (Allocator.cpp:126 via SerializationString.cpp:491). The 62-byte CI fuzzer input, replayed through the harness calls, aborts at the CI frame SerializationLowCardinality.cpp:366.
b Root cause explained? The dictionary size is read from the stream and passed as limit to the keys' bulk reader, which reserves or resizes the column for limit before reading.
c Fix matches root cause? Yes. The count no longer sizes any allocation: keys are read in batches of at most DEFAULT_BLOCK_SIZE, at the place the untrusted value is read. No allocator guard and no fixed size bound.
d Test intent preserved / new tests added? New stateless test: 3 malformed blocks (String with a huge and a 2^40 count, Nullable(UInt64)) and one valid 200000-key block. With the batch loop replaced by one capped call, the valid block fails 50/50. With the end-of-stream check removed, the malformed blocks never return.
e Both directions demonstrated? Base: the server dies on the first query (LOGICAL_ERROR), and the 2^40 block gives MEMORY_LIMIT_EXCEEDED. Fix: CANNOT_READ_ALL_DATA for all three; 50/50 randomized runs pass.
f Fix is general across code paths? All three dictionary reads (single-dictionary prefix, shared dictionary, additional keys) use one helper. FixedString already reads in bounded steps.
g Fix generalizes across inputs (params/datatypes/wrappers)? Native round trips of 100000-key dictionaries for 16 key types (string, fixed string, integers up to 256 bit, floats, dates, UUID, IPv4, IPv6, Nullable, Bool) match the base. So do MergeTree Wide (single dictionary), Compact and multi-dictionary parts. The whole LowCardinality test family passes with a batch size of 3.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default changes, and valid data is read identically. Malformed input gets error code 33 instead of 49 or 241.
i Invariants and contracts preserved? A dictionary that declares N keys yields exactly N keys or throws. The batches consume exactly the bytes that one call would. The null map has one entry per key read. The EOF and seek logic of the prefix read is unchanged.

Session id: cron:clickhouse-impl-slot-7:20261031-103800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @KochetovNicolai, could you review this and add the can be tested label so CI runs? SerializationLowCardinality passed the dictionary key count read from the stream straight to the keys' deserializeBinaryBulk as the reserve size, so a malformed Native block hit the allocator's LOGICAL_ERROR; the keys are now read in DEFAULT_BLOCK_SIZE batches, with CANNOT_READ_ALL_DATA on a short stream.

@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a20ff86]

Summary: ✅


AI Review

Summary

The PR reads LowCardinality dictionary keys in bounded batches across all three dictionary-loading paths, preventing allocations based on an untrusted key count and reporting truncated dictionaries with CANNOT_READ_ALL_DATA. No actionable findings at commit a20ff86d57eb82c5f23d3298dd023c03aca69670.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). labels Oct 31, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a20ff86d5 with master 94d1a63f2 (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.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

All good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 31, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 31, 2026
Merged via the queue into ClickHouse:master with commit 47f313c Oct 31, 2026
529 of 531 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 31, 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 comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants