Repository navigation
Do not prune Parquet row groups and pages on uuid min/max statistics - #118387
Conversation
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]>
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260906-064100 |
|
cc @grantholly-clickhouse @al13n321, could you review this? Parquet orders |
|
Workflow [PR], commit [ae0ea92] Summary: ✅
AI ReviewSummaryThis PR disables Parquet row-group and page-index pruning for columns decoded as Missing context / blind spots
Final Verdict✅ No review findings. No inline comments were posted. LLVM Coverage ReportMeasured on commit ae0ea92.
Changed lines: Changed C/C++ lines covered: 9/13 (69.23%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units17 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. |
CI finish ledger - 608c09aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR, structurally: this diff is confined to Cross-PR breadth of that signature over 30 days, measured on this tick: 36 rows across 33 distinct
Session id: cron:our-pr-ci-monitor:20260906-120041 |
…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]>
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)Results:
Backport the fix to CC introducing PR author: @ivanmantova CC component owner: @al13n321 Analysis metadata
|
Closes: #118371
Related: #118380
Changelog category (leave one):
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
UUIDcolumn could silently return fewer rows than the file holds, or reject a valid file withINCORRECT_DATA: Statistics have min_value > max_value. Parquet sortsuuidstatistics by big-endian bytes while ClickHouse sortsUUIDby 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 return0, and on a file whose statistics pair inverts as ClickHouse UUIDs the read failed withCode: 117 INCORRECT_DATA. One cause, and it reaches any conforming writer's files, including ClickHouse's own.Root cause.
SchemaConverterdeclared Parquetuuidstatistics usable as bounds (allow_stats = true). The endpoints decode to the correct values, but are compared in ClickHouse'sUUIDorder, 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, soKeyConditionprunes the row group or page holding the matching row; an inverted pair is reported as corrupt metadata. That flag had replaced the reader's ownTODO: check if stats are usable.Change. Leave
allow_stats == falseat the three sites that install aUUIDConverter, and deleteUUIDConverter::convertFieldso no bound can be produced.FLOAT16andINT96in the sameswitchalready answer no for a sort-order reason. One flag covers both pruning legs.Cost. A
uuidcolumn loses row group and page pruning with no fallback: the Parquet bloom filter never accepts theuuidlogical 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
StringandUInt64paths. 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 = trueis present on 26.4 through 26.8; I have not applied a backport label.Workflow [PR]
Sync PR [sync-upstream/pr/118387]
Version info
26.9.1.1328(included in26.9and later)