Skip to content

Do not prune Parquet row groups and pages on integer statistics the requested type reorders - #121033

Merged
grantholly-clickhouse merged 6 commits into
ClickHouse:masterfrom
groeneai:parquet-int-signedness-no-minmax-pruning
Oct 2, 2026
Merged

grantholly-clickhouse merged 6 commits into
ClickHouse:masterfrom
groeneai:parquet-int-signedness-no-minmax-pruning

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #118376
Related: #117017
Related: #118387

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 an integer column read with a type hint that reorders the file's statistics (for example UInt32 over a plain INT32 column, Enum8 over a UINT_8 one, or IPv4 over a UINT_64 one) could silently return fewer rows than the file holds. Such statistics are no longer used for row group or page pruning, and a DATE value outside the requested type's range now raises the same error with pruning as without it. Closes #118376.

Description

The native Parquet reader is the default since 25.11. At default settings a point lookup on an integer column read with an unsigned hint silently returned no rows, 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, should be 1

Root cause. Min/max are ordered as the stored type, and convertField unbounds only the endpoint the reinterpretation cannot represent. Read as UInt32, the kept max = 5 of {-1, 5} is not an upper bound, so both are pruned.

Change. One guard in that lambda, called by all five integer sites, keeps the statistics only when the cast preserves the stored order for every stored value: an equal or wider output of the same signedness, or unsigned to a strictly wider signed type. It covers the native integers, Enum8/Enum16, Date and IPv4, which order by their underlying integer. Date32 keeps statistics only on the parquet DATE path, whose day-range check confines the endpoints. A DateTime endpoint above UINT32_MAX bounds nothing, since that cast saturates. Under throw, an out-of-range DATE endpoint voids the chunk's statistics so the read raises its error.

Scope. Left open, measured below: a point lookup on a narrowing hint is still lost to the bloom and dictionary filters (#121077). The IPv4 and DateTime hunks are the rules #117017 proposes for those arms.

Validation. New stateless tests: both legs, both widths and directions, a widening flip, narrowing, Enum, Date, Date32, IPv4 and DateTime hints, both DATE overflow modes per leg, footers with only a min or a max, and a ParquetPrunedRowGroups control per kept widening. Each published head reddens exactly the arms its round adds; randomized, plain and non-UTC runs are clean.

Measured: the Enum arms, and what a min/max guard cannot reach

count() for a predicate that matches, so a low number is silent row loss.

A range predicate is served by neither hash filter, so it isolates the min/max legs at completely default settings:

arm, all defaults, nothing disabled before here
UINT_8 {5, 200} as Int8, x < 0 0 1
UINT_8 {5, 200} as Enum8('lo' = 5, 'hi' = -56), x < 'lo' 0 1
UINT_16 {5, 40000} as Enum16('lo' = 5, 'hi' = -25536), x < 'lo' 0 1

A point lookup is a different story. (a) all defaults; (b) input_format_parquet_filter_push_down = 0, input_format_parquet_page_filter_push_down = 0; (c) (b) plus the dictionary and bloom push-downs off.

arm (a) (b) (c)
UInt32 file read as UInt16 0 0 1
UInt8 file read as Int8 0 0 1
UInt32 file read as Date32 0 0 1
Int32 file {65536, 65537} read as Date 0 0 2

(b) is load-bearing: with both min/max legs off the row is still lost, so no min/max guard recovers those point lookups. The filters hash both sides after a static_cast to the physical type, so a naive sizeof(output) >= sizeof(physical) rule would disable them for every UInt8/UInt16/Int8/Int16 column, which ClickHouse writes as physical INT32.

The Date rows above are fixed here on the min/max side: with only those legs live, {65536, 65537} read as Date returns 2. Also fixed on those legs: a UINT_64 column {2^32, 2^32+1} read as DateTime decodes to two 2106-02-07 06:28:15 values while the raw bounds survived (0, now 2); {3, 2^32+1, 2^32+2} read as IPv4 wraps to 0.0.0.3, 0.0.0.1, 0.0.0.2 (0, now 1); and an IPv4 hint over a signed column, or a DATE value out of range, now raises its error instead of an empty result.


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

Version info

  • Merged into: 26.10.1.1243-master (included in 26.10 and later)

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 19, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex) plus a separate cold read of the
resulting tree; bounded: 1 full pass + 1 fix round + a delta recheck that returned 0 findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ Deleting the converter.input_signed disjunct of the new guard leaves the whole suite green, although it is the only thing that refuses statistics for a widening sign flip such as a plain INT32 column read as UInt64 (SchemaConverter.cpp:988) AGREE, fixed @ 813089a7f5548 every signedness-flipping arm was equal-width; added an i32 read as UInt64 point lookup (0 on master, 1 here) and mutation-proved the disjunct: dropping it takes that arm 1 -> 0 and moves no other line
2 ⚠️ Deleting the declared-width source output_size.value_or(input_size) also leaves the suite green, and the change claimed a pruning-preservation control for UINT_8 widened to Int16 that did not exist (SchemaConverter.cpp:985) AGREE, fixed @ 813089a7f5548 no arm used an 8- or 16-bit INTEGER annotation; added the UINT_8 to Int16 control asserting a non-zero ParquetPrunedRowGroups, and using the physical width instead takes it 1 1 -> 2 0 with the count unchanged
3 💡 The description says which reads keep their statistics, not what the affected reads pay AGREE, answered here a signedness-flipping read loses row group and page pruning on that column but keeps the dictionary and bloom filters: both hash each side after a static_cast to the parquet physical type, so they stay sound for exactly the equal-width flips this change withholds statistics for. Two test arms pin that, each hash filter enabled in turn with both min/max legs off. Unlike the uuid sibling #118387, equality lookups do not degrade to full scans
4 💡 stored_bits overstates the declared width when an INT(8) or INT(16) annotation sits on a physical INT64, and convertField does not apply output_size on the plain integer path DISAGREE, no action neither is reachable: the guard can only ever withhold statistics, so overstating stored_bits costs pruning and cannot produce a wrong bound, and the second point needs a file whose values exceed their own declared INTEGER width, which the writer never emits

