Skip to content

Reject NaN and infinite polygon vertices at dictionary load time - #105583

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-polygon-dict-nan-inf-validation
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-polygon-dict-nan-inf-validation

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

The polygon dictionary load path called addNewPoint with whatever Float64 value the source column produced. SlabsPolygonIndex then sorted those x-coordinates with ::sort and deduped with std::unique, both of which are undefined when the input contains a NaN. The slab walker would later end up with edge endpoints that did not match sorted_x[l] / sorted_x[r], fire the invariant check at PolygonDictionaryUtils.cpp:188, and abort the server with a LOGICAL_ERROR (Error occurred while building polygon index. Edge ... but found ...).

The query-side path in IPolygonDictionary::extractPoints already rejects NaN and infinite components with BAD_ARGUMENTS. This change mirrors the same check on the build-side, in addNewPoint, so a malformed source table fails at load with a clear user-facing error instead of aborting the server inside the index builder.

tests/queries/0_stateless/04273_polygon_dict_nan_inf_rejected.sql covers both POLYGON_INDEX_EACH and POLYGON_INDEX_CELL, plus a follow-up clean reload to confirm a sanitised source still loads.

Local reproducer (before the fix this aborts the server in a debug build):

INSERT INTO src VALUES ([[[(0., 0.), (1., 0.), (nan, 1.), (0., 1.), (0., 0.)]]], 1);
SYSTEM RELOAD DICTIONARY d;

Surfaced by the server-side AST fuzzer mutating 04204_polygon_dict_bytes_allocated.sql into inserts like (cx, cy + nan).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=1b384725455cdbaa49114566ba6b6e25f15809ed&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_tsan%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):

Polygon dictionaries with LAYOUT(POLYGON_INDEX_EACH()) or LAYOUT(POLYGON_INDEX_CELL()) now reject source rows whose polygon vertex coordinates contain NaN or infinity at load time with BAD_ARGUMENTS, instead of aborting the server inside the slab index builder.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The polygon dictionary load path called `addNewPoint` with whatever
`Float64` value the source column produced. `SlabsPolygonIndex` then
sorted those x-coordinates with `::sort` and deduped with `std::unique`,
both of which are undefined when the input contains a `NaN`. The slab
walker would later end up with edge endpoints that did not match
`sorted_x[l]` / `sorted_x[r]`, fire the invariant check at
`PolygonDictionaryUtils.cpp:188`, and abort the server with a
`LOGICAL_ERROR` (`Error occurred while building polygon index. Edge ...
but found ...`).

The query-side path in `IPolygonDictionary::extractPoints` already
rejects `NaN` and infinite components with `BAD_ARGUMENTS`. Mirror the
same check on the build-side, in `addNewPoint`, so a malformed source
table fails at load with a clear user-facing error instead of aborting
the server inside the index builder.

Add `04273_polygon_dict_nan_inf_rejected` to lock the contract in for
both `POLYGON_INDEX_EACH` and `POLYGON_INDEX_CELL`, plus a follow-up
sanity reload to confirm a clean source still loads.

Reproducer (before the fix this aborts the server):
INSERT INTO src VALUES ([[[(0., 0.), (1., 0.), (nan, 1.), (0., 1.), (0., 0.)]]], 1);
SYSTEM RELOAD DICTIONARY d;

Surfaced by the server-side AST fuzzer mutating
`04204_polygon_dict_bytes_allocated.sql` into inserts like
`(cx, cy + nan)`. See CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=1b384725455cdbaa49114566ba6b6e25f15809ed&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_tsan%29
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(a) Deterministic repro? Yes:

CREATE TABLE src (polygon Array(Array(Array(Tuple(Float64, Float64)))), city_id UInt32) ENGINE = Memory;
INSERT INTO src VALUES ([[[(0., 0.), (1., 0.), (nan, 1.), (0., 1.), (0., 0.)]]], 1);
INSERT INTO src VALUES ([[[(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)]]], 2);
CREATE DICTIONARY d (...) ... LAYOUT(POLYGON_INDEX_EACH());
SYSTEM RELOAD DICTIONARY d;

