Skip to content

Validate hex digits in parseUUID (issue #86714) - #104370

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-touuid-strict-hex-validation
May 9, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-touuid-strict-hex-validation

Conversation

@groeneai

@groeneai groeneai commented May 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #86714.

Problem

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). As a result toUUID*, CAST(... AS UUID), 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 -> 00000000-0000-0000-0000-000000000000

Fix

parseUUID now performs an explicit pre-validation pass:

  • 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.
  • Other lengths still throw with the same error as before.

A new tryParseUUID(span, UUID&) returning bool is introduced for the no-throw path. readUUIDTextImpl<bool> (used by tryReadUUIDText, and therefore by toUUIDOrNull / OrZero / OrDefault, CAST AS Nullable(UUID), accurateCastOrNull, JSONExtract on UUID, MsgPack input, ...) routes through it so invalid inputs surface as a clean false instead 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

  • All 17 UUID-related stateless tests still pass (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).
  • 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, CAST AS UUID, CAST AS Nullable(UUID), and accurateCastOrNull. 30/30 passes with random settings enabled.

Changelog category (leave one):

  • Backward Incompatible Change

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

toUUID, toUUIDOrNull, toUUIDOrZero, toUUIDOrDefault, CAST to UUID and Nullable(UUID), accurateCastOrNull to UUID, 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; now toUUID throws CANNOT_PARSE_UUID, and the Or* variants return NULL / the zero UUID / the supplied default.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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`.
@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per worker policy):

(a) Deterministic repro? ✓ SELECT toUUID('teststr-665785014160310158e823a3') reproduces 100% on demand. Before fix: returns feefefef-6657-8501-4160-310158e823a3. After fix: throws CANNOT_PARSE_UUID.

(b) Root cause? ✓ parseUUID called parseHex<N> which used unhex2 without validating digits. The hex_char_to_digit_table maps invalid chars to 0xff; multiplying that by 0x10 overflows a UInt8 so e.g. unhex2('s', 't') = 0xff*16 + 0xff = 4335 → 0xef (truncated). parseHex<8> happily wrote 8 bytes of garbage into the UUID.

(c) Fix matches root cause? ✓ Pre-validation in parseUUID / tryParseUUID: length check (32 or 36) + dash positions for 36-char + every non-dash byte must be a valid hex digit. Validation happens before any parsing.

(d) Test intent preserved + new tests added? ✓ 17 existing UUID stateless tests pass unchanged. New test 04211_uuid_parser_strict_validation_86714.sql covers the reproducer, all four toUUID* variants, multiple invalid shapes, round-trips, and CAST / accurateCastOrNull. 30/30 runs pass with random settings.

(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 parseUUID / tryParseUUID: toUUID*, CAST AS UUID, CAST AS Nullable(UUID), accurateCastOrNull, SerializationUUID::deserializeTextQuoted (fast path), AvroRowInputFormat, JSONExtractTree, MsgPackRowInputFormat, ZooKeeperReplicator. No symmetric variants left unfixed.

Session: cron:clickhouse-ci-task-worker:20260508-114500

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @den-crane @KochetovNicolai @Avogar @rschu1ze — fix for #86714 per @den-crane's directive ("@groeneai try to fix it.").

The parser-level change makes parseUUID validate hex digits + dash positions before parsing, and adds tryParseUUID so the no-throw path stays exception-free. Could one of you take a look?

@KochetovNicolai you're listed as the assignee on the issue.
@Avogar / @rschu1ze tagging by component (comp-data-types / comp-regular-function — UUID parsing sits between the two).

@den-crane

Copy link
Copy Markdown
Contributor

Try testing how much performance is impacted by the new implementation using this query:

SELECT count() 
from numbers(1e8) 
where ignore(toUUIDOrNull('teststr-665785014160310158e823a3'))=0 
settings max_threads=1
format Null;

0 rows in set. Elapsed: 0.045 sec. Processed 100.00 million rows, 800.00 MB (2.25 billion rows/s., 17.97 GB/s.)
Peak memory usage: 126.64 KiB.

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

@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

  • Release build (clang-21, -O3 -DNDEBUG, no LTO/sanitizer/tests), 32-core x86 machine
  • Same build-release directory, freshly rebuilt for each state (apply patch → bench → revert + rebuild → bench)
  • clickhouse client --progress=err (numbers below are stderr Progress: lines, 5 runs each)

Q1 — your exact query (constant-folded)

SELECT count() FROM numbers(1e8)
WHERE ignore(toUUIDOrNull('teststr-665785014160310158e823a3'))=0
SETTINGS max_threads=1 FORMAT Null;
master (no fix) PR #104370
run 1–5 (Grow/s) 5.86 / 5.83 / 6.01 / 5.83 / 6.30 6.12 / 5.91 / 6.03 / 5.71 / 5.74
avg throughput 5.97 G rows/s 5.90 G rows/s
query_log duration 17 ms 16 ms
query_log peak_mem 195.95 KiB 195.87 KiB

Δ ≈ −1.2%, well within run-to-run noise (±5%). The constant-folder eliminates the parser from the hot loop, so this query measures numbers() + ignore()=0 + count(), not parsing. (My machine happens to be ~2.6× faster than yours; absolute numbers don't compare across hosts but the relative delta is what matters.)

Q2 — invalid input forced per-row via materialize()

WHERE ignore(toUUIDOrNull(materialize('teststr-665785014160310158e823a3')))=0
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:

  1. SIMD areHexChars — the loop is naturally vectorizable (SSE2 pcmpgtb / AVX2 lookup); could reclaim most of the overhead at the cost of ~30 lines.
  2. Fuse validation into parseHex — check unhex2 results for 0xff instead 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.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8ec6f70]

Summary: ✅


AI Review

Summary

This 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 parseUUID/tryParseUUID, plus routing no-throw paths through tryParseUUID, is consistent with expected toUUID vs toUUIDOr* semantics, and the added stateless regression coverage is aligned with the reported issue.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 8, 2026
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.
@groeneai

groeneai commented May 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fix-up commit pushed: 8ec6f70b0b1 — fixes the PR-caused Fast test failure on 03773_deterministic_functions_key_condition[_explain].

What broke

After my parseUUID validation patch, the existing 03773 test started failing on Fast test:

Code: 376. DB::Exception: Cannot parse UUID from String: invalid format,
expected 32 or 36 hexadecimal digits with dashes at positions 8, 13, 18, 23
(query: INSERT INTO events (uuid, person_id, ...) VALUES (
    '017adbc0-98b5-0000-3f74-619a368fe65g',  ← trailing 'g' is not hex
    '017adbc0-98b5-0000-3f74-619a368fe65a',
    ...))

This is exactly the bug we are fixing: the old parseUUID accepted '017adbc0-98b5-0000-3f74-619a368fe65g' and silently produced a fabricated UUID; the new strict parser correctly rejects it.

Fix

The g was a typo — the test's queries filter only on person_id, never on uuid. The author likely meant any distinct hex digit so the second row's uuid would differ from the first row's 65d. Replace g → b:

 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 .sql.j2 templates and both .reference files for the data + explain variants.

Verification

  • Local Debug build with the strict parseUUID patch.
  • tests/clickhouse-test --test-runs 30 03773_deterministic_functions_key_condition → 60/60 passes (data + explain, randomized settings on).
  • 04211_uuid_parser_strict_validation_86714 (the new regression test for this PR) — still passes 1/1.
  • count() semantics preserved: both rows still insert (with valid distinct uuids), so count() WHERE person_id < '...65e' still returns 2.

This is the only test in the suite affected — no other test inputs malformed UUID strings.

Session: cron:clickhouse-ci-task-worker:20260509-104500

@clickhouse-gh

clickhouse-gh Bot commented May 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 87.50% (35/40) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff 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.

Acceptable.

@alexey-milovidov alexey-milovidov self-assigned this May 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 9, 2026
Merged via the queue into ClickHouse:master with commit dd819ff May 9, 2026
165 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 9, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: parseUUID in src/IO/ReadHelpers.cpp - core UUID parsing without hex validation — core code present in all supported branches.

Why this might apply: The parseUUID function in ReadHelpers.cpp has existed since ancient times. The bug causes silent data corruption (garbage strings produce fabricated UUIDs) which is P0 severity. All supported branches contain this code and should receive the fix.

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 pr-must-backport or a version label like v26.4-must-backport.

@fm4v fm4v added the pr-backward-incompatible Pull request with backwards incompatible changes label Jul 2, 2026
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Sep 2, 2026
…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).
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-backward-incompatible Pull request with backwards incompatible changes 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

Development

Successfully merging this pull request may close these issues.

toUUIDOrZero does not recognise invalid UUID

6 participants