Skip to content

Fix Parquet pruning that skips rows when inverted UInt64 statistics are read as DateTime - #128508

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:parquet-inverted-statistics-stored-order
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:parquet-inverted-statistics-stored-order

Conversation

@groeneai

@groeneai groeneai commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128302
Related: #128336
Related: #121033
Related: #128494

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 the native Parquet reader skipping matching rows when a UInt64 column with inverted statistics (min_value > max_value, as polars 0.20 writes them for values >= 2^63) is read as DateTime and filtered. Such statistics are now detected in the column's stored order and ignored.

Description

On 26.10.2.103, SELECT count() FROM file('f.parquet', Parquet, 'u Nullable(DateTime)') WHERE u > toDateTime(100) over the #128302 reproducer (polars 0.20.31, pl.Series([1, 2**63], dtype=pl.UInt64), statistics min_value 2^63, max_value 1) returns 0. With input_format_parquet_filter_push_down = 0, input_format_parquet_page_filter_push_down = 0 it returns 1: the read saturates 2^63 to the DateTime maximum.

#128336 ignores statistics whose decoded range is inverted. Since #121033, a DateTime bound above UINT32_MAX decodes to no bound, so this pair decodes to [-inf, 1]. That range is not inverted, and row group and page pruning use it to skip the row. 26.9 and older reject the query with INCORRECT_DATA instead.

IntConverter::statsInverted compares the two stored values in the column's sort order. getHyperrectangleForRowGroup and applyColumnIndex ignore statistics that are inverted there, before the type-dependent decode. The TopN and optimize_min_max_from_files paths already give up on a bound that does not decode.

This re-lands c61dbb6, which was pushed to #128336 after it was enqueued and so did not merge with it. The test now also checks that the valid row group and page are still pruned.

Validation: 05479_parquet_inverted_statistics_ignored gets two DateTime arms (row group and page pruning). On master both rows are missing; with the fix it passes, 50/50 with random settings. The real polars file behaves the same for DateTime, Nullable(DateTime), LowCardinality(Nullable(DateTime)) and timezone-qualified hints; other hints and valid statistics prune as before. The other Parquet stateless tests give the same results with and without the fix.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits November 1, 2026 16:15
The inversion check ran on the decoded range. Decoding leaves a bound at
infinity when the requested type cannot hold it, so under a type hint the
inverted polars statistics can stop looking inverted: a UInt64 chunk with
min_value 2^63 and max_value 1 read as `DateTime` decodes to [-inf, 1], and
row group and page pruning dropped the row that the read saturates to the
`DateTime` maximum (`WHERE u64 > toDateTime(100)` returned nothing; it
returns that row with the pruning disabled). 26.10 and master return no
row; 26.9 and older fail the query with INCORRECT_DATA instead.

`IntConverter` now compares the stored values in the column's sort order
(signed or unsigned per the logical type), and the row group and column
index paths ignore statistics that are inverted there. The TopN and
min/max-from-statistics paths already give up when a bound does not
decode. The check on the decoded range stays for the other converters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nt in 05479

The two DateTime arms asserted only the returned row, so they would also
pass if every statistic were ignored under a DateTime hint. They now also
print ParquetPrunedRowGroups / ParquetPrunedPages, like the no-hint arms:
row group 1 / page 1 (valid statistics {10, 20}) must still be pruned.

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

