Skip to content

Fix heap-use-after-free in Parquet UUID writer column statistics - #103692

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix/parquet-uuid-stats-uaf-1288-3e88
Jun 6, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix/parquet-uuid-stats-uaf-1288-3e88

Conversation

@groeneai

@groeneai groeneai commented Apr 29, 2026 •

Copy link
Copy Markdown
Collaborator

A heap-use-after-free in the Parquet writer's UUID column statistics path,
detected by AddressSanitizer in BuzzHouse fuzzing (STID 1288-3e88). Hit on
PR #100366 (Optimize minmax skip index evaluation performance) at commit
f8d1795edeee81e2ec015f68c1a82721803c80f8 on BuzzHouse (arm_asan_ubsan).

ConverterUUID::getBatch reuses a member PODArray<UUID> swapped_buf,
filling each output parquet::FixedLenByteArray::ptr = &swapped_buf[i]
before returning. The Parquet writer loop in writeColumnImpl feeds those
pointers into StatisticsFixedStringRef, which keeps raw const uint8_t *
min/max. After a page flush, total_statistics.merge(page_statistics)
propagates the same raw pointers into total_statistics.

When the next batch's data_count exceeds the current capacity (e.g. after
a low-density null run, where data_count swings from near 0 to near
write_batch_size), swapped_buf.resize(count) reallocates, freeing the
prior buffer. total_statistics.min/max are now dangling. The next
merge performs memcmp(p, total_statistics.min, 16) and reads from freed
memory.

Fix: switch ConverterUUID::Statistics to
StatisticsFixedStringCopy<sizeof(UUID), /*SIGNED=*/ false>, which stores
min/max as inline 16-byte arrays and copies bytes via memcpy on
update/merge, with no lifetime dependency on the converter's buffer. UUIDs
are written big-endian and Parquet's UUID logical type compares as unsigned
binary, so SIGNED=false is correct.

Other Parquet converters using StatisticsFixedStringRef /
StatisticsStringRef (ConverterFixedString, ConverterString,
ConverterFixedStringAsString, ConverterEnumAsString) point into the
source column's stable storage (column.getChars, the enum's name table)
rather than an owned buffer that resizes between batches, so they are not
affected.

Local AddressSanitizer reproducer (deterministic, fails first try without
the fix, passes 50/50 with the fix):

SELECT if(number % 2000 < 1000, NULL, generateUUIDv4()) AS u
FROM numbers(100000)
SETTINGS output_format_parquet_data_page_size = 1024,
         output_format_parquet_batch_size = 1024,
         output_format_parquet_max_dictionary_size = 0,
         output_format_parquet_use_custom_encoder = 1
FORMAT Parquet;

Codified as tests/queries/0_stateless/04141_parquet_uuid_statistics_uaf.sh.

Recategorized from Bug Fix to CI Fix or Improvement per maintainer
request: the bug is a heap-use-after-free that only aborts reliably under a
sanitizer build, but the Bugfix validation (functional tests) job runs the
master HEAD release binary, where the freed read does not deterministically
fail (the test's round-trip row and null counts are unaffected by the
corrupted statistics bytes). The fix and the regression test are kept; only
the changelog category changes so the pr-bugfix validation contract no
longer applies.

CI report (original sanitizer hit):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100366&sha=f8d1795edeee81e2ec015f68c1a82721803c80f8&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.452

`ConverterUUID::getBatch` reuses a member `PODArray<UUID> swapped_buf`,
filling `buf[i].ptr = &swapped_buf[i]` before returning. The Parquet writer
loop then feeds those pointers into `StatisticsFixedStringRef`, which keeps
raw `const uint8_t *` `min`/`max`. After a page is flushed,
`total_statistics.merge(page_statistics)` propagates these pointers into
`total_statistics`.

When the next batch of values exceeds the current capacity (e.g. after a
low-density null run, where `data_count` swings from near 0 to near
`write_batch_size`), `swapped_buf.resize(count)` reallocates and frees the
prior buffer. The `total_statistics.min`/`max` pointers are now dangling.
The next call to `merge` performs `memcmp(p, total_statistics.min, 16)` and
reads from freed memory — heap-use-after-free, detected by AddressSanitizer
in BuzzHouse with STID 1288-3e88.

Switch `ConverterUUID::Statistics` to `StatisticsFixedStringCopy<16, false>`,
which stores min/max as inline 16-byte arrays and copies bytes via memcpy on
update/merge, eliminating the lifetime dependency. UUIDs are written
big-endian and Parquet's UUID logical type compares as unsigned binary, so
`SIGNED=false` is correct.

Other Parquet converters using `StatisticsFixedStringRef` /
`StatisticsStringRef` (e.g. `ConverterFixedString`, `ConverterString`,
`ConverterEnumAsString`) point into the source column's stable storage
(`column.getChars()`, the enum's name table) rather than an owned buffer
that resizes between batches, so they are unaffected.

Add a stateless regression test that triggers the bug pre-fix and passes
post-fix: 100k Nullable(UUID) rows with clustered nulls, small
`output_format_parquet_data_page_size`, custom encoder enabled.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100366&sha=f8d1795edeee81e2ec015f68c1a82721803c80f8&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29
PR with original sanitizer hit: ClickHouse#100366
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @Avogar — could you review this? It fixes a heap-use-after-free in the Parquet writer's UUID column statistics path: ConverterUUID filled StatisticsFixedStringRef with raw pointers into its own swapped_buf PODArray, but that buffer reallocs between getBatch calls when null density swings widely, leaving total_statistics.min/max dangling for the next merge's memcmp. Switched ConverterUUID::Statistics to StatisticsFixedStringCopy<16, false> so min/max are stored as inline byte arrays. Other converters using Ref-style stats already point into stable column storage, so they were unaffected. Deterministic ASan repro included as a stateless regression test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per worker policy, session cron:clickhouse-ci-task-worker:20260429-024500):

