Skip to content

Do not prune Parquet row groups and pages on uuid min/max statistics - #118387

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-parquet-uuid-minmax-stats
Sep 13, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-parquet-uuid-minmax-stats

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #118371
Related: #118380

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 a Parquet reader bug where a filter on a UUID column could silently return fewer rows than the file holds, or reject a valid file with INCORRECT_DATA: Statistics have min_value > max_value. Parquet sorts uuid statistics by big-endian bytes while ClickHouse sorts UUID by its second half, so those statistics are no longer used for row group or page pruning. Closes #118371.

Description

At default settings, SELECT count() FROM file('u.parquet') WHERE u = <a value the file holds> could return 0, and on a file whose statistics pair inverts as ClickHouse UUIDs the read failed with Code: 117 INCORRECT_DATA. One cause, and it reaches any conforming writer's files, including ClickHouse's own.

Root cause. SchemaConverter declared Parquet uuid statistics usable as bounds (allow_stats = true). The endpoints decode to the correct values, but are compared in ClickHouse's UUID order, which is by the second half (docs/reference/data-types/uuid.mdx), not by bytes. A value inside the byte-ordered interval can fall outside it there, so KeyCondition prunes the row group or page holding the matching row; an inverted pair is reported as corrupt metadata. That flag had replaced the reader's own TODO: check if stats are usable.

Change. Leave allow_stats == false at the three sites that install a UUIDConverter, and delete UUIDConverter::convertField so no bound can be produced. FLOAT16 and INT96 in the same switch already answer no for a sort-order reason. One flag covers both pruning legs.

Cost. A uuid column loses row group and page pruning with no fallback: the Parquet bloom filter never accepts the uuid logical type, so no dictionary filter runs either. Equality lookups become full scans. The sound subset is a pair whose first 8 bytes are equal, which for UUIDv4 and UUIDv7 means a single distinct value per row group. Your call.

Validation. New stateless test: both legs, both symptoms, both carriers, plus pruning-preservation controls for the neighbouring String and UInt64 paths. Fails on master, passes here, 50/50 with and without randomized settings. The writer is already correct and untouched.

The Iceberg manifest-bound leg of the same mismatch is #118380. allow_stats = true is present on 26.4 through 26.8; I have not applied a backport label.


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

Version info

  • Merged into: 26.9.1.1328 (included in 26.9 and later)

Parquet's spec sort order for the `uuid` logical type is unsigned big-endian
byte comparison, while ClickHouse orders the `UUID` data type by its second
half, deliberately and documented in `docs/reference/data-types/uuid.mdx`.
`SchemaConverter::processPrimitiveColumn` nevertheless set `allow_stats = true`
for every column decoded by `UUIDConverter`, so
`Reader::getHyperrectangleForRowGroup` and `Reader::applyColumnIndex` turned the
file's min/max pair into a `DB::Range` and handed it to `KeyCondition`.

`UUIDConverter::convertField` decodes both endpoints to the correct values, but
they are then compared under a different total order, so the pair bounds
nothing. A value that lies inside the byte-ordered interval can lie outside it
in ClickHouse's order, and the row group or page holding the matching row is
pruned, so `WHERE u = <a value the file holds>` returned 0 rows at default
settings. When the byte-ordered pair inverts under ClickHouse's order, which
happens for roughly half of random uuid pairs, `adjustRangeFromIndexIfNeeded`
reads it as corrupt metadata and the whole read fails with `INCORRECT_DATA`,
"Statistics have min_value > max_value", on a perfectly valid file. Both
symptoms reach a file written by any conforming writer, including ClickHouse's
own Parquet output.

Leave `allow_stats == false` at the three sites that install a `UUIDConverter`,
and remove `UUIDConverter::convertField` so no bound can be produced at all.
`FLOAT16` and `INT96` in the same `switch` already answer no for a sort-order
reason, and the flag's own documentation says `SchemaConverter` sets it only
after checking that min/max stats are usable. One flag covers both pruning
legs, and with `column_index_conditions` left empty the ColumnIndex is no
longer prefetched or thrift-deserialized for such a column. With the override
gone, a future site that re-enables `allow_stats` for a `UUID` column fails
loudly from the base class instead of silently losing rows again; the override
is unreachable today, since its only caller returns early on `!allow_stats`.