groeneai commented Nov 1, 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; round 1: 1 finding, round 2 on 48650b681d7a: 0 findings) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The DateTime arms of 05479 check only the returned row, not that valid statistics still prune AGREE, fixed @ 48650b6 the arms also assert ParquetPrunedRowGroups / ParquetPrunedPages = 1; the master build gives 2 / 2 and no row
2 💡 TopN and optimize_min_max_from_files do not call the stored-order check DISAGREE both give up on a bound that does not decode; every integer decode that keeps both bounds preserves their order
3 💡 A wrong-size max_value is now read before a rejected min_value DISAGREE malformed files only; same CANNOT_PARSE_NUMBER, same message

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261101-172500

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The polars 0.20.31 file from #128302 ([1, 2**63] as UInt64) read as u Nullable(DateTime) with WHERE u > toDateTime(100) returns 0 rows with row group pruning, page pruning and default settings, and 1 row with both pushdowns off. Every run, on master and 26.10.2.103.
b Root cause explained? Since #121033 a DateTime bound above UINT32_MAX decodes to no bound. The inverted pair (2^63, 1) therefore decodes to [-inf, 1], which the decoded-range check of #128336 does not see as inverted, so pruning skips a row that the read saturates to the DateTime maximum.
c Fix matches root cause? Yes. Inversion is checked on the stored values in the column's own sort order, before the lossy decode that hides it. No widened bound, no tag, no masking guard.
d Test intent preserved / new tests added? Yes. 05479 gets two DateTime arms (row group and page), each checking the returned row and that the valid row group / page is still pruned (ParquetPrunedRowGroups / ParquetPrunedPages = 1). Existing arms are unchanged (additions only).
e Both directions demonstrated? Yes. Master build: 05479 fails only in the two DateTime arms: no 4294967295 row, and 2 row groups / pages pruned instead of 1. Fix build: passes, 50/50 with random settings.
f Fix is general across code paths? Yes. Both min/max pruning paths (row group statistics, column index) are fixed; the cached file filter replays the row group ranges; TopN and optimize_min_max_from_files already give up on a bound that does not decode.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. DateTime, Nullable(DateTime), LowCardinality(Nullable(DateTime)) and timezone-qualified hints are fixed; UInt64, Int64, UInt32, Date hints give the same results as before; signed or unsigned order comes from the logical type.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Only chunks and pages whose stored min exceeds the stored max lose pruning, and their results now equal the unpruned read.
i Invariants and contracts preserved? Yes. convertField behaviour is unchanged (the load is only extracted); a wrong-size value throws the same CANNOT_PARSE_NUMBER in the same try; unusable statistics give the whole-universe range as before.

Session id: cron:clickhouse-impl-slot-4:20261101-171700

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @grantholly-clickhouse, could you review this and add the can be tested label so CI runs? Inverted integer statistics are now detected on the stored values in the column's sort order, before the type-dependent decode: with a DateTime hint the out-of-range minimum 2^63 decodes to no bound, so row group and page pruning dropped the matching row (wrong results on 26.10).

@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1e8630f]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

PR #128508, reviewed at 1e8630f9840ff20ac2a52a0b06775c79788e89a2, detects inverted integer Parquet statistics before type conversion can hide the inversion. This prevents row-group and page pruning from dropping matching rows under a DateTime type hint. No actionable findings. The regression covers both pruning paths and verifies that valid statistics still prune.

Missing context / blind spots
  • ⚠️ Current-head stateless and bugfix-validation jobs are skipped behind an existing human review thread. The identical regression script passed five runs in the previous revision's debug CI job. No local tests were run because this checkout has no ClickHouse binary. Rerunning current-head CI after that thread is resolved would provide fresh runtime confirmation.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 1, 2026
return val;
}

bool IntConverter::statsInverted(std::span<const char> min, std::span<const char> max) const

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.

@groeneai why do we need to cover the case when stats are inverted? seems a bit ridiculous

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.

I think that the user won't try to invert the stats

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user doesn't produce them, the writer does: polars 0.20 writes UInt64/UInt32 min/max in signed order while declaring TYPE_ORDER (#128302), so a row group holding both 1 and 2^63 gets min = 2^63, max = 1. Until #128336, any filter on such a column failed with INCORRECT_DATA; @ fm4v asked in #128302 to ignore these statistics instead.