All five sub-expressions of the guard now have a measured reddening arm, each mutation rebuilt and
restored: the signedness comparison, the input_signed disjunct, the declared-width source, <=
versus <, and the single-bit BOOLEAN case.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-49:20260919-140100

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3b54e6]

Summary: ✅


AI Review

Summary

This PR tightens Parquet min/max pruning for integer-backed type hints whose cast can reorder or otherwise invalidate the stored statistics, and it also closes the DATE/partial-statistics throw hole that could previously turn a conversion exception into an empty result. I re-read the current diff, the touched reader/converter paths, the added stateless coverage, and every existing review thread/reply; the previously reported issues are fixed in the current code, and I did not find any new contract violations in the remaining changed surface.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit d3b54e6.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.70% +0.10%

Changed lines: Changed C/C++ lines covered: 102/108 (94.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the comp-parquet-reader-v3 Issues related to the native Parquet reader. label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d3b54e640 with master 1ed3fcc2c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of a0b65176b; 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

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

Job report

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 91bb8ca

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
AST fuzzer (amd_debug, targeted) / Server unresponsive: memory limit exceeded job-level memory limit, not a fuzzer finding: 35 rows across 17 unrelated PRs in 30 days on this flavour alone, plus true-master rows #118467 (external, open)
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 perf noise promoted to a red by the dashboard-verdict gate; the query is flagged slower in 231 unrelated PRs in 14 days, at +1.158x (0.015 s to 0.018 s, p=0.132), and reads a MergeTree table this diff cannot touch #121090 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) / iceberg_suite_tpch query4 harness timeout, Code: 159 at 16134 ms against the 15000 ms max_query_seconds cap, surfaced as "10 errors" because the run-errors table counts traceback rows rather than tests a fix task is moved to pending (investigating at full effort, fixing PR link to follow on this PR)

Notes on the 5/6 line: #120923 (merged 2026-09-19 18:34Z) was the candidate fix for this class and
is deliberately not linked as its owner, because the class continues after it: 40 reds across 42
distinct PRs in the 6 hours from that merge, and more since. #116491 (merged 2026-09-20 02:23Z)
corrects only the "10 errors" miscount, not the timeout. Neither is on this branch.

None of the three failures is caused by this diff, which is confined to Parquet integer statistics
pruning; the head carries no Parquet or reader failure.

Session id: cron:our-pr-ci-monitor:20260920-043144

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the arm_release, master_head, 5/6 ledger line - 91bb8ca

This corrects one line of the CI finish ledger above; the other two lines are unchanged.

Fixing PR: #120923 (external, merged 2026-09-19 18:34:47Z, merge commit 0b3b89d0).

My ledger note withheld that link on the grounds that "the class continues after it". That reading was
wrong, and the error was in my measurement rather than in the revert. I bucketed job failures in 6 hour
windows, so the 18:34:47Z merge fell inside the 18:00 bucket, and I counted pull request runs whose
binaries were built before the revert existed.

Re-measured on true master only, and keyed on the build rather than on the job start time:

  • Master rows carrying a run error since the revert merged: 2, both explained. One is a master commit
    that predates the revert. The other is the revert's own merge commit, whose reference (left) binary is
    the preceding master build and so still carries the regression.
  • From 2026-09-20 00:00Z: 0 of 132 master Performance Comparison job rows report a run error.
  • iceberg_suite_tpch #4 on true master is back to baseline: p50 364 ms, max 616 ms over 11 samples,
    against 346 to 359 ms before Join reordering: FK->PK heuristic for equi joins without NDV statistics #120176 landed.

This head is still red because both binaries it compared predate the revert:

  • reference (left): master bf51e0555dd8, 2026-09-19 16:47:35Z;
  • patched (right): the merge commit praktika resolved at workflow dispatch 2026-09-19T18:12:59Z,
    22 minutes before the revert merged.

So the correct disposition for this line is a merged fixing PR that is absent from this branch. Merging
master picks it up and clears the shard. The other two ledger lines are unchanged.

@grantholly-clickhouse

Copy link
Copy Markdown
Contributor

@groeneai what about other data types where the sort order could differ if the user passes a different data type? I'm thinking about a Enum8 as an example

@groeneai

Copy link
Copy Markdown
Collaborator Author

There are more, and Enum8 is the sharpest one. What decides a case is whether the cast from the stored type to the requested type preserves order for every value the stored type can hold. The guard in this PR only reaches requested types that WhichDataType::isNativeInteger() accepts; Enum8, Enum16, Date32 and Date reach the same statistics through the other arm of the same switch in dispatch_int_stats_converter, so it does not see them.

Measured at this head against master. A UINT_8 column {5, 200} has statistics [5, 200] in unsigned order and reads back as {5, -56} in 8-bit signed order. Every row below is default settings, nothing disabled:

file requested type predicate master this PR correct
UINT_8 {5, 200} Int8 x < 0 0 1 1
UINT_8 {5, 200} Enum8('lo' = 5, 'hi' = -56) x < 'lo' 0 0 1
UINT_16 {5, 40000} Int16 x < 0 0 1 1
UINT_16 {5, 40000} Enum16('lo' = 5, 'hi' = -25536) x < 'lo' 0 0 1

That is worse than the table in the description, which used point lookups where the hash filters lose the row anyway: with a range predicate the min/max leg drops the rows on its own, at defaults. So I am folding Enum8 and Enum16 into this PR. A ClickHouse enum compares by its underlying signed integer value, so the predicate itself does not change, only which types enter it: Enum8 counts as 8 signed bits and Enum16 as 16. Nothing sound is withheld by that, since INT_8 to Enum8 is the identity and UINT_8 to Enum16 is a widening flip.

The rest of the surface, so the scope paragraph is not vague:

  • Date over a plain integer column, and Date32 over a 32-bit column, are wrong today too, but they are not a width question: an integer past the day-number range is reinterpreted, so the discriminator has to be the unit and the target's valid day window, and a parquet DATE column read as Date must keep pruning. Those stay in the follow-up.
  • IPv4 is left to Use min/max stats for raw parquet INT64 columns read as DateTime #117017, which fail-closes it for the same reason.
  • DateTime and TIMESTAMP_MILLIS are sound: those conversions saturate rather than wrap, and saturation is monotonic.
  • Nullable and LowCardinality add no order of their own. They are unwrapped before this decision, and the fix reaches through them: LowCardinality(Int8) and Nullable(Int8) over that same UINT_8 file both go from 0 to 1.
  • The other statistics gates are type-matched or fail closed, so no further requested type reaches a reordering: the decimal gate needs the same size and scale and refuses the DateTime64 to Time64 wrap explicitly, the float gate takes only Float32 and Float64, the string sites grant statistics only when the output type is String (so a parquet ENUM column read as Enum8 prunes correctly, measured 1 at defaults), and a negative parquet DECIMAL read as an unsigned wide integer is rejected with Code: 321 instead of wrapping.

An Enum column orders and compares by its underlying signed integer, so an
Enum hint over a parquet integer column reinterprets the stored statistics
exactly like the native integer of that width, and the guard added in the
previous commit has to cover it. It did not: Enum8 and Enum16 left the
requested type through the `switch` below, which granted statistics
unconditionally, so the same reordering the guard rejects for Int8 and Int16
was still accepted for Enum8 and Enum16.

This is reachable at completely default settings, which the min/max legs
alone decide for a range predicate. A UINT_8 column {5, 200} has statistics
[5, 200] in unsigned order and reads back as {5, -56} in 8-bit signed order,
so the stored max is not an upper bound. Measured, correct answer 1 in all
four lines, nothing disabled:

    UINT_8  {5, 200}    as Int8    x < 0     0 before the previous commit, 1 after
    UINT_8  {5, 200}    as Enum8   x < 'lo'  0 before, 0 after, 1 here
    UINT_16 {5, 40000}  as Int16   x < 0     0 before, 1 after
    UINT_16 {5, 40000}  as Enum16  x < 'lo'  0 before, 0 after, 1 here

The point-lookup form of those two arms is additionally lost to the bloom and
dictionary filters, which is why the previous commit's measured table read as
if the Enum carriers were unreachable through this leg. A range predicate is
served by neither hash filter, so it isolates the min/max legs at defaults and
shows that closing them is a complete fix for that predicate class.

The predicate itself does not change, only which requested types enter it:
Enum8 counts as 8 signed bits and Enum16 as 16, both via
getSizeOfValueInMemory, and field_signed becomes true for them, which is what
the `switch` arm already left in place by default. Nothing sound is withheld:
an INT_8 column read as Enum8 is the identity and a UINT_8 column read as
Enum16 is an always-monotonic widening flip, and both keep pruning under a new
control apiece. Dropping the enum clause from the field_signed assignment
alone reddens both new arms and the INT_8 to Enum8 control (2 row groups read,
0 pruned), so neither half of the change is redundant.

Date32 stays in the `switch`: it is the same label group but not the same
question, since its reinterpretation is bounded by the target's valid day
window rather than by a width, and a parquet DATE column read as Date must
keep pruning. That carrier, the Date one, and the bloom and dictionary hash
legs remain the follow-up named in the description.

One claim of the previous commit message needs correcting. It said a DateTime
hint over a plain integer column returns its row at default settings because
those conversions saturate and saturation is monotonic. The monotonicity
argument does not hold as stated: the statistics are not converted along with
the values, they stay in the raw integer domain. The conclusion survives on the
legs this PR touches, but only by measurement. An INT64 column {2^32, 2^32+1}
read as DateTime decodes to two 2106-02-07 06:28:15 values, and a lookup of
that timestamp returns 2 rows with the dictionary and bloom push-downs off,
with either min/max leg alone, and 0 at default settings. So the min/max legs
are sound for that hint, and its default-settings loss belongs to the hash
legs, with the rest of that family.

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

Copy link
Copy Markdown
Collaborator Author

Folded in as 3485e08. Enum8 and Enum16 now take the same order test as the native integer of their width, the two arms in the table above go from 0 to 1 at default settings, and two preservation controls pin the sound direction (INT_8 read as Enum8 is the identity, UINT_8 read as Enum16 a widening flip; both still prune, asserted through ParquetPrunedRowGroups). Date, Date32 and IPv4 are unchanged, for the reasons above.

One correction to what I told you about DateTime. Saying it is sound "because those conversions saturate, which is monotonic" was the wrong reason: the statistics are not converted along with the values, they stay in the raw integer domain, so monotonicity of the value map is not what makes that bound safe. The conclusion survives, but by measurement rather than by that argument. An INT64 column {2^32, 2^32+1} read as DateTime decodes to two 2106-02-07 06:28:15 values, and a lookup of that timestamp returns 2 with the dictionary and bloom push-downs off and with either min/max leg alone, and 0 at completely default settings. So the min/max legs are sound for that hint and its default-settings loss belongs to the hash-filter family, not to this one. The description and the commit message say that now instead.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3485e08

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
AST fuzzer (amd_debug, targeted, old_compatibility) / OOM in dmesg host-OOM: oom-kill:constraint=CONSTRAINT_MEMCG inside the job's own docker memcg, with task=clickhouse-serv as the victim. 12 rows / 7 unrelated carrier PRs in the last 72 hours across the three amd_debug fuzzer flavours, so the trigger is job memory pressure and not this diff. #118467 (external, open)

Session id: cron:our-pr-ci-monitor:20260922-043144

@grantholly-clickhouse

Copy link
Copy Markdown
Contributor

@groeneai there are still other data types where this bug can manifest. Can you explain and the others?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Three more, and I measured each one instead of arguing it. Two are the same defect on the same leg and
are now folded in; the third already has a fix PR open against the same lines.

Date and Date32 reach these statistics through the other arm of that same switch, and they order by
their underlying integer exactly like an Enum does (Date is UInt16, Date32 is Int32). So a day
number the requested type cannot represent is not carried over, it is reinterpreted, which is the same
reordering this PR is about. Every row below has the two hash filters off so that only the min/max legs
are live; the last column is the answer with all four push-downs off.

file, one row group requested values it holds predicate master this PR correct
plain INT32 {65536, 65537} Date 1970-01-01, 1970-01-01 x = '1970-01-01' 0 2 2
plain INT64 {65536, 65537} Date 1970-01-01, 1970-01-01 x = '1970-01-01' 0 2 2
plain INT64 {100000, 2^32} Date32 2243-10-17, a 2106 day x < '2243-10-17' 0 1 1
plain INT32 {-1, 5} IPv4 cast unsupported x = '255.255.255.255' 0 0 error

The IPv4 row is the symptom reported in #118376: pruning turns Conversion from Int32 to IPv4 is not supported into a silent empty result. #117017 fail-closes precisely that (converter.input_signed || converter.input_size != sizeof(IPv4)) in the arm right above mine, so folding it in here would only
conflict with it.

The rest of that surface is sound, and I checked rather than assumed:

  • A DATE column read as Date or Date32 keeps pruning: date_overflow_behavior is set on that path,
    so convertField drops every endpoint outside the target's day window, and inside that window the day
    number is the output value. The new guard defers to that check, and both directions still prune
    (asserted through ParquetPrunedRowGroups).
  • A negative value in a plain integer carrier does not reorder: the cast to Date and to DateTime
    saturates to the window floor rather than wrapping, so {-1, 5} decodes to {1970-01-01, 1970-01-06} and
    the kept max still bounds it. Measured 1 with the min/max legs live, 0 only at defaults, so that loss is
    the hash-filter family, tracked in Do not use Parquet bloom or dictionary filters when the requested type changes what a value hashes to #121077.
  • Same-order carriers keep pruning: INT32 to Date32 is the identity, UINT_16 to Date an unsigned
    16-bit identity, UINT_32 to DateTime and to IPv4 unsigned 32-bit identities.
  • DateTime over a plain integer carrier is sound on these legs today, and Use min/max stats for raw parquet INT64 columns read as DateTime #117017 is extending its
    pruning, so I left that arm untouched.

The cost is the trade this PR already makes elsewhere: a plain INT32 column whose values all sit inside
the Date window stops being pruned under a Date hint, since the endpoints have to bound every value the
stored type can hold, not only the ones present. Answers stay correct, that read just scans.

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

Copy link
Copy Markdown
Collaborator Author

Folded in as 2bfa4e4. Date now takes the same order test as the native integer of its width, which is
sound because its window is exactly the underlying UInt16. Date32 does not get that shortcut, and
chasing why corrected two things I told you above.

INT32 to Date32 is not the identity. Date32 reaches day 2932896 and reads a larger number as
seconds instead, so a plain INT32 column {2932896, 2932897} decodes to 9999-12-31 and 1970-02-03 while
the statistics keep that order: x < '2000-01-01' returned 0 with only the min/max legs live, 1 with
everything off. Since the width test cannot see that, Date32 now keeps statistics only where the
day-range check confines the endpoints, which is the parquet DATE path.

That day-range check was not actually running for a Date target. convertField applied it only when
the Field is signed, and a Date target asks for an unsigned one, so a DATE column whose days pass
2149-06-06 read as Date with date_time_overflow_behavior = 'saturate' arrived as 2149-06-06 while the
raw bounds survived: the lookup of that day returned 0 instead of 2. The check now runs before the Field
is built, for both signednesses. Without that, the exemption I am leaning on for DATE would have been
unsound, so it is part of the same commit.

And DateTime is not sound, for a 64-bit carrier. I only measured a plain INT64 one, where the
statistics are refused outright anyway. With the UINT_64 annotation they are not: a column
{2^32, 2^32+1} decodes to two 2106-02-07 06:28:15 values, and each min/max leg drops that lookup, 0
against 2 with both off.

That last one and the IPv4 row are what I am still leaving to #117017, for a reason rather than to keep
this smaller: it range-checks those endpoints against the target's window, the same shape as the DATE
path above, so it keeps the pruning that a width test would give up. Duplicating its hunk here would only
conflict with it. If you would rather have all four arms in one change, say so and I will fold those two
in as well.

Test: 5 new arms, each reddening on the previous head and nothing else; 11 ParquetPrunedRowGroups
controls unchanged, including DATE read as both Date and Date32. Description updated.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2bfa4e4

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
Performance Comparison (arm_release, master_head, 4/6) / bitmap_cardinality #4 dashboard-only verdict, not PR-caused: the dashboard reports 0.0398 -> 0.0540 (+35.4%) tier confirmed_regression, while this shard's own report publishes that query as success and lists no slower query at all (summary 4 too long; 1 confirmed regression(s) on the performance dashboard, no "slower" phrase) #121090 (mine, open)
Mergeable Check aggregator row, mirrors the row above, no independent failure #121090 (mine, open)
PR aggregator row, mirrors the row above, no independent failure #121090 (mine, open)

Measured at this head rather than inherited: 313,511 CIDB rows over 135 checks, 0 FAIL/ERROR
test rows
, and the failing shard is 1106 success rows plus the one job summary. All six
bitmap_cardinality queries, #4 included, are success on both the old and the new binary, so
the red comes only from the dashboard arm. #121090 is causal for exactly that shape: it fails a
master_head shard only when the shard's own report also calls the query slower, and it exits
early when the shard published no slower query, which is this case.

Not reachable from this diff: the change is Parquet integer-statistics pruning in
Decoding.cpp / SchemaConverter.cpp plus one stateless test, and bitmap_cardinality is a
groupBitmap perf test over MergeTree that reads no Parquet. Breadth over 7 days: the
confirmed regression(s) on the performance dashboard red hits 643 rows across 338 distinct pull
requests and 0 true-master runs, and bitmap_cardinality #4 alone is flagged unstable on 136
distinct pull requests, so the leaf is known-noisy independently of this branch.

Session id: cron:our-pr-ci-monitor:20260923-073136

@grantholly-clickhouse

Copy link
Copy Markdown
Contributor

@groeneai it also looks like we might still have issues of erroneous row pruning with DateTime and IPv4 types as well when used in combination with UInt64s. Here's a bit from claude on the topic

Still unaddressed: IPv4 and DateTime

These are the only arms of the else switch that never call stats_order_preserved and are not range-check-gated — they're guarded solely by the allow_datetime_and_ipv4 flag, which controls reachability, not order preservation.

IPv4 over a signed carrier. Reachable from the INT logical site and the plain-INT32 site. Int32 {-1, 5} read as IPv4:

min/max ON : 0
min/max OFF : Code: 48. NOT_IMPLEMENTED: Conversion from Int32 to IPv4 is not supported

Pruning converts a loud error into a silent empty result — which is precisely the second symptom reported in issue #118376, the issue this PR says it closes. UINT_32 carriers are sound (same width, same signedness): verified 1 both with and without pruning.

DateTime over an annotated 64-bit carrier. UInt64 {2^32, 2^32+1} read as DateTime:

decoded values : ['2106-02-07 06:28:15','2106-02-07 06:28:15']
count WHERE x=that : 0 (min/max ON)
count WHERE x=that : 2 (min/max OFF)

Both values clamp to UINT32_MAX while the raw bounds [2^32, 2^32+1] survive, so the range no longer contains them. Silent row loss.

Could you verify first before making any changes?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified on master (064b09a3) before changing anything. One row group per file; "min/max" = dictionary and bloom filters off, "none" = all four push-downs off (the true answer).

file read as predicate min/max none
plain INT32 {-1, 5} IPv4 x = '255.255.255.255' 0 NOT_IMPLEMENTED
INT_16 {-1, 5} (pyarrow) IPv4 same 0 NOT_IMPLEMENTED
UINT_64 {3, 2^32+1, 2^32+2} IPv4 x = '0.0.0.1' 0 1
UINT_32 {5, 4000000000} IPv4 x = toIPv4(4000000000) 1 1
UINT_64 {2^32, 2^32+1} DateTime('UTC') x = toDateTime(4294967295, 'UTC') 0 2
plain INT32 {-1, 5} DateTime('UTC') x = toDateTime(0, 'UTC') 1 1

Both claims hold, and there is a third case: a UINT_64 carrier read as IPv4 does not just hide an error, it loses rows silently, because that cast wraps (the values arrive as 0.0.0.3, 0.0.0.1, 0.0.0.2) while the stored min 3 survives. DateTime only breaks above UINT32_MAX, where the cast saturates. A negative value saturates to 0 and its endpoint is already dropped, so signed 32-bit carriers are sound on the min/max legs. (At default settings the last row returns 0; that loss is the dictionary filter, which #121077 covers.)

What I'm changing:

  • IPv4: statistics only for an unsigned carrier of at most 32 bits, through the same order test the integer arms use. Signed carriers and UINT_64 get none, so the cast error surfaces and the wrapped rows are found.
  • DateTime: statistics kept, but an endpoint above UINT32_MAX no longer bounds anything.

These are the rules #117017 proposes for the same two arms. I had left them to it to avoid a conflict, but it has been idle since early September, so I'll fold them in here; whichever merges second resolves trivially.

The throw question is answered in its thread. For the timezone one, I'll run the whole test under a non-UTC session once the build is done.

…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]>
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 1289aec8 with the changes from my earlier comment, plus one gap the extra review turned up:

  • IPv4: statistics only from an unsigned carrier of at most 32 bits. The signed cases now raise NOT_IMPLEMENTED like the unpruned read, and the wrapped UINT_64 row is found (0, now 1).
  • DateTime: an endpoint above UINT32_MAX no longer bounds anything (0, now 2 on the min/max legs). At default settings that lookup still returns 0 through the bloom and dictionary filters, which Do not use Parquet bloom or dictionary filters when the requested type changes what a value hashes to #121077 covers.
  • throw: an out-of-range DATE endpoint voids the statistics of its row group or page, so the Date and Date32 cases, above and below the range, now raise VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE with pruning on (for Date32 also through each leg alone). saturate still prunes.
  • New: every row group statistics field is optional, so a footer carrying only min_value (or only max_value) could still prune such a chunk. Under throw a row group now needs both endpoints. Covered by 05230_parquet_date_partial_statistics with two small hand-made fixtures.

Every new defect arm fails on the previous head and passes here; the new controls pass on both. 40 randomized runs and runs under Asia/Tokyo, Pacific/Kiritimati and America/Los_Angeles are clean. PR description updated.

…_load_2

00900_long_parquet_load_2 loads every file in data_parquet/ and compares
the output with its reference, so the two hand-crafted fixtures added for
05230_parquet_date_partial_statistics showed up as unexpected blocks.
They only make sense for that test, so add them to the exclusion list,
like the other test-specific fixtures there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d3b54e6

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
Stress test (arm_release) / Hung check failed, possible deadlock found trunk hang, not PR-caused: the hung query is desc file(..., 'Freeform') settings max_memory_usage = 150000000 from the new test 05258_freeform_schema_inference_search_bound (added by #122447, merged today at 01:32Z). The stress runner drew compatibility = '25.11', which reverts input_format_freeform_max_search_steps to 0 (unlimited), and the search then ignored KILL (is_cancelled = 1, 472 s) and reached 22.45 GB against its 150 MB limit. The same 05258 query hung master d6021c7b43d5 and another unrelated PR in the same window. This PR only changes Parquet statistics pruning and does not reach Freeform a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (same as above)
Sync - CH Inc sync (private, not actionable by me)

146 of 146 check runs completed (127 passed, 18 not selected, 1 red: the job above), Finish Workflow is green, and the 00900_long_parquet_load_2 failure of the previous head is fixed at this head.

Session id: cron:our-pr-ci-monitor:20261001-080315

@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_release) hung check (05258 Freeform search): #123238

@grantholly-clickhouse
grantholly-clickhouse added this pull request to the merge queue Oct 1, 2026
@grantholly-clickhouse grantholly-clickhouse self-assigned this Oct 1, 2026
Merged via the queue into ClickHouse:master with commit 1ea026f Oct 2, 2026
294 of 295 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 Oct 2, 2026
alexey-milovidov pushed a commit to RinChanNOWWW/ClickHouse that referenced this pull request Oct 3, 2026
EmeraldShift pushed a commit to EmeraldShift/ClickHouse that referenced this pull request Oct 20, 2026
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]>
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-request PR origin: a maintainer pinged or directed groeneai 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

3 participants