Skip to content

Reject NaN and infinite coordinates in polygon dictionaries - #106423

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix/polygon-dictionary-nan-inf-coordinates
Jun 6, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix/polygon-dictionary-nan-inf-coordinates

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

A polygon dictionary built from source data containing NaN or infinite point coordinates could fail the consistency check in SlabsPolygonIndex::indexBuild and throw a LOGICAL_ERROR ("Error occurred while building polygon index"). This was hit by the server fuzzer in the stress test on master.

Non-finite coordinates break the ordering assumptions of the scanline index construction: std::sort and std::unique over sorted_x give undefined results for NaN, and Float64 values that overflow to infinity when cast to the Float32 coordinate type corrupt the index the same way.

Query points are already validated for NaN/infinity in extractPoints, but the polygons used to build the index were not. The fix validates them in addNewPoint, the single chokepoint for both the tuple and array point representations, and rejects non-finite components with a BAD_ARGUMENTS exception instead of producing a logical error. Checking after the cast to the coordinate type also catches finite Float64 values that overflow to infinity.

Also fixes a double whitespace in the index-build error message.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=bb40bf2d712e3638ba51a89f9f64a05c5bfffbef&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_msan%29

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):

Fix a logical error when building a polygon dictionary from source data containing NaN or infinite point coordinates. Such coordinates are now rejected with a clear error.

🤖 Generated with Claude Code

Version info

  • Merged into: 26.6.1.437