# Check Status
a Deterministic repro — exact SQL crashes unpatched ASan binary on first try ✅ — see PR description
b Root cause explained — swapped_buf realloc invalidates StatisticsFixedStringRef::min/max raw pointers stored across page flushes ✅
c Fix matches root cause — switching to StatisticsFixedStringCopy removes the lifetime dependency at the source, no widened bounds, no defensive null check ✅
d Test intent preserved / new test added — new stateless regression test 04141_parquet_uuid_statistics_uaf.sh; no existing test weakened or settings tagged out ✅
e Both directions demonstrated — same SQL: pre-fix → ASan UAF (READ size 16, thread ParquetEncoder); post-fix → 50/50 clean runs ✅
f Fix is general, not a narrow patch — audited every other Parquet Converter. Only ConverterUUID both owns its own buffer (swapped_buf) AND uses a Ref-style Statistics. ConverterFixedString, ConverterString, ConverterFixedStringAsString, ConverterEnumAsString all point into stable column/enum storage, so they are unaffected by the same pattern. ✅

Related fuzzer-found bug already fixed earlier in the same STID (1288-3e88) — MSAN side at FileSegmentRangeWriter::completeFileSegment was fixed in #101161 (merged 2026-04-17). This PR fixes the ASan side, which surfaced separately on PR #100366 today.

@Avogar Avogar self-assigned this Apr 29, 2026
@Avogar Avogar added the can be tested Allows running workflows for external contributors label Apr 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [00a406c]

Summary: ✅


AI Review

Summary

This PR fixes the Parquet UUID column statistics lifetime bug by switching ConverterUUID from pointer-backed fixed string statistics to StatisticsFixedStringCopy, and adds an ASan-oriented stateless regression test for the swapped_buf reallocation path. The prior Bug Fix validation concern was addressed by recategorizing the PR as CI Fix or Improvement; I found no unresolved correctness, safety, or metadata issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 29, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, the test does not reproduce the issue in the "Bug fix validation check". Either make the test stronger, or change the changelog category.

@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov went with the second option: changed the changelog category to CI Fix or Improvement.

Reason the test cannot be made stronger here: this is a heap-use-after-free that only aborts reliably under a sanitizer build. The Bugfix validation (functional tests) job downloads the master HEAD release binary (ci/jobs/functional_tests.py wgets master/{arch}/clickhouse), and in a release build the freed read does not deterministically fail. The test's round-trip row and null counts are unaffected by the corrupted statistics bytes, so a non-sanitizer run passes even on the unfixed code. The original evidence is the ASan abort on BuzzHouse (arm_asan_ubsan) (STID 1288-3e88).

The real fix and the regression test are unchanged. The note output_format_parquet_use_custom_encoder defaults to true, so the fix matters for the default writer path; only the category is relaxed.

Could you remove the pr-bugfix label? Fork contributors cannot remove labels, and the label keeps the bugfix validation contract active even after the category change.

@alexey-milovidov alexey-milovidov added pr-ci and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 6, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Continued work on this PR:

  • Merged master (branch was 764 commits behind and red). No conflicts; the diff stays exactly the 3 files (Write.cpp + test). Verified the merge correctly combined the ConverterUUID statistics change with master's clang-tidy init-variable edits to Write.cpp (compressed_size = 0, h = 0), which were the only master-side touches to that file. Compiled Write.cpp.o cleanly against merged master.
  • Recategorized to CI Fix or Improvement: replaced the pr-bugfix label with pr-ci so the Bugfix validation (functional tests) contract no longer applies (the UAF only aborts under a sanitizer build, not the release binary that job uses). Replied to and resolved the clickhouse-gh bot thread.
  • Remaining red CI is unrelated:
    • 00096_obfuscator_save_load / 00175_obfuscator_schema_inference Aborted — a master-wide regression that spiked on 2026-06-03 (207 failures across ~110 PRs including master itself), now back to background levels. Picked up by the master merge.
    • Performance Comparison (logical_functions_small, parallel_hash_join_various, rand) — noise; both old and new flagged.
    • Unit tests (asan_ubsan) — produced 0 test results (job infra error, not a test failure).

The fix itself is confirmed correct: StatisticsFixedStringRef held raw pointers into ConverterUUID::swapped_buf, which reallocates between batches; StatisticsFixedStringCopy<sizeof(UUID), /*SIGNED=*/ false> copies min/max into inline 16-byte arrays. The comparison stays an unsigned 16-byte memcmp, identical to the previous Ref semantics, and matches Parquet's unsigned-binary UUID ordering.

@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.50% 84.50% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines coverable by tests: 0 (nothing to score) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: 00a406c07749505a20ed2727fb3327f0ba3afc05

CI fully finished and clean on the new HEAD (master-merge by @ alexey-milovidov 2026-06-06): 146 pass / 20 skipping, Finish Workflow pass, Mergeable Check pass, no failing checks, zero per-test FAIL/ERROR rows in CIDB.

Earlier chronic flakies (00096_obfuscator_save_load, 00175_obfuscator_schema_inference, perf-comparison noise, Unit tests asan_ubsan zero-results) that hit the prior SHA 01864313add77ab30f0284fad06f53635330e627 did not recur. The pr-ci recategorization and master merge stuck.

al13n321 APPROVED still stands (HEAD changed but only a clean master-merge plus fix Write.cpp + test).

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 6, 2026
Merged via the queue into ClickHouse:master with commit 4242313 Jun 6, 2026
166 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 6, 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-ci 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.

5 participants