Repository navigation
Use min/max stats for raw parquet INT64 columns read as DateTime - #117017
wudidapaopao wants to merge 13 commits into
Conversation
Stats outside the `DateTime` range are not used as bounds because the cast saturates.
|
Workflow [PR], commit [1fac236] Summary: ❌
AI ReviewSummaryThis PR enables Parquet min/max pruning when physical Final Verdict
LLVM Coverage Report |
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, 155 s compile time in total, 17 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
Only the `UInt32` to `IPv4` cast is supported; stats on other inputs could hide the unsupported-cast error when all row groups are pruned.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…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]>
`Date` and `Date32` reach the integer statistics through the reinterpreting arm
of `dispatch_int_stats_converter`, which never checked whether the requested
type keeps the endpoints' order. A day number outside the target's window is
reinterpreted rather than carried over, so the raw endpoints stop bounding the
values:
- a plain `INT32` or `INT64` column {65536, 65537} read as `Date` holds two
1970-01-01 values under statistics that stay [65536, 65537], so a lookup of
1970-01-01 was pruned away, 0 rows instead of 2;
- a plain `INT64` column {100000, 2^32} read as `Date32` holds a 2106 day under
a kept min of 2243-10-17, so `x < '2243-10-17'` was pruned away, 0 instead
of 1;
- a plain `INT32` column {2932896, 2932897} read as `Date32` straddles the day
2932896 limit above which the cast reads the number as seconds instead, so
9999-12-31 and 1970-02-03 arrive in that order and `x < '2000-01-01'` was
pruned away, 0 instead of 1.
All measured with the dictionary and bloom push-downs off, so that only the
min/max legs were live. At completely default settings those rows are lost to
the hash filters as well, which is a separate defect.
The width and signedness test is hoisted into `stats_order_preserved` and
applied to `Date`, whose window is the whole UInt16 domain
(DATE_LUT_MAX_DAY_NUM is 0xFFFF), so passing that test already means no stored
value leaves the window. `Date32` stops at day 2932896, well below INT32_MAX, so
matching widths prove nothing there and it now requires the day-range check
instead. That check is `date_overflow_behavior`, set on the parquet `DATE` path,
where `convertField` drops every endpoint outside the window and inside it the
day number is the output value, so a `DATE` column read as `Date` or `Date32`
keeps pruning.
Applying that check turned out to require a fix of its own: `convertField` ran it
only for a signed Field, and a `Date` target asks for an unsigned one, so the
parquet `DATE` path never range-checked its endpoints either. Days past
2149-06-06 read as `Date` with `date_time_overflow_behavior = 'saturate'`
therefore arrived as 2149-06-06 while their raw bounds survived, and the lookup
of that day was pruned away, 0 rows instead of 2. The check now runs before the
Field is built, for both signednesses.
The `IPv4` and `DateTime` arms keep their current behaviour, and both are
unsound in the same way: `IPv4` over a signed carrier hides `Conversion from
Int32 to IPv4 is not supported` behind an empty result, and a `UINT_64` column
{2^32, 2^32+1} read as `DateTime` decodes to two 2106-02-07 06:28:15 values
whose lookup each min/max leg discards. ClickHouse#117017 fixes both by range-checking
those endpoints, which preserves the pruning that a width test would give up, so
those arms are better left to it.
The cost is the trade the rest of this change already makes. A plain `INT32`
column whose values all sit inside the Date window is no longer pruned under a
`Date` hint, and no integer carrier is pruned under a `Date32` hint, because the
endpoints have to bound every value the stored type can hold, not only the ones
present.
…overflow error
Three more cases where Parquet min/max pruning answered differently from a read
with push-down off, found in review:
- `IPv4` over a signed carrier has no cast at all, so pruning turned the
NOT_IMPLEMENTED error into an empty result; over a UINT_64 carrier the cast
wraps, so a row group {3, 2^32+1, 2^32+2} arrives as 0.0.0.3, 0.0.0.1,
0.0.0.2 under a stored min of 3 and `x = '0.0.0.1'` returned 0 instead of 1.
`IPv4` now takes statistics only through the same order test as the integer
arms, i.e. from an unsigned carrier of at most 32 bits.
- `DateTime` saturates above UINT32_MAX, so a UINT_64 row group {2^32, 2^32+1}
arrives as two 2106-02-07 06:28:15 values outside the stored bounds. Such an
endpoint now bounds nothing. Same rule as ClickHouse#117017 for these two arms.
- A parquet `DATE` value outside the requested type's window fails the read
under the default `date_time_overflow_behavior`, but the out-of-window
endpoint was only dropped, so the other side could still prune the chunk and
`x < '2000-01-01'` over {2149-06-06, 2149-06-07} read as `Date` returned 0
instead of VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE. Under `throw` such an
endpoint now voids the chunk's statistics (row group and page index), so the
chunk is read and raises the same error; `saturate` keeps the one-sided
widening. Since every row-group statistics field is optional, such a row
group is bounded under `throw` only when both min and max are present. The
window check also moves before the signed-to-unsigned check, because a
negative day is outside the `Date` window too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
TopN dynamic filtering for Parquet (ClickHouse#115798) skips a row group when its min/max statistics are compared with the running threshold, at the OffsetIndex stage of ReadManager::finishRowGroupStage. ReadManager::init started all row groups at once, so with no bloom filter, dictionary or page index work every row group passed that check before the sorting transforms had published any threshold, and with such work the row groups still reached it in file order. Inside one file the skip almost never fired; 05025 only covers it across the files of a glob. Now, when the read order is free (no input_format_parquet_preserve_order, no lazy materialization row list) and at least one row group to read has a usable range of the sort column: - Reader::prefilterAndInitRowGroups orders the row groups by the minimum of the sort column for ascending order and by the maximum for descending order; row groups without a range go last. row_group_idx and start_global_row_idx keep the file positions, so _row_number, bucket matching and the query condition cache are unaffected. - ReadManager admits them gradually: at most max(parsing_threads, admitted / 2) are admitted but not fully read, and each is checked against the latest threshold right before it starts. A skipped row group does not raise the allowance and an admitted one does, so a scan that the threshold cannot prune quickly converges to an unthrottled one (the same scheduling as Pivot's table_source.rs). Row groups excluded by the bucket list or the query condition cache are deallocated at admission without being counted. - New profile event ParquetTopKSkippedRowGroups. The format-source branch of tryOptimizeTopK ran before the dependsOnItsBlock guard that only the MergeTree branch had, so a stateful or non-deterministic function below the sort (expression, WHERE, user PREWHERE) already saw rows dropped by the reader's threshold filter, and with the new order it would also see the row groups out of file order. The guard now applies to both branches. For formats it also covers a block-dependent row policy: the Parquet reader applies the row-level filter after the threshold filter, while MergeTree applies it first. Analysis and the original patch by snelheidai in ClickHouse#123564. Allowing statistics for a plain INT64 column read as DateTime (part 3 of that patch, needed for ClickBench's EventTime with the DateTime schema) is left to ClickHouse#117017. Closes ClickHouse#123564 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The plain INT64 branch of SchemaConverter::processPrimitiveColumn turned the statistics off for a DateTime target, so a Parquet INT64 column without a logical type (EventTime in ClickBench's hits.parquet) got no row group or page pruning and no top-K row group skipping. The plain INT32 and annotated INTEGER(64) branches already allow it: a bound outside the DateTime range is not used, and IPv4 over a 64-bit integer is still refused. This is the remaining part of ClickHouse#117017; ClickHouse#121033 already added those rules. Co-authored-by: wudidapaopao <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Use min/max statistics for pruning when a parquet
INT64column is read asDateTime, including rawINT64columns without a logical type annotation. Also stop using out-of-rangeINTEGER(64)statistics asDateTimebounds, which could previously prune matching row groups incorrectly.Previously, predicates on such columns scanned all row groups. Statistics values outside the
DateTimerange are not used as bounds, because the cast saturates.IPv4statistics are additionally restricted to unsigned 32-bit parquet columns — the only input whose cast is supported — so that pruning cannot hide an unsupported-cast error behind an empty result.Columns of this shape are common in files from older parquet writers, e.g.
EventTime,ClientEventTimeandLocalEventTimein the ClickBenchhits.parquet.Workflow [PR]
Sync PR [sync-upstream/pr/117017]