Byte-swapping the bound instead, which is the shape first proposed on the
issue, is not a fix. Measured: it silences the `INCORRECT_DATA` failure while
the silent row loss survives untouched, because the defect is the order and not
the decoded value. The only exactly sound subset is a point range where
`min == max`, which for UUIDv4 and UUIDv7 means one distinct value per row
group, so it buys almost no pruning.

The cost is real and has no fallback:
`isParquetStringTypeSupportedForBloomFilters` admits only the none, `STRING`,
`BSON` and `JSON` logical types, so a `uuid` column never reaches a bloom
hasher, `use_bloom_filter` stays false and the dictionary filter is never
enabled either. An equality lookup on a large `uuid` column becomes a full scan
of every row group. The alternative is silent row loss plus spurious
`INCORRECT_DATA` on valid files.

The writer needs no change: `ConverterUUID` already emits spec-correct
byte-lexicographic statistics over the big-endian bytes, measured hex-identical
to pyarrow's. The Iceberg manifest-bound leg of the same order mismatch is a
separate change.

The new test covers both pruning legs, both symptoms, both sites that install a
`UUIDConverter`, and the no-type-hint form the defect was reported in, with
pruning-preservation controls for the neighbouring `String` and `UInt64` paths.

Closes: ClickHouse#118371

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

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

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold pass
(3 nits), bounded: 1 full pass + 1 fix round + 1 delta recheck.

# Sev Finding Verdict Evidence / action
1 ⚠️ The page-pruning arms assert only count(), so they would still pass if page-index filtering silently stopped running (05099...sql:47-52, :87) DISAGREE The premise is right, the signal loss is not: 04849_parquet_wide_integer_decimal.sh:909-950 already pins the ordinary page-index leg with exact counts under the same isolation (filter_push_down=0, page_filter_push_down=1), asserting read=1 pruned=15 and read=0 pruned=16; 04060/04691 pin the spatial leg. Page filtering stopping reddens those. The arms here are live for this fix (0 on master, 1 here, and on master the two Code: 117 messages name different sites). I am not duplicating an exact-count guard for a counter unrelated to UUID.
2 💡 3 nits of my own, all in the PR text, none in the diff AGREE, fixed Issue and sibling links made visible instead of sitting inside the template's HTML comment; an over-claimed "only exactly sound subset" corrected (the sound subset is a pair whose first 8 bytes are equal, of which min == max is a special case).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20260906-064100

@clickhouse-gh clickhouse-gh Bot closed this Sep 6, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @grantholly-clickhouse @al13n321, could you review this? Parquet orders uuid statistics by unsigned big-endian bytes while ClickHouse orders UUID by its second half, so the min/max pair is not an interval in the column own order and KeyCondition pruned the row group or page holding a matching row. I leave allow_stats false at the three sites that install a UUIDConverter, which removes min/max pruning for uuid columns with no bloom filter fallback, so the cost is the part worth your ruling.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ae0ea92]

Summary: ✅


AI Review

Summary

This PR disables Parquet row-group and page-index pruning for columns decoded as UUID by keeping allow_stats off at the UUID decoding sites and by removing the now-unusable UUIDConverter statistics decoder, then adds a focused stateless regression test for the silent row-loss and spurious INCORRECT_DATA cases. I did not find a surviving correctness, safety, or compatibility issue in the current diff.

Missing context / blind spots
  • ⚠️ I did not run the new stateless test locally because this checkout does not contain a prepared build directory or matching local binary; the review is based on current code inspection plus the PR discussion and CI context.
Final Verdict

✅ No review findings. No inline comments were posted.

LLVM Coverage Report