This PR covers the case where the decoded-range check (the old INCORRECT_DATA one and #128336's) cannot see the inversion: with a DateTime hint the min 2^63 is out of range and decodes to no bound, so the decoded range is [-inf, 1] and the row group is pruned. With the #128302 file:

SELECT count() FROM file('polars_u64.parquet', Parquet, 'u Nullable(DateTime)') WHERE u > toDateTime(100)
-- 26.10.2.103: 0 (1 with both Parquet filter pushdowns disabled); 26.9: INCORRECT_DATA

So since 26.10 it is a silent wrong result instead of an error. Checking the stored values before the decode is the smallest fix I found. If you still think it isn't worth handling, I'll close the PR.

@clickhouse-gh clickhouse-gh Bot added the comp-parquet-reader-v3 Issues related to the native Parquet reader. label Nov 1, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 48650b681 with master aff304839 (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

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

Job report

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 48650b6

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
Stateless tests (amd_debug, parallel) / 05474_parquet_corpus_writers broken on master, not from this PR: the polars 0.20 rows of the reference are stale; the tree that ran (merge ref 944eb61) predates the fix #128494 (ours, merged)
Stateless tests (arm_binary, parallel) / 05474_parquet_corpus_writers same as the row above #128494 (ours, merged)
Finish Workflow / Post Hooks the new-tests check found no Bugfix validation result: both functional Bugfix validation jobs were dropped after the 05474 red above, so they did not run #128494 (ours, merged)
Mergeable Check, PR praktika rollups of the rows above #128494 (ours, merged)

CIDB has no other FAIL or ERROR row on this head. The later stages were skipped after the early-stage red, so they need a rerun on a tree that has the fix.

Session id: cron:our-pr-ci-monitor:20261101-233003

…atistics-stored-order

Conflict in Decoding.h: master added [[nodiscard]] to the converter
declarations (clang-tidy modernize-use-nodiscard). Kept it and added it to
the new statsInverted and loadValue declarations as well.

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

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review approves this commit, see the AI Review comment.

Ergus pushed a commit to Ergus/ClickHouse that referenced this pull request Nov 19, 2026
`query_plan_propagate_predicate_across_join` copied a filter conjunct onto
the other side of an equi-join only when that side reads a MergeTree whose
primary key contains the key. A `file`, `url` or plain object storage read
of Parquet got nothing, although the same filter written by hand skips row
groups by their min/max statistics.

A read now says through `SourceStepWithFilterBase::canSkipDataByFilterOn`
whether a filter on a column lets it skip data without dropping rows that
pass the filter. `ReadFromFile`, `ReadFromURL` and `ReadFromObjectStorageStep`
answer yes for a Parquet read with `input_format_parquet_filter_push_down`
for a column the format reads from the file as it is (in `format_header`
with the same type, no Hive partition or virtual column, no default
expression) of a native integer, `Date`, `Date32` or `Decimal` type,
also inside `Nullable` / `LowCardinality`. Left out on purpose:
- floats: Parquet bounds leave out NaN, so `x != 1.5` would skip a row group
  of NaN and 1.5 that the join matches (ClickHouse#118110);
- `String`: bounds of a FIXED_LEN_BYTE_ARRAY read as `String` keep the
  padding (ClickHouse#120986);
- `DateTime`, `IPv4`: a narrowing conversion leaves a bound unset (ClickHouse#128508);
- `UUID`, `DateTime64`, `FixedString`, containers and others: no usable
  statistics, so a copy would be a full-scan filter;
- default expressions: the default replaces NULL after the reader skipped
  data (ClickHouse#125929);
- data lakes: their `format` is only the write format, and Iceberg pruning
  still has open defects a join-side filter would reach (ClickHouse#128578, ClickHouse#119576,
  ClickHouse#122602).

`use_primary_key` now only stops the copy onto a MergeTree read (read from
that read's context) instead of disabling the whole pass.

Release build, 30M-row Int64 Parquet files of 29 row groups, MergeTree
source, 10-20 paired alternating runs, median change [95% CI]:
point lookup -80.5%, narrow range -81.7%, IN of 6 keys -94.2%, unsorted
with bloom filters -55.5%; costs of a copy that skips nothing
(`k % 1000 = 0 AND k >= 1000`): hash join +3.2% [+0.3, +6.8] at 1 thread,
+2.2% at 4, +1.1% at default threads; full_sorting_merge +7.8%
[+6.5, +11.4] at 1 thread, +2.1% at 4; non-selective IN of 1000 keys -3.7%.

Related: ClickHouse#129119
Related: ClickHouse#128374

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

This branch has not been deployed

No deployments
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. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants