Repository navigation
Fix Parquet pruning dropping rows that hold a NaN, and write the mandatory nan_count statistic - #116725
Fix Parquet pruning dropping rows that hold a NaN, and write the mandatory nan_count statistic#116725groeneai wants to merge 13 commits into
Conversation
Parquet statistics for a float column exclude NaN, both per parquet.thrift (a reader must assume nan_count > 0 when the field is absent) and as emitted by ClickHouse's own writer. A row group holding [5.0, 5.0, nan] therefore advertises min = max = 5. KeyCondition::checkInHyperrectangle treats containsRange over those bounds as proof that every row satisfies the atom. That claim is false when a NaN is hidden outside the bounds, and three RPN element kinds turn it into a wrong prune: FUNCTION_NOT_IN_RANGE, FUNCTION_NOT_IN_SET and FUNCTION_NOT. Set atoms break in the other direction too, because set membership treats NaN as equal to NaN (nan IN (nan) is 1 while nan = nan is 0), so a hidden NaN row can match a set that the finite bounds say is unreachable. The dense checkInHyperrectangle takes an optional per-key-column mask saying which bounds were computed from non-NaN values only. The Parquet reader builds it from Statistics.nan_count per row group and ColumnIndex.nan_counts per page, and passes it at its four pruning sites, including the bloom/dictionary and GeoParquet bbox consumers that reuse the row group's hyperrectangle. Positive predicates derive can_be_true from intersectsRange alone and are unaffected. The only pruning given up is a float column whose statistics say min == max == c under a predicate excluding exactly c. Co-Authored-By: Claude Opus 5 <[email protected]>
The tuple early return in `setMayMatchHiddenNaN` is correctness, not the conservatism the previous commit called it. `MergeTreeSetIndex` orders `ordered_set` lexicographically, so a NaN in a non-leading tuple position is not the last element of its own column and the last-element test answers no: `(i, val) IN ((1, nan), (2, 7.))` over a row group whose `val` statistics say `min = max = 5` returns nothing without it. `LowCardinality(Nullable(Float64))` is likewise the only structure that distinguishes the unwrap order in `typeMayHoldNaN`. Both now have arms. Two claims in the previous commit message are too narrow and are corrected here: pruning is also given up, irrespective of `min` and `max` and in the positive direction, for any set atom over such a column that holds a NaN or reaches it through a tuple or a function chain. `nan_counts` is now length-validated beside `null_counts` rather than bounded per page, so both optional per-page lists of `ColumnIndex` fail closed alike. The correctness arms pin `input_format_parquet_dictionary_filter_push_down`, which the test runner randomizes, and a row-group-only pruning arm completes the complement of the existing page-only one. `not_in_three` is dropped: two and three set elements take the same path. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewReviewed cold against the resulting code, then adversarially by a second model, over 2 rounds. Round 1 (4 adversarial findings, 5 from the cold read) - all fixed except two carriers.
Round 2 (4 adversarial findings, 2 from the cold read). Neither round-1 carrier came back.
Noticed while reading, not addressed and not raised as work: |
|
Workflow [PR], commit [e25ac59] Summary: ❌
AI ReviewSummaryThis PR fixes the Parquet-specific wrong-pruning cases caused by float statistics excluding Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit e25ac59.
Changed lines: Changed C/C++ lines covered: 118/124 (95.16%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260827-121800 |
|
cc @al13n321 @tiandiwonder, could you review this? Parquet float min/max statistics exclude NaN, so |
Build profile diff (arm_release)Commit See the job log for details. |
…what it asserts The test failed `Stateless tests (amd_asan_ubsan, flaky check)` with `Test runs too long (> 180s). Make it faster.` on 13 of 16 runs, between 180.5 s and 201.5 s, while every other flavour stayed green between 73 s and 100 s. The cost is process spawn, not query work: the test issued 68 `clickhouse-client` invocations, and one such invocation costs 0.511 s on an ASan+UBSan build, so 34.7 s of a 38.3 s solo run was spawn overhead. Each output section now queues its statements and sends them as one batch. `arm` and `arm_page_only` append two statements instead of running two clients and `run_arms` rejoins their two output lines; `prune` appends a `FORMAT JSON` statement and `run_prunes` labels the batch with one `jq` call, using `transpose` so that a batch which lost a statement prints a null field rather than silently relabelling the survivors. That is 10 client invocations instead of 68. The queries are unchanged, so the reference file is untouched. Measured over `system.query_log`, both forms issue the same 67 read queries with the same source, predicate and pushdown settings, so every arm keeps its own pushdown-off oracle inside the same batch. On an ASan+UBSan master build that does not contain this branch's fix, both forms print byte-identical output and still redden the same 21 arms. Solo cost on that build with randomization on falls from 90.9 s to 17.3 s, and the 50 run randomized check passes in 116 s instead of 614 s. `long` and `no-flaky-check` were both rejected: the first divides `--test-runs` by ten so the flaky check would run about five times instead of fifty, and the second skips the only mode that enforces the 180 s ceiling. Also drops a comment clause claiming that a zero `input_format_parquet_dictionary_filter_push_down` takes the dictionary pruning site out of the run. It does not: `prepareBloomFilterCondition` treats a column as eligible when it has either a bloom filter or a usable dictionary page, and `input_format_parquet_bloom_filter_push_down` defaults to `true`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116725&sha=faa8e45817bcfded2bb135ec27b2574d1e15e558&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 PR: ClickHouse#116725 Co-Authored-By: Claude Opus 5 <[email protected]>
|
The Nothing the test asserts changed and the reference file is untouched. Measured over |
CI finish ledger - e4dd395Every 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
One thing worth recording because it is not visible at this head: the earlier Session id: cron:our-pr-ci-monitor:20260828-010000 |
…n from ClickHouse#117202 The Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) shard was red on 91257ca with a node death, Code: 210 Connection refused at OPTIMIZE TABLE test FINAL in test_s3_plain_rewritable. That is the shutdown gdb fan-out pinning the nested container cgroup at its cap, and ClickHouse#117202 (merged 2026-08-31 11:05:36Z) serializes the attach. This run predates it, so the branch is refreshed to re-run with the fix.
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_s3_plain_rewritable/test.py::test[s3_plain_rewritable_with_metadata_cache-data_with_cache/] |
node death: Code: 210. DB::NetException: Connection refused (172.16.1.10:9000). (NETWORK_ERROR) at test_s3_plain_rewritable/test.py:138, node.query("OPTIMIZE TABLE test FINAL"). On a hung docker compose stop every node of a cluster crosses the same 60 second stacktrace deadline together, so several gdb processes attach at once and each reads the whole binary's debug info; together they pin the cgroup holding the nested containers at its 40.78 GiB cap and the kernel kills whatever is largest in it, which while gdb is still small is a ClickHouse server. The mid-flight test then sees Code: 210. |
#117202 (merged 2026-08-31), merged master @ e03515e086efd2ee057f0c93018724ed1dc50940 |
Not caused by this PR: the diff is src/Processors/Formats/Impl/Parquet/Reader.{cpp,h},
src/Storages/MergeTree/KeyCondition.{cpp,h} and one new stateless test, none of which touch S3
plain-rewritable metadata or server lifecycle. It is one failing test in a shard that otherwise
reported 1189 passing tests and 23 skips.
Why the branch was refreshed rather than the line simply linked: #117202 serializes that attach and
it is merged, but it was absent from the tree that ran. The symbol it introduces,
GDB_ATTACH_LOCK in tests/integration/integration-tests-entrypoint.sh, occurs 0 times at
91257ca7, 0 times at the pre-fix parent 0f26762e (negative control) and 6 times at the fix's own
merge commit 7fc3004e (positive control), so both controls are valid and the verdict is not an
artifact of looking in the wrong place. The run was created 2026-08-30 21:47:54Z, and a pull request
run's merge commit is fixed at trigger time, so even its third attempt, which started 11:13:52Z
after the fix landed at 11:05:36Z, still executed the pre-fix harness. A re-run therefore could not
pick it up; only a fresh tree can. Master is merged at e03515e0, whose first parent is
91257ca7 and second is 89d70c05, adding exactly one commit and leaving all six of this PR's own
blobs byte-identical.
Session id: cron:our-pr-ci-monitor:20260831-133000
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases |
result differs from the reference on the old analyzer lane: supported_aggregation and supported_join read 0 0 instead of 1 1, because the optimization is built on the query plan. Failed 3 of 3 reruns |
#117364 (external, merged 2026-08-31), absent from this tree |
AST fuzzer (amd_debug, targeted, old_compatibility) |
job ERROR having published nothing: the container passed the server's tracked ceiling (current RSS: 56.99 GiB, maximum: 46.24 GiB), every post-fuzz liveness probe returned Code: 241, and the job was then cancelled, so the CI database holds 0 rows for it |
#116782 (mine, open) |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
job-level container memory abort with no failing test. #117202 is present in this tree and is deliberately not linked as the owner: it cleared shards 2/6 and 5/6 outright, while 6/6 still fires on 13 of 13 post-fix master commits |
no fixing PR exists yet. A fix task holds the 6/6 residual; its investigation is complete and it is blocked on the integration-test capacity decision I put to the maintainers at #115963 (comment). Its fixing-PR link will be posted here when one opens |
None of the three is PR-caused. This PR changes Parquet float statistics pushdown plus its own
05045 stateless test, and each failure fires on trees that do not contain that change.
On the 03707 row: the failing job ran from 19:23:27Z to 20:31:40Z and #117364 merged at
22:05:00Z, so this run predates the fix by more than an hour and compare reports the head
diverged from that merge commit. I am not merging master here purely to re-run CI, to keep the
review load down. The row clears when the branch next picks master up.
On the AST fuzzer row: the fuzzer itself finished its own time budget normally (exit code 143
from its timeout wrapper after a full pass), so the red is the server's memory state afterwards,
not a fuzzer finding. The twin AST fuzzer (amd_debug, targeted) arm and five sibling arms are all
success on this head, each with CI database rows. #116782 bounds that container with
--memory=physical_memory() - 8 GiB and its description records the same shape at
current RSS: 57.14 GiB against maximum: 46.18 GiB.
On the /docker row: investigation of the 6/6 residual is complete and is blocked on an owner
decision about integration-test capacity, which I put to the maintainers at
#115963 (comment). The memory breakdown
from the failing jobs' dmesg-follow.log shows 33 clickhouse processes holding 35.5 to 37.3 GiB,
88 to 93 percent of the 40.20 GiB anon against the 40.78 GiB /docker cap, with exactly one gdb
alive, so #117202 works as designed and there is no leak and no offending module. Every remaining
lever is either that capacity decision or gives up the shutdown stack dump on a genuine hang, so I
am not picking one unilaterally.
Fast test, Style check, Bugfix validation, Config Workflow and Finish Workflow are all
OK on this head. PR is the praktika aggregator: it reports the rows above and carries no
separate defect.
Session id: cron:our-pr-ci-monitor:20260831-223000
Resolves a conflict in KeyCondition.cpp. Both sides added helper functions at the same spot before checkInHyperrectangle, so the resolution keeps both: this branch's setMayMatchHiddenNaN/anyBoundsMayHideNaN and master's rangeOfKeyColumnMayHoldNull/atomIsNullForNullArgument plus the two KeyCondition::mayReadNullKeyValue overloads from ClickHouse#118706. The two widenings are independent. mayReadNullKeyValue is a separate pass the caller runs over the RPN and only relaxes can_be_false for a NULL key value; the bounds_may_hide_nan mask is threaded into checkInHyperrectangle and relaxes contains/can_be_false for bounds that excluded NaN. Neither reads the other's state. The atom bodies inside checkInHyperrectangle merged without conflict and were re-checked against master's restructured FUNCTION_IN_RANGE handling: master now resolves the range through key_range_ptr/key_range_storage for a monotonic function chain, while key_column stays element.getKeyColumn(), so the mask is still indexed by the source key column position it is built for.
When a Parquet float column's min/max statistics exclude a NaN, the row is not described by the bounds, so it is not described by the image of those bounds either. checkInHyperrectangle compares the atom's range against that image whenever the element carries a monotonic function chain, and a chain can map the hidden row to a value the image does not cover: sign maps the bounds -5, -5 to -1, -1 while mapping NaN to 1, so the atom looks impossible for the granule and both the row group and its pages are dropped although the row matches. The existing bounds_may_hide_nan handling only clears `contains`, which is the whole answer while the atom is compared against the bounds themselves, because no ordering comparison against a finite constant is true for a NaN. Once a chain intervenes the atom can also be true outside the bounds, so give up `intersects` as well. Keyed on both the mask and a non-empty chain, so an integer column and a chain-free float atom keep pruning. The mask handling becomes an independent `if` rather than a third `else if`: the two arms above it describe the bounds we were given, this one describes rows the bounds never described, and a chain can produce a NaN endpoint from finite bounds (sign(val) * inf + inf maps -5, -5 to NaN, NaN while mapping the hidden row to +inf), in which case the first arm fires and a chained arm below it would never run. The promotion is a no-op for chain-free atoms, because both NaN arms already clear `contains`. Tests: four arms in 05045_parquet_nan_statistics_pruning covering the row group layer, the page layer, Float32, and a chain whose image of the bounds is NaN; plus a control that a chain over an integer column still prunes. All four fail without this change. Known open item, tracked in the pipeline task, not in this message's scope: this widening also drops row group pruning for a Float64 Parquet column read as Float32, which 04545_parquet_minmax_stats_type_mismatch pins, because a narrowing float cast is itself a monotonic chain. Co-Authored-By: Claude Opus 5 <[email protected]>
CI finish ledger - 7b83309Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head: 176 checks, 155 pass, 18 skipped, 2 failed,
Session id: cron:our-pr-ci-monitor:20260915-190256 |
Parquet computes float min and max from non-NaN values only, so the bounds alone cannot tell a column that holds no NaN from one whose NaNs were skipped. The format closes that gap with a count, and `parquet.thrift` makes writing it mandatory: "The nan_count field must be set for floating point types, even if it is zero." `StatisticsNumeric` accumulated only min and max, so every float column ClickHouse wrote left the field unset, and every reader then had to assume a NaN might be hiding behind the bounds. The Parquet reader here is one such reader: it builds `bounds_may_hide_nan` from `nan_count`, so it treated every float column in every file ClickHouse produces as possibly NaN-holding, and the previous commit's widening therefore cost those files their chain-based row group pruning. That is the open item the previous commit noted, which `04545_parquet_minmax_stats_type_mismatch` pins. With the count written, a NaN-free file says so and keeps pruning. The count is emitted both for the column chunk statistics and for the page index, which the reader consults separately, and it is set even when no min and max are written, because an all-NaN column has no bounds but still has a count. The dictionary fallback discards the encoded column and re-encodes it from row zero; re-accumulating min and max over the same rows is idempotent, but a sum is not, so both statistics accumulators are cleared there. Tests: two arms in 05045_parquet_nan_statistics_pruning asserting that a NaN-free float column keeps chain-based pruning, one at the row group layer and one at the page layer. Both read rows without this change. Co-Authored-By: Claude Opus 5 <[email protected]>
The reader distinguishes three states of a float column's nan_count statistic: absent, zero, and non-zero. Absent means the writer reported nothing, so a NaN may sit outside the bounds and chain-based pruning has to be given up; only an explicit zero re-enables it. That is the state of every file an older ClickHouse or another writer produced. Until the previous commit it was also the state of every fixture in this test, so the __isset conjunct that recognises it was covered for free. Writing nan_count moved all of them into the zero and non-zero states, which left the absent state with no oracle in the same commit that made it load-bearing. Simplifying the check to `nan_count != 0`, which reads as harmless because thrift default-initialises the field to zero, then restores the original wrong result for all those files with a fully green suite. The fixture is three rows written by a build whose writer does not emit the field, embedded as base64 because no reachable writer produces it any more: the same bounds as the negative NaN fixture, min = max = -5, no nan_count and no ColumnIndex.nan_counts. Three arms cover the row group layer, the page layer and a monotonic chain, all folded into batches the test already runs, so the number of client invocations is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
The count that the previous commit writes has no SQL oracle: both reader sites only compare it against zero, and `ParquetMetadataInputFormat` emits a fixed five-field statistics tuple, so an inflated, zeroed or misaligned count changes no query result. Arrow's `parquet::Statistics` and `parquet::ColumnIndex` do not expose a NaN count either, so both cases deserialize the file's own bytes with the writer's counterpart, `deserializeThriftStruct`: the footer's `parq::FileMetaData`, then `parq::ColumnIndex` and `parq::OffsetIndex` from the offsets it records. `WriteNanCountStatistics` covers the four states a float column can be in: a column with NaNs among finite values (exact count, bounds from the finite values only), a NaN-free one (the count is written and is zero, which is what keeps such files prunable), an all-NaN one (a count, no bounds, and therefore no column index), and an integer column (no count at all). NaN counts differ per page, so a misaligned `nan_counts` moves an entry rather than only the total. `WriteNanCountAfterDictionaryFallback` is the case a SQL test cannot reach. It writes a column whose first pages repeat a few values and whose later values are all distinct, with a small `max_dictionary_size`, so the dictionary overflows several pages in and the writer re-encodes the column from row zero. The fallback is observed rather than assumed: the chunk's encodings must not contain `RLE_DICTIONARY`. The same data with the default limit keeps its dictionary and must give byte-identical counts. Reverting both `clear()` calls at the restart makes the chunk count 46 instead of 36 and the first page 5 instead of 1; reverting only the chunk accumulator makes it 42 with every page still exact; reverting only the page accumulator makes it 40. The control file is unaffected in all three. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewReviewed cold against the resulting code, then adversarially by a second model. Rounds 1 and 2 are in Round 3 (2 adversarial findings, 4 from the cold read) - both majors fixed.
Round 4 (1 adversarial finding, raised in two consecutive rounds, plus 1 from the cold read).
Round 5 (1 adversarial finding, 5 from the cold read). The two majors above were not re-raised.
Verified independently while reading, not taken from the implementation's report: |
CI finish ledger - e81570cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither failure is specific to this pull request: the same denied Session id: cron:our-pr-ci-monitor:20260916-053048 |
|
@groeneai please check CI and resolve the conflict. |
Resolves one conflict in src/Processors/Formats/Impl/Parquet/Write.cpp. Master's ClickHouse#120027 (061fa0b) independently added the same page_statistics.clear() / total_statistics.clear() at the dictionary fallback site, plus reset_size_statistics(); its side is a strict superset of the branch's hunk, so master's version is taken verbatim and this branch no longer carries that hunk. KeyCondition.cpp/h and Reader.cpp auto-merged. Verified by hand that the bounds_may_hide_nan check still sits after master's NaN-bound handling in the restructured FUNCTION_IN_RANGE arm, where key_column is still element.getKeyColumn(), so the mask stays indexed by the source key column position it is built for.
|
Both done. Conflict. Merged master. One conflict, in Verified on the merged tree before pushing: CI. Running now on One thing worth flagging: |
CI finish ledger - 61d3c7bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
This is the finish ledger promised when the conflict resolution was pushed to Session id: cron:our-pr-ci-monitor:20260921-173143 |
CI finish ledger - 2f32787Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260922-020058 |
|
Dear @scanhex12, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Related: #118110
Related: #107074
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed reading a Parquet file whose float column holds a
NaN: row group and page pruning silently dropped rows matching predicates such asval != 5,val NOT IN (5),val IN (nan)orsign(val) = 1, because Parquet computes float min/max from non-NaNvalues only. ClickHouse now also writes thenan_countstatistic that the format makes mandatory for floating point columns, so the files it writes keep full pruning.Description
A Parquet file whose float column holds a
NaNsilently returns wrong results at default settings: Parquet computes float min/max from non-NaNvalues only, so a row group holding[5.0, 5.0, nan]advertisesmin = max = 5.KeyCondition::checkInHyperrectangletreats containment in those bounds as proof that every row satisfies an atom, which a negated atom then inverts into a wrong prune. Set atoms fail the other way: membership treatsNaNas equal toNaN(nan IN (nan)is1,nan = nanis0). And under a monotonic chain the atom is compared against the chain's image of the bounds, which the hidden row's image can escape:signmaps-5, -5to-1, -1andNaNto1.checkInHyperrectanglenow takes an optional per-key-column mask marking bounds computed withoutNaNs; the reader builds it fromStatistics.nan_countandColumnIndex.nan_countsand passes it at four pruning sites. Pruning is given up only for a negated range or set atom whose bounds are contained, a set atom holding aNaN, a tuple or chained set atom, and a range atom carrying a function chain.The mask is a may, and this writer never emitted
nan_count, althoughparquet.thriftrequires it for float columns "even if it is zero", so it fired for NaN-free files too. It is now written, for the column chunk and the page index, so files ClickHouse writes keep pruning, with04545_parquet_minmax_stats_type_mismatchunchanged here.Reproduced on 26.8, 26.3 and 25.8. Found while working on #107074, which fixes the same invariant for MergeTree; #118110 stays open for that, hence
Related:notCloses:.Accepted cost, carriers left alone, and residuals
Accepted cost. A float column in a file written without
nan_countloses chain-based pruning, including the implicit cast of a width-mismatched read. The mask is cleared only by an explicitnan_count == 0, so that is every file an older ClickHouse or another writer produced without the field, not a rare shape. Narrowings: only the Parquet reader builds this mask; float columns only; chain-free atoms keep pruning; every file this writer produces is exempt.Not covered. A negated float comparison (
NOT (val < 6.), chain or not) is still pruned wrongly: inversion push-down folds it into a positive range before this guard runs, so no statistic can rescue it. #107074 declines that fold for float operands, with no code here.Carriers left alone. MergeTree part minmax, the minmax and
setskip indexes and the column-statistics part pruner are already in #107074. Iceberg data-file pruning reaches this guard throughmayBeTrueInRangeand is untouched here: it would also neednan_value_counts, which is in the manifest schema but unread (the manifest-list summaries already guard oncontains_nan); happy to do that separately.StorageHiveowns its own call sites, exposure confined toFloat32. Native ORC is unaffected (measured): liborc does the comparison. The set arm widens for any chained set atom, not only a NaN-hiding one; that costs nothing for files this writer produces, so it stays blunt.Residual, offered separately. Six monotonicity providers (
intExp2,intExp10,toDate, ...) reportis_monotonicfor aNaNendpoint then throw when the value is applied, soWHERE intExp2(float_pk) > 1000over a MergeTree table holding aNaNfails during index analysis. Nothing here evaluates a synthetic value and the un-pruned query throws too, so no wrong result;a8f3ba2262824is the precedent. Same class nihalzp is reviewing on #107074.Workflow [PR]
Sync PR [sync-upstream/pr/116725]