Measured on commit ae0ea92.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 9/13 (69.23%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ae0ea924c with master 55c256363 (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

17 translation units recompiled, 142 s compile time in total, 17 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -5.0 s (-3%) in total before that adjustment.

Job report

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 608c09a

Every failure below has an owner: a fixing PR (mine 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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) a background mutation retries forever, about once a second, on a column the table no longer has: MutatePlainMergeTreeTask: Code: 47. DB::Exception: Unknown expression identifier 'b'. Maybe you meant: ['a']. In scope b, b. (UNKNOWN_IDENTIFIER), logged from MergeTreeBackgroundExecutor on part all_1_1_1_2, which the upgrade job's log scan then reports #115962 (mine, open)

Mergeable Check and PR are aggregators of the row above, so they do not get their own lines.
Head census: 174 checks, 153 success, 18 skipped, 3 failure.

Not caused by this PR, structurally: this diff is confined to
src/Processors/Formats/Impl/Parquet/Decoding.{cpp,h} and SchemaConverter.cpp plus one stateless
test, so it changes which Parquet row groups and pages are pruned on uuid min/max statistics. It
touches nothing in mutation execution, MergeTree part reading or analyzer scope resolution, and the
failing log line is a mutation expression resolving column b against a table that only has a.

Cross-PR breadth of that signature over 30 days, measured on this tick: 36 rows across 33 distinct
pull requests and 36 commits, from 2026-08-22 04:45:32 to 2026-09-06 09:52:33, with 0 occurrences on
master. A second unrelated carrier, #113208, hit the identical signature at 07:43:26 the same day.
#115962 ("Do not read a part column that the table no longer has") is the product-level fix for it
and is open and awaiting review, so it cannot be present on this head.

Mergeable Check is red only because of that one job, so merging stays blocked until it is re-run
green or #115962 lands.

Session id: cron:our-pr-ci-monitor:20260906-120041

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 20fa35e Sep 13, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
…equested type reorders

A Parquet column stored as a plain INT32/INT64 has signed-order min/max
statistics. Read with an unsigned type hint, a point lookup silently
returned no rows at default settings, on a file ClickHouse wrote itself:

    INSERT INTO FUNCTION file('i32.parquet', Parquet, 'x Int32')
        SELECT arrayJoin([toInt32(-1), toInt32(5)]) AS x;
    SELECT count() FROM file('i32.parquet', Parquet, 'x UInt32')
        WHERE x = 4294967295;   -- 0, wrong; 1 with both push-downs off

IntConverter::convertField decodes one endpoint at a time: it
sign-extends under input_signed (the stored type's signedness) and emits
a Field under field_signed (the requested type's). Where the two
interpretations disagree in sign it answers std::nullopt, and
PageDecoderInfo::decodeField turns that into "leave that side of the
range at infinity". That is sound only if the surviving pair is still an
interval in the Field order, and it is not when the pair straddles the
sign boundary. For the row group {-1, 5} the signed-order pair is
min = -1, max = 5; as UInt32 the values are {4294967295, 5}, so the true
bounds are [5, 4294967295]. min = -1 becomes nullopt, correctly
unbounding the left side, but max = 5 is kept, and 5 is not an upper
bound in unsigned order. KeyCondition::checkInHyperrectangle gets
(-inf, 5], and both the row group and the page holding the matching row
are pruned - two legs, so disabling either one alone still returned 0.

dispatch_int_stats_converter authorised this by taking signedness from
the output type alone and never comparing it with the stored type's, so
allow_stats contradicted its own documented contract in Decoding.h:
"False if type hint requires a nontrivial cast that's either not
monotonic or not supported". A signedness-flipping reinterpretation is
exactly such a cast - castColumn wraps the values while the endpoints
were compared in the stored order.

The guard withholds the statistics unless the cast to the requested type
preserves the stored order for every value the stored type can hold,
which is FunctionConvert::getMonotonicityForRange's "always monotonic"
class: the same signedness needs an equal or wider output, and a
signedness flip needs an unsigned stored type and a strictly wider
signed output. Everything else reorders. A flip maps the negative half
above the positive one, and a narrowing cast wraps, so a UINT_32 column
holding {65535, 65536} read as UInt16 produces {65535, 0} and the stored
max is again not an upper bound. stored_bits is the declared width
(output_size is set to 1 or 2 exactly when the INTEGER annotation is 8
or 16 bits), and 1 for physical BOOLEAN, whose single bit fits every
native integer. It sits in the one lambda all five integer sites call,
so no site can be forgotten, and the single flag covers the row group
leg, the page index leg and the ColumnIndex prefetch.

Cost is zero on every healthy read: an un-hinted read infers the
matching signedness, ClickHouse writes UInt* with UINT_* annotations,
and the order-preserving widenings (UINT_32 to Int64, UINT_8 to Int16 or
wider, BOOLEAN to Int8) keep their statistics. The new test has a
pruning-preservation control for each, asserting a non-zero
ParquetPrunedRowGroups.

Two alternatives were rejected. Dropping only a straddling pair at the
Reader level needs a pair-level API (convertField sees one endpoint and
cannot know the other), a fail-closed rule for a lone endpoint, and a
data-dependent branch in both legs, to keep pruning in a configuration
that is a deliberate reinterpretation. Reinterpreting the endpoint into
the output order cannot work at all: the value set is then a union of
two disjoint intervals, [0, max] and [min + 2^N, 2^N - 1], which no
single Range expresses, and emitting the reinterpreted min inverts the
pair so adjustRangeFromIndexIfNeeded reports a valid file as
INCORRECT_DATA - the same dead end measured on ClickHouse#118387.

Scope, measured rather than argued. The narrowing and 8-bit arms are
fixed in the min/max legs only. With both hash push-downs off and both
min/max legs on, a UINT_32 column read as UInt16 and an INT32 column
read as Int16 each returned 0 rows where 1 is correct, on master and on
the signedness-only form of this guard alike, and 1 here. At default
settings they are still lost, because the bloom and dictionary filters
hash both sides after a static_cast to the parquet physical type, so the
two hashes agree only if the low sizeof(physical) bits do: the count is
0 at defaults, still 0 with both min/max push-downs off, and 1 only once
the dictionary and bloom push-downs are off too. That leg is left to a
follow-up, so the bound removed here is unsound and its removal a strict
improvement, but not a complete fix for those arms. The Enum8/Enum16 and
Date32 carriers of this lambda have the same min/max hole and stay with
that follow-up too: they change the value space or the unit rather than
the width, so the width rule above is not the right predicate for them.
The IPv4 arm is left to ClickHouse#117017, which fail-closes IPv4 statistics for
the same reason. DateTime and TIMESTAMP_MILLIS hints stay sound and
untouched: those conversions saturate rather than wrap
(ToDateTimeTransform64Signed returns 0 for a negative input, and an
out-of-range positive lands on UINT32_MAX), and saturation is monotonic,
so the converted endpoints still bound the converted values; both were
measured to return the row at default settings. A Date hint over an
integer column, however, joins the Enum and Date32 carriers rather than
being sound: an integer past the day-number range is reinterpreted as a
Unix timestamp, so a plain INT32 column holding {65536, 65537} decodes
to two 1970-01-01 values while its statistics stay [65536, 65537], and a
lookup of 1970-01-01 returns 0 of 2 rows with only the min/max legs
active. The width rule above cannot separate that from its sound path,
since a parquet DATE column read as Date must keep pruning, so it goes
to the same follow-up.

Closes: ClickHouse#118376

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
-- 3 UUIDs in one row group. Byte order A < C < B, so the Parquet stats are
-- min = A, max = B; in ClickHouse UUID order (second half first) C > B, so the
-- only row group is pruned and the matching row is lost.
INSERT INTO FUNCTION file('u3.parquet', Parquet, 'u UUID')
SELECT toUUID(x) FROM values('x String',
    '00000000-0000-0000-0000-000000000001',
    '00000000-0000-0000-ffff-ffffffffffff',
    '00000001-0000-0000-0000-000000000002')
SETTINGS engine_file_truncate_on_insert = 1, max_insert_threads = 1;

SELECT count() FROM file('u3.parquet', Parquet, 'u UUID')
WHERE u = toUUID('00000000-0000-0000-ffff-ffffffffffff');
-- 26.4-26.8: 0   (expected 1; SELECT count() without the WHERE returns 3)

-- Second symptom: a stats pair that inverts in ClickHouse order is rejected.
INSERT INTO FUNCTION file('u2.parquet', Parquet, 'u UUID')
SELECT toUUID(x) FROM values('x String',
    '00000000-0000-0000-ffff-ffffffffffff',
    '00000001-0000-0000-0000-000000000002')
SETTINGS engine_file_truncate_on_insert = 1, max_insert_threads = 1;

SELECT count() FROM file('u2.parquet', Parquet, 'u UUID')
WHERE u = toUUID('00000001-0000-0000-0000-000000000002');
-- 26.4-26.8: Code: 117. DB::Exception: Statistics have min_value > max_value ... (INCORRECT_DATA)

▶ Run on ClickHouse Fiddle

Results:

  • Culprit PR: Add Arrow and Parquet format support for UUID data type Add Arrow and Parquet format support for UUID data type #99521
  • Reproduces on: 26.8, 26.7, 26.6
  • Does not reproduce on: 26.3
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • Bisect anchor (below the supported window, not a backport target): 26.2 clean
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.6.

CC introducing PR author: @ivanmantova

CC component owner: @al13n321

Analysis metadata

comp-parquet-reader-v3 · Severity P2 · Finding phase_d_pr118387

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-parquet-reader-v3 Issues related to the native Parquet reader. groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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