Repository navigation
Validate hex digits in parseUUID (issue #86714) - #104370
alexey-milovidov merged 2 commits into
Conversation
Closes ClickHouse#86714. Before this change, `parseUUID` did not validate that the input characters were valid hexadecimal digits. The lookup table mapped invalid characters to `0xff`, and `unhex2` then folded that back into `UInt8` arithmetic that wrapped around silently (for example `unhex2('s', 't')` = `0xff*16 + 0xff = 4335`, which truncates to `0xef` in `UInt8`). As a result `toUUID*` and any other caller of `parseUUID` happily accepted arbitrary 32- or 36-character garbage strings and fabricated a UUID from them. ``` WITH 'teststr-665785014160310158e823a3' AS str SELECT toUUID(str), toUUIDOrNull(str), toUUIDOrZero(str); -- Old behaviour: feefefef-6657-8501-4160-310158e823a3 for all three -- New behaviour: throws CANNOT_PARSE_UUID; OrNull -> NULL; OrZero -> 00...0 ``` The fix adds an explicit pre-validation pass in `parseUUID`: * For 36-character inputs: dashes must be at positions 8, 13, 18, 23 and every other byte must be a hex digit `0-9 / a-f / A-F`. * For 32-character inputs: every byte must be a hex digit. * Any other length still throws as before. A new `tryParseUUID(span, UUID&)` returning `bool` is introduced for callers on the no-throw path; `readUUIDTextImpl<bool>` (used by `tryReadUUIDText` and therefore by `toUUIDOrNull/OrZero/OrDefault`, `CAST AS Nullable(UUID)`, `accurateCastOrNull`, JSONExtract, MsgPack input, ...) routes through it so that invalid inputs surface as a clean `false` instead of an exception leaking through. Existing tests: all UUID-related stateless tests continue to pass (`01528_to_uuid_or_null_or_zero`, `04137_conversion_functions_edges`, the rest of the `*uuid*` family). New regression test: `04211_uuid_parser_strict_validation_86714.sql` covers the exact reproducer from the issue, all four `toUUID*` variants, multiple invalid-input shapes (full-garbage 32-char, 36-char with right dashes but non-hex elsewhere, misplaced dashes, single bad digit at start / end), valid 36-char / 32-char / mixed-case inputs, round-trip identity, and `CAST` / `accurateCastOrNull`.
|
Pre-PR validation gate (per worker policy): (a) Deterministic repro? ✓ (b) Root cause? ✓ (c) Fix matches root cause? ✓ Pre-validation in (d) Test intent preserved + new tests added? ✓ 17 existing UUID stateless tests pass unchanged. New test (e) Demonstrated in both directions? ✓ Confirmed locally on debug build that the same query fails before fix, passes after fix. (f) Fix is general? ✓ Single fix at the parser layer covers every caller of Session: cron:clickhouse-ci-task-worker:20260508-114500 |
|
cc @den-crane @KochetovNicolai @Avogar @rschu1ze — fix for #86714 per @den-crane's directive ("@groeneai try to fix it."). The parser-level change makes @KochetovNicolai you're listed as the assignee on the issue. |
|
Try testing how much performance is impacted by the new implementation using this query: |
|
@den-crane — perf benchmarks below. TL;DR: your exact query is constant-folded so it shows ~no per-row parser cost; on per-row variants the new validation costs about −16% on valid UUIDs and is +120% on invalid input (early-bail). Setup
Q1 — your exact query (constant-folded)SELECT count() FROM numbers(1e8)
WHERE ignore(toUUIDOrNull('teststr-665785014160310158e823a3'))=0
SETTINGS max_threads=1 FORMAT Null;
Δ ≈ −1.2%, well within run-to-run noise (±5%). The constant-folder eliminates the parser from the hot loop, so this query measures Q2 — invalid input forced per-row via
|
| master | PR #104370 | |
|---|---|---|
| avg throughput | 42.79 M rows/s | 94.92 M rows/s |
| duration | 2335 ms | 1043 ms |
+121.8% (2.22× faster). The new code bails at byte 0 in areHexChars ('t' isn't hex), where the old code always ran the full parseHex<8>×2 to fabricate the garbage UUID.
Q3 — valid 36-char UUID forced per-row
WHERE ignore(toUUIDOrNull(materialize('a1b2c3d4-e5f6-1234-9876-abcdef012345')))=0| master | PR #104370 | |
|---|---|---|
| avg throughput | 40.13 M rows/s | 33.51 M rows/s |
| duration | 2493 ms | 3003 ms (+20%) |
−16.5% — the new code does an extra full pass over the 32 hex bytes (plus 4 dash-position checks) before parseHex runs.
Q4 — valid 32-char no-dash UUID forced per-row
WHERE ignore(toUUIDOrNull(materialize('a1b2c3d4e5f612349876abcdef012345')))=0| master | PR #104370 | |
|---|---|---|
| avg throughput | 42.69 M rows/s | 36.00 M rows/s |
| duration | 2394 ms | 2775 ms (+16%) |
−15.7% — same areHexChars(32) overhead.
Peak memory
Identical across both states for every query (deltas in the 0.04% range — just measurement noise). The patch is stack-only; no new allocations.
Bottom line
The cost of correctness is one extra 32-byte hex-validation pass (areHexChars) before the (now bug-free) parseHex runs. In absolute terms the strict parser still runs at ~33–36 M valid UUIDs/sec single-threaded — fast enough for any realistic workload. Invalid inputs are faster under the new code thanks to the early-bail.
If 16% on the valid hot path matters for any workload, two cheap follow-ups:
- SIMD
areHexChars— the loop is naturally vectorizable (SSE2pcmpgtb/ AVX2 lookup); could reclaim most of the overhead at the cost of ~30 lines. - Fuse validation into
parseHex— checkunhex2results for0xffinstead of the separate up-front pass; would halve the byte-scan cost.
Happy to follow up on either if you'd like — otherwise the current code is, I think, a reasonable correctness/perf tradeoff.
|
Workflow [PR], commit [8ec6f70] Summary: ✅ AI ReviewSummaryThis PR fixes a real UUID parsing correctness bug: non-hex characters in 32/36-char inputs were previously accepted and silently converted into fabricated UUID bytes. The new validation in ClickHouse Rules
Final Verdict
|
The test `03773_deterministic_functions_key_condition[_explain]` contains a UUID literal `'017adbc0-98b5-0000-3f74-619a368fe65g'` whose trailing `g` is not a valid hex digit. The previous garbage-tolerant `parseUUID` silently fabricated a UUID from this input, allowing the `INSERT` to succeed; the strict parser added by this PR correctly rejects it, breaking the test. The test queries only filter on `person_id` (which is a valid UUID), never on the `uuid` column. The author of the test almost certainly intended a distinct hex digit (the first row's uuid ends in `65d`, the second row's person_id ends in `65a`) so the second row would have a different `uuid` value. Replace the invalid `g` with `b` so the second row's uuid is `'017adbc0-98b5-0000-3f74-619a368fe65b'` — distinct from `65d`, distinct from `65a`, and a valid hex digit. `count()` results stay at 2 rows in all queries that use the `events` table. Update both `.sql.j2` templates and the matching `.reference` files (echo mode) for the data and explain variants. Verified locally with the strict parseUUID build: 60/60 passes across both tests with `--test-runs 30` and default randomization.
|
Fix-up commit pushed: What brokeAfter my parseUUID validation patch, the existing 03773 test started failing on Fast test: This is exactly the bug we are fixing: the old FixThe INSERT INTO events (uuid, person_id, event, timestamp, team_id)
VALUES (
- '017adbc0-98b5-0000-3f74-619a368fe65g',
+ '017adbc0-98b5-0000-3f74-619a368fe65b',
'017adbc0-98b5-0000-3f74-619a368fe65a',Updated all four files (echo-mode test): both Verification
This is the only test in the suite affected — no other test inputs malformed UUID strings. Session: cron:clickhouse-ci-task-worker:20260509-104500 |
LLVM Coverage Report
Changed lines: 87.50% (35/40) | lost baseline coverage: 2 line(s) · Uncovered code |
|
Hi — could this be a backport candidate for Affected code: Why this might apply: The Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider |
…ease notes The 26.6 Cloud release notes were missing several backward incompatible changes that ship in that version: * UUID parsing now rejects same-length non-hexadecimal strings (ClickHouse#104370). * The obsolete Arrow-based Parquet reader and writer were removed (ClickHouse#100949). * `RANK` and `DENSE_RANK` reject arguments (ClickHouse#104324). * `Dynamic`/`Variant` types are validated in window `PARTITION BY` (ClickHouse#105450).
Closes #86714.
Problem
parseUUIDdid not validate that the input characters were valid hexadecimal digits. The lookup table mapped invalid characters to0xff, andunhex2then folded that back intoUInt8arithmetic that wrapped around silently (for exampleunhex2('s', 't')=0xff*16 + 0xff = 4335, which truncates to0xef). As a resulttoUUID*,CAST(... AS UUID), and any other caller ofparseUUIDhappily accepted arbitrary 32- or 36-character garbage strings and fabricated a UUID from them.Fix
parseUUIDnow performs an explicit pre-validation pass:0-9 / a-f / A-F.A new
tryParseUUID(span, UUID&)returningboolis introduced for the no-throw path.readUUIDTextImpl<bool>(used bytryReadUUIDText, and therefore bytoUUIDOrNull / OrZero / OrDefault,CAST AS Nullable(UUID),accurateCastOrNull, JSONExtract on UUID, MsgPack input, ...) routes through it so invalid inputs surface as a cleanfalseinstead of an exception leaking through the try-path.The fix lives at the parser layer, so all callers benefit at once:
toUUID*,CAST,SerializationUUID::deserializeTextQuoted(fast path),AvroRowInputFormat,JSONExtractTree,MsgPackRowInputFormat,ZooKeeperReplicator.Tests
01528_to_uuid_or_null_or_zero,04137_conversion_functions_edges,00396_uuid,00472_compare_uuid_with_constant_string,00679_uuid_in_key,01032_cityHash64_for_UUID,01338_uuid_without_separator,01413_if_array_uuid,01453_normalize_query_alias_uuid,01554_bloom_filter_index_big_integer_uuid,02491_part_log_has_table_uuid,01746_convert_type_with_default,01533_distinct_nullable_uuid,03595_funcs_on_zero,03593_funcs_on_empty_string,03212_variant_dynamic_cast_or_default,00396_uuid_v7).04211_uuid_parser_strict_validation_86714.sqlcovers the exact reproducer from the issue, all fourtoUUID*variants, multiple invalid-input shapes (full-garbage 32-char, 36-char with right dashes but non-hex elsewhere, misplaced dashes, single bad digit at start / end), valid 36-char / 32-char / mixed-case inputs, round-trip identity,CAST AS UUID,CAST AS Nullable(UUID), andaccurateCastOrNull. 30/30 passes with random settings enabled.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
toUUID,toUUIDOrNull,toUUIDOrZero,toUUIDOrDefault,CASTtoUUIDandNullable(UUID),accurateCastOrNulltoUUID, and the input formats that parse a UUID from text (Avro,MsgPack,JSONExtract, ...) now reject strings that have the right length but contain non-hexadecimal characters. Previously such inputs were silently turned into a fabricated UUID by walking off the end of the hex digit lookup table; nowtoUUIDthrowsCANNOT_PARSE_UUID, and theOr*variants returnNULL/ the zero UUID / the supplied default.Documentation entry for user-facing changes