A polygon dictionary built from source data containing `NaN` or infinite
point coordinates could fail the consistency check in
`SlabsPolygonIndex::indexBuild` and throw a `LOGICAL_ERROR` ("Error
occurred while building polygon index"). Non-finite coordinates break the
ordering assumptions of the scanline index construction (`std::sort` and
`std::unique` over `sorted_x` give undefined results for `NaN`, and
`Float64` values that overflow to infinity when cast to the `Float32`
coordinate type corrupt the index the same way).

Query points are already validated for `NaN`/infinity in `extractPoints`,
but the polygons used to build the index were not. Validate them in
`addNewPoint`, which is the single chokepoint for both the tuple and array
point representations, and reject non-finite components with a
`BAD_ARGUMENTS` exception instead of producing a logical error. Checking
after the cast to the coordinate type also catches finite `Float64` values
that overflow to infinity.

Also fix a double whitespace in the index-build error message.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=bb40bf2d712e3638ba51a89f9f64a05c5bfffbef&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_msan%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [34c8594]

Summary: ✅


AI Review

Summary

This PR rejects non-finite polygon dictionary source coordinates before building polygon indexes and adds regression coverage for NaN, infinity, and a finite Float64 value that overflows to Coord. The NaN and direct infinity paths are covered, but the overflow path is still validated only after the out-of-range narrowing conversion, so the promised BAD_ARGUMENTS exception is not guaranteed.

Findings

❌ Blockers

  • [src/Dictionaries/PolygonDictionary.cpp:621] The finite-overflow contract is still checked too late. handlePointsReprByArrays and handlePointsReprByTuples cast source Float64 values to Coord before addNewPoint tests std::isinf, and converting a value such as 1e39 outside the Float32 range is not defined by C++. The new check only works on targets that happen to produce infinity, so the PR can still fail to provide the promised BAD_ARGUMENTS exception before undefined behavior. Validate the original Float64 with std::isfinite plus explicit Coord bounds, then cast only after the value is known representable.
Final Verdict

Status: ❌ Block

Minimum required action: move polygon source coordinate validation before the Float64 to Coord narrowing conversion, while preserving the new regression coverage for the overflow case.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 4, 2026
@Ergus

Ergus commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

These changes are the same in: #105583
This is duplicated. Could we close it?

Maybe it worth checking if the tests here cover new edge cases

@Ergus Ergus self-assigned this Jun 4, 2026
alexey-milovidov and others added 2 commits June 5, 2026 14:10
… to 04318

Address review: the validation in `addNewPoint` runs after the cast to the
`Coord` (`Float32`) type, so a finite `Float64` coordinate that overflows to
infinity when narrowed (for example `1e39`) must also be rejected. Add a
dictionary-load case asserting `BAD_ARGUMENTS` for it, which locks in the
cast-after-validation ordering.

Also renumber the test from `04299` to `04318` to avoid the crowded `04299`
prefix after merging master.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged latest master (was 539 commits behind), addressed the review feedback, and verified the fix.

Review feedback: Added a third dictionary-load case covering a finite Float64 coordinate (1e39) that overflows to Float32 infinity when narrowed to Coord, asserting BAD_ARGUMENTS. This locks in the cast-after-validation ordering. Renumbered the test from 04299 to 04318 to avoid the now-crowded 04299 prefix.

Empirical verification (locally built binary, clickhouse local):

  • nan → BAD_ARGUMENTS "PolygonDictionary polygon point component must not be NaN"
  • inf → BAD_ARGUMENTS "...must not be infinite"
  • 1e39 → BAD_ARGUMENTS "...must not be infinite" (overflow-to-Float32-inf case)
  • valid polygon → returns the matched value

CI failures (both unrelated to this change):

  • 04239_streaming_combinations (amd_debug, distributed plan, s3 storage): flaky streaming-queries test, also failed on unrelated PR Randomize tests with DETACH/ATTACH table before query execution #96130; no dictionary code involved.
  • test_storage_delta::test_replicated_database_and_unavailable_s3: the assertion '123456' not in <output> fails by coincidence because the digest hash 9101234564970589296 contains the substring 123456 — a test-bug flaky assertion, independent of polygons.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, the 04239_streaming_combinations failure in Stateless tests (amd_debug, distributed plan, s3 storage, parallel) looks unrelated to this polygon-dictionary change (streaming queries on MergeTree, no dictionary code). It is flaky on master — it also failed on unrelated PR #96130. Could you investigate and provide a fix in a separate PR? Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106423&sha=c63e3b252e8a6bd504220f99031f9ba16a95ce09&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29

The other failure (test_replicated_database_and_unavailable_s3) is fixed in #106571.

throw Exception(ErrorCodes::BAD_ARGUMENTS,
"PolygonDictionary polygon point component must not be NaN");

if (std::isinf(x) || std::isinf(y))

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.

The overflow case is still checked after handlePointsReprByArrays and handlePointsReprByTuples have narrowed the source Float64 to Coord with static_cast<IPolygonDictionary::Coord>. For a value such as 1e39, that conversion is outside the range of Float32, so the behavior of the conversion itself is not defined by C++; this check only works if the compiler and target happen to produce infinity. That means the PR's promised BAD_ARGUMENTS exception for finite values that overflow to Coord is not guaranteed. Please validate the original Float64 with std::isfinite and explicit Coord bounds before narrowing, then cast only after the value is known representable.

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov, opened #106574 with a fix for the 04239_streaming_combinations flake.

Root cause: Test Regular Union Stream spawns SELECT a FROM t UNION ALL SELECT a FROM t STREAM against a table containing one pre-existing row (('started', 0)). Both UNION ALL sources emit one started line, but the test's read_until "$fifo_1" "started" returns after the FIRST started and then issues INSERTs. With no ordering guarantee between UNION ALL sources, the streaming side can emit a post-INSERT 0 into the FIFO before the regular side's started reaches stdout, producing started\n0\nstarted\n0\n1 instead of the reference started\nstarted\n0\n0\n1. distributed plan + s3 storage widens the scheduling-latency window, which matches where CIDB saw the diff (1 hit on this PR, 1 hit on PR #96130 in 30 days, 0 master hits in the same window).

Fix: extend read_until in streaming.lib with an optional target-count (defaults to 1, preserving existing callers) and wait for both started markers in the Test Regular Union Stream subtest before issuing INSERTs. Two-line diff in 04239_streaming_combinations.sh, three-line addition in streaming.lib.

Verified locally: 20/20 passes with --no-random-settings --no-random-merge-tree-settings, 1/1 with default randomization.

@Ergus

Ergus commented Jun 5, 2026

Copy link
Copy Markdown
Member

@groeneai Can you check this PR vs #105583?

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

@Ergus comparison done. The two PRs are functionally equivalent for the source fix (both add isNaN(x) || isNaN(y) and std::isinf(x) || std::isinf(y) guards in IPolygonDictionary::addNewPoint throwing BAD_ARGUMENTS, both after the static_cast<Coord> so they catch the 1e39 Float64-to-Float32 overflow case as well). Test-coverage delta is the only difference: this PR adds the 1e39 overflow case explicitly and fixes a double-space typo in PolygonDictionaryUtils.cpp; #105583's test (04273_polygon_dict_nan_inf_rejected) instead splits across POLYGON_INDEX_EACH and POLYGON_INDEX_CELL layouts plus a clean-reload sanity check.

Recommendation: close #105583 in favour of this PR, since alexey-milovidov is actively keeping it merge-ready. I'll close mine after this comment. If the layout-split / clean-reload cases are worth keeping, happy to port them onto 04318_polygon_dict_nan_inf_coordinates as a tiny test-only follow-up after #106423 merges.

Session: cron:clickhouse-ci-task-worker:20260605-162600

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 9/11 (81.82%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 6, 2026
Merged via the queue into master with commit 5a3a058 Jun 6, 2026
166 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/polygon-dictionary-nan-inf-coordinates branch June 6, 2026 00:24
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 6, 2026
pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Jun 6, 2026
The "Test Regular Union Stream" subtest spawns

    SELECT a FROM t_streaming_test UNION ALL SELECT a FROM t_streaming_test STREAM

against a table that already contains one row (`'started'`, `0`). Both
`UNION ALL` sources scan that row and emit one `started` line each, so the
expected output starts with two `started` lines before any post-INSERT
data arrives.

The test previously synchronized with `read_until "$fifo_1" "started"`,
which returns after the FIRST `started` is observed. There is no
ordering guarantee between the two `UNION ALL` sources, so the regular
side's `started` could still be in flight when the test issues its
`INSERT`s. When that happens the streaming side emits a post-INSERT row
(`0`) into the FIFO before the regular side's `started` reaches stdout,
producing `started\n0\nstarted\n0\n1` instead of the reference
`started\nstarted\n0\n0\n1`. The race widens under `distributed plan` +
`s3 storage` because of the higher and more variable scheduling latency
of those configurations, which is exactly where CI saw the failures
(report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106423&sha=c63e3b252e8a6bd504220f99031f9ba16a95ce09&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel%29
PR: ClickHouse#106423).

This patch extends `read_until` in `streaming.lib` with an optional
target-count argument (defaults to 1, preserving existing callers) and
updates the `Test Regular Union Stream` subtest to wait for both
`started` markers before issuing the INSERTs, so the post-INSERT rows
are appended in a deterministic position relative to both source rows.

Verified locally: 20/20 passes with random settings disabled, 1/1 with
default randomization.

Caused by: ClickHouse#96130
Related: ClickHouse#106423
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Development

Successfully merging this pull request may close these issues.

4 participants