On a debug build at master without this fix, this aborts the server with Logical error: Error occurred while building polygon index. Edge 0 is [nan, 0] but found [1, 1]. l = 3, r = 3 (signal 6).

(b) Root cause explained? Yes. IPolygonDictionary::loadData -> extractPolygons -> addNewPoint -> Data::addPoint stores polygon vertex Float64s directly into a bg::polygon. Each SlabsPolygonIndex ctor then calls uniqueX(polygons) which runs ::sort and std::unique over the x-coordinates. Both are undefined when the input contains NaN (NaN doesn't satisfy strict weak ordering, and NaN == NaN is false so std::unique never dedupes it). The slab loop in indexBuild then misroutes edges into edge_left / edge_right and the post-check sorted_x[l] != all_edges[i].l.x() || sorted_x[r] != all_edges[i].r.x() fires.

(c) Fix matches root cause? Yes. The fix rejects non-finite vertex components at load time, before they reach the index builder. This is the same boundary already used by the query-side path IPolygonDictionary::extractPoints (lines 423-429), so the dict's input contract is now symmetric on both ends.

(d) Test intent preserved? / new tests added? New test 04273_polygon_dict_nan_inf_rejected locks the contract for both POLYGON_INDEX_EACH and POLYGON_INDEX_CELL, including a follow-up sanity reload that confirms a clean source still loads. No existing test was modified.

(e) Demonstrated in both directions? Yes.

  • Before the fix: SYSTEM RELOAD DICTIONARY causes signal 6 with the Logical error: Error occurred while building polygon index. Edge ... trace (reproduced locally on the debug binary).
  • After the fix: same reload returns Code: 36. DB::Exception: PolygonDictionary input polygon vertex component must not be NaN. (BAD_ARGUMENTS) and the server continues serving queries. SELECT version() immediately afterwards still returns 26.6.1.1.

(f) Fix is general? Yes.

  • All polygon vertices flow through the single addNewPoint entry point (line 615), called from both handlePointsReprByArrays and handlePointsReprByTuples (InputType::SimplePolygon and InputType::MultiPolygon both end up here). No other call sites add polygon points.
  • The symmetric query-side validation was already in extractPoints; this PR plugs the only remaining hole.
  • Upstream: Float64 columns are allowed to store NaN and infinity (IEEE 754 / SQL semantics), so we cannot reject this earlier without breaking unrelated functionality. The dict load boundary is the correct place to enforce the polygon-geometry input contract.

CIDB

check_name                                              cnt  last_seen
Stress test (experimental, serverfuzz, arm_tsan)        1    2026-05-21 17:55:40 UTC

Single hit in the last 90 days, triggered when the AST fuzzer mutated 04204_polygon_dict_bytes_allocated.sql (added 2026-05-20 by #105431) into inserts containing cy + nan. No prior occurrences on other sanitizers / arches.

cc @groeneai

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @vitlibar — could you review? This adds NaN/Inf validation in the polygon dictionary load path to match the existing query-side validation in extractPoints, fixing a serverfuzz LOGICAL_ERROR (STID 3147-4f6a).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [98ac93f]

Summary: ✅


AI Review

Summary

This PR rejects non-finite polygon dictionary vertices during load, before they can reach the slab index builder. The validation is placed on the shared polygon point ingestion path, so the tuple path exercised by the regression test and the array path used by existing polygon dictionary tests go through the same guard; the changelog category and entry match the bug-fix scope.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Bugfix validation FAIL update. Investigated.

Bugfix validation (functional tests) reports Failed to reproduce the bug for 04273_polygon_dict_nan_inf_rejected on master @ d1761c82. From job.log:

[00:19:55] Run clickhouse-test on master with abort_on_logical_error.yaml
[00:21:00] Hung check failed: server is not responding
[00:21:09] Unable to locate any ClickHouse server process. It must have crashed or exited prematurely!
[00:21:14] Failed to reproduce the bug
[00:22:22] core.ExternalLoader.1587-316925.zst captured
[00:22:35] Failed to reproduce the bug

The master binary aborts inside the dictionary ExternalLoader thread (core dump confirms it), exactly where this fix lives. clickhouse-test records the run as SERVER_DIED, but bugfix_validate_check.py only treats Result.Status.FAIL as bug-reproduced, so the framework reports "not reproduced". The bug IS reproducing (LOGICAL_ERROR + signal 6 in SlabsPolygonIndex::indexBuild), the framework just cannot see this shape.

Same framework limitation we hit in:

Two options:

  1. Keep Bug Fix (user-visible misbehavior in an official stable release) and override the failing check. The bug is user-visible: any polygon dictionary fed NaN or Inf vertex coordinates aborts the server.
  2. Re-categorise to CI Fix or Improvement (changelog entry is not required) per PR Fix inconsistent AST formatting for CREATE TABLE with UNIQUE KEY and TTL #104968 precedent.

@vdimir @vitlibar, which do you prefer? I'll push the PR-body edit either way.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai check the failing tests

@groeneai

Copy link
Copy Markdown
Collaborator Author

Checked all failing tests on commit d1761c82:

  1. Bugfix validation (functional tests): known framework limitation. The bug is a LOGICAL_ERROR that aborts the server (signal 6). When the regression test runs against the master release binary, the server aborts so clickhouse-test returns SERVER_DIED, but bugfix_validate_check.py only counts Result.Status.FAIL as a reproduction. Same pattern as PR Add regression test for set index under MV layer type change (#89802) #105552 and PR Fix inconsistent AST formatting for CREATE TABLE with UNIQUE KEY and TTL #104968 (re-categorised to CI Fix per Allow parenthesized queries in EXPLAIN #100136 / Fix inconsistent AST formatting for array/tuple with tuple element access #96894 precedent). Pending decision from earlier comment: keep Bug Fix and override, or re-categorise to CI Fix or Improvement.

  2. Five Integration tests (...) failing on test_mysql_protocol/test.py::test_mysql_dotnet_client (amd_asan_ubsan db-disk-old-analyzer 2/6, amd_llvm_coverage 3/5, amd_msan 2/6, amd_tsan 2/6, arm_binary distributed-plan 3/4). All unrelated to this PR. Caused by PR Support C# client in postgres protocol #80785's Dockerfile WORKDIR /pg_testapp change making the MySQL test run the Npgsql PG client against the MySQL port. Reverted in master at 2026-05-22T08:46:35Z via Revert "Support C# client in postgres protocol" #105615. Rebasing this PR on master will clear these.

Plan: rebase on master to pick up the revert, then the only remaining failing check should be the Bugfix validation framework limitation, which still needs the category decision.

@Ergus Ergus self-assigned this May 22, 2026

@Ergus Ergus left a comment

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.

The fix is fine, I get just two minor details in the tests I think must be address before merging

CREATE TABLE polygon_src_nan
(
polygon Array(Array(Array(Tuple(Float64, Float64)))),
city_id UInt32

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.

Why not id, polygon to conventionally read ID first like in other tests?

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.

Reordered columns to put city_id first in 0e39d4693d1e. Now matches the conventional source-table layout (id first, then the array attribute).

(
polygon Array(Array(Array(Tuple(Float64, Float64)))),
city_id UInt32
) ENGINE = Memory;

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.

We do need a primary key right?

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.

Switched the source table to MergeTree ORDER BY city_id in 0e39d4693d1e. The dictionary itself already had PRIMARY KEY polygon; now the source table also has a primary key on the id column.

Address @Ergus inline comments on 04273_polygon_dict_nan_inf_rejected:
put the id column first to follow the conventional source-table column
order in other tests, and use a `MergeTree` source table with a primary
key on `city_id` instead of `Memory`. Dictionary definitions reference
attributes by name, so no other adjustments are needed.

Test still reproduces the original LOGICAL_ERROR (NaN / Inf vertex
crashes `SlabsPolygonIndex::indexBuild`) when the fix in
`PolygonDictionary::addNewPoint` is removed, and still passes with the
fix.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Ergus addressed both inline comments in 0e39d46:

  • Reordered the source table columns to put city_id first, matching the conventional source-table layout in other tests.
  • Switched the source table from Memory to MergeTree ORDER BY city_id so it has a primary key on the id column.

Verified the test still reproduces the original LOGICAL_ERROR before the fix and passes with it. Ready for re-review.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai merge with master

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim merged master into the branch. New HEAD 3a9ece9600150e8d91aaec340b43dc8a080b65bb. No conflicts. Diff vs master is unchanged (only src/Dictionaries/PolygonDictionary.cpp plus the 04273_polygon_dict_nan_inf_rejected test). CI will rerun.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai can you check the CI failures, are they related to this PR?

@groeneai

groeneai commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim both failures are unrelated to this PR.

Check Failure Attribution
AST fuzzer (amd_debug, targeted) LOGICAL_ERROR 'WhichDataType(const_type).isArray()' (STID 2508-2f0a) at KeyCondition.cpp:3315 Pre-existing trunk bug in KeyCondition::extractAtomFromTree. Same STID hit @Algunenano's closed PR #104231 (polygon-dict-memory-fixes) on 2026-05-18. The failing query uses a literal if(cond, Array_of_tuples, String) as the polygon argument, so the dictionary load-path validation added here cannot trigger it.
Bugfix validation (functional tests) The test runner was terminated unexpectedly Chronic infra. 96 hits / 45 distinct PRs in 30d (e.g. #105041 x12, #104419 x6, #105959 x3). 3 hits on this PR are runner retries on the same commit.

Regression test 04273_polygon_dict_nan_inf_rejected passed on every Stateless variant including 200/200 flaky check runs across asan/debug/msan/tsan, both planners, s3 storage, parallel replicas, DatabaseReplicated, and arm targeted. No PR-caused failure.

PR is approved and otherwise green.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai I've told you a million times to stop pinging me. Please make a special note about it. Do not ping @Algunenano for anything.

@Ergus

Ergus commented Jun 2, 2026

Copy link
Copy Markdown
Member

@groeneai get the updated changes in master (merge) and trigger CI again.

@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

@Ergus master merged in 98ac93f (clean, no conflicts). PR diff unchanged: PolygonDictionary.cpp +12, 04273 test + reference. CI re-running.

@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

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

Full report · Diff report

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: 98ac93f4b28fb7a3fc3eac71f18db14b4014576d

CI fully finished (Mergeable Check completed; 0 pending checks). No CIDB-recorded test failures in 2d.

No PR-caused failures. Awaiting maintainer decision (Ergus approved 2026-05-22; PedroTadim follow-up replied 2026-05-22).

Session: cron:our-pr-ci-monitor:20260604-213000

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Closing in favour of #106423 (alexey-milovidov, "Reject NaN and infinite coordinates in polygon dictionaries"). The src/Dictionaries/PolygonDictionary.cpp fix is functionally equivalent (same isNaN || isinf guards in addNewPoint, same BAD_ARGUMENTS); per @Ergus' comparison call, deferring to that PR. If the per-layout (POLYGON_INDEX_EACH / POLYGON_INDEX_CELL) split and clean-reload sanity check from this PR's 04273_polygon_dict_nan_inf_rejected test are worth keeping, I'll port them onto 04318_polygon_dict_nan_inf_coordinates as a tiny follow-up after #106423 merges.

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants