Skip to content

Rewrite in Rust - #100272

Closed
alexey-milovidov wants to merge 119 commits into
masterfrom
replace-h3-with-rust-h3o
Closed

alexey-milovidov wants to merge 119 commits into
masterfrom
replace-h3-with-rust-h3o

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 21, 2026 •

Copy link
Copy Markdown
Member

Replace the H3 C library backend with a Rust wrapper around h3o.

A new Rust crate (rust/workspace/h3o/) wraps the h3o library and exposes the H3 C API via extern "C" FFI, so existing C++ callers keep working unchanged. The C h3 contrib has been removed; h3o is now the sole backend.

Performance comparison (10M rows, best of 5 runs):

geoToH3 res15: 29160 ms → 3918 ms (7.4x faster)
geoToH3 res9: 20140 ms → 3221 ms (6.3x faster)
h3ToGeo: 31678 ms → 6405 ms (4.9x faster)
h3ToParent: 29337 ms → 3992 ms (7.3x faster)
h3ToGeoBoundary: 8352 ms → 2012 ms (4.2x faster)
h3CellAreaM2: 16768 ms → 5183 ms (3.2x faster)
h3IsValid/h3kRing/h3Distance/h3PointDistM: ~same (ClickHouse overhead)

User-visible behavior changes from the backend swap:

  • Functions that return a set of cells (h3kRing, h3HexRing, h3ToChildren, h3PolygonToCells, ...) emit the cells in h3o's iteration order; the result set is unchanged but element order differs from the C library.
  • The average per-resolution metric functions (h3HexAreaM2, h3HexAreaKm2, h3EdgeLengthM, h3EdgeLengthKm) are exact copies of the C H3 library's lookup tables, so their outputs are byte-for-byte identical to the C backend — these functions do not change. (The current C backend already returns the H3 v4 average-metric values, e.g. h3EdgeLengthKm(0) = 1281.256011; the older H3 v3 values such as 1107.712591 are no longer the C backend's behavior, so there is no change to restore here.)
  • Floating-point outputs from the computed per-cell / per-edge / geometry functions (h3CellAreaM2, h3CellAreaRads2, h3ExactEdgeLengthM/h3ExactEdgeLengthKm/h3ExactEdgeLengthRads, h3ToGeo, h3ToGeoBoundary, ...) differ in the last few ULPs from the C library because the underlying formulas are computed in Rust with slightly different rounding.
  • h3PolygonToCellsWithContainment no longer supports containment mode 3 (CONTAINMENT_OVERLAPPING_BBOX), which the C library implemented as an over-inclusive bounding-box mode; h3o has no equivalent, so passing mode 3 now raises an exception. Modes 0 (CONTAINMENT_CENTER), 1 (CONTAINMENT_FULL), and 2 (CONTAINMENT_OVERLAPPING) remain supported.
  • stringToH3 now follows permissive sscanf-style parsing and returns 0 instead of throwing for inputs that contain no hex digit ('xyz', '', '-z') or that parse to a zero value ('0', '000', '0x'). On the old C-library backend these inputs threw. The longest valid hex prefix is still consumed and trailing garbage is ignored (so 'foo' parses to 0xf), and the result is not validated to be a real H3 cell — use h3IsValid for that.
  • Because the backend is now the Rust h3o crate, the H3 functions are built only when Rust is enabled. ENABLE_H3 defaults to OFF whenever Rust is unavailable: on platforms without Rust (for example, FreeBSD) or in builds configured with -DENABLE_RUST=OFF, the H3 functions (geoToH3, h3*) are no longer compiled. This differs from the old C-library backend, which did not depend on Rust.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Improve the performance of H3 functions by replacing the H3 C library backend with a Rust wrapper around h3o. Cells in array-returning functions (h3kRing, h3HexRing, h3ToChildren, h3PolygonToCells, ...) may be emitted in a different order, floating-point outputs of the computed cell-area, exact-edge-length, and cell-to-geo functions can differ in the last few ULPs (the average per-resolution area/edge-length functions h3HexArea*/h3EdgeLength* are exact copies of the C library tables and are unchanged), and h3PolygonToCellsWithContainment no longer supports containment mode 3 (CONTAINMENT_OVERLAPPING_BBOX); modes 0, 1, and 2 remain supported. stringToH3 now uses permissive sscanf-style parsing and returns 0 instead of throwing for inputs with no hex digit ('xyz') or that parse to zero ('0', '0x'). Because the backend is now the Rust h3o crate, the H3 functions are built only when Rust is enabled: on platforms without Rust (for example, FreeBSD) or in -DENABLE_RUST=OFF builds, the H3 functions are no longer available.

Add a Rust wrapper crate (`rust/workspace/h3o/`) around the `h3o` library
that exposes all H3 C API functions via `extern "C"` FFI. The wrapper is
API-compatible with the existing `h3api.h` header, so no C++ function code
needs to change.

The new `ENABLE_H3O` CMake option (OFF by default) switches the H3 backend
from the C library to the Rust implementation. When enabled, the C H3
library is automatically disabled to avoid symbol conflicts.

Performance comparison (10M rows, best of 5 runs):

  geoToH3 res15:      29160 ms → 3918 ms  (7.4x faster)
  geoToH3 res9:       20140 ms → 3221 ms  (6.3x faster)
  h3ToGeo:            31678 ms → 6405 ms  (4.9x faster)
  h3ToParent:         29337 ms → 3992 ms  (7.3x faster)
  h3ToGeoBoundary:     8352 ms → 2012 ms  (4.2x faster)
  h3CellAreaM2:       16768 ms → 5183 ms  (3.2x faster)
  h3IsValid/h3kRing/h3Distance/h3PointDistM: ~same (ClickHouse overhead)

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

clickhouse-gh Bot commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c1896fb]

Summary: ✅


AI Review

Summary

This PR replaces the H3 C backend with the Rust h3o wrapper and documents several behavior changes. Most previously raised wrapper, build-gating, polygon, and stringToH3 issues are addressed in the current code, but one compatibility issue remains: the average H3 area/edge metric functions still change materially while the PR text describes only ULP-level floating-point drift.

PR Metadata
  • The selected Performance Improvement category is incomplete for the current change. Unless the incompatible H3 metric changes are restored or gated, the category should be Backward Incompatible Change.
  • The changelog entry is present, but the phrase that floating-point outputs differ only "in the last few ULPs" is not accurate for h3HexArea* / h3EdgeLength*. Suggested replacement:

Replace the H3 backend with the Rust h3o library, improving H3 function performance. This changes user-visible compatibility: h3HexArea* and h3EdgeLength* return H3 v4 average metric values (for example, resolution 0 edge length changes from 1107.712591 km to 1281.256011 km), array-returning functions may emit cells in a different order, h3PolygonToCellsWithContainment rejects mode 3, stringToH3 follows permissive sscanf-style parsing and can return 0 instead of throwing, and H3 functions are unavailable when Rust is disabled or unavailable.

Findings

⚠️ Majors

  • [rust/workspace/h3o/src/lib.rs:762] h3HexArea* / h3EdgeLength* no longer preserve the legacy ClickHouse H3 C backend metric tables. The diff changes h3EdgeLengthKm(0) from 1107.712591 to 1281.256011 and h3HexAreaKm2(0) from 4250546.848 to 4357449.416078383, which is a material semantic change, not last-ULP drift. Existing queries that rely on these average metrics will produce different results after upgrade. Restore the legacy tables/formulas, gate the new semantics behind a compatibility setting, or explicitly classify and document this as a backward-incompatible change. I reopened the existing bot-authored inline thread for this issue.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: resolve the average metric compatibility issue by preserving/gating the old values, or update the PR category and changelog so the substantial h3HexArea* / h3EdgeLength* result changes are clearly released as backward-incompatible.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Mar 21, 2026
Comment thread rust/workspace/h3o/src/lib.rs Resolved
alexey-milovidov and others added 2 commits March 21, 2026 12:08
Handle `0x` prefix and trailing `L` suffix in `stringToH3` to maintain
backward compatibility with legacy H3 string formats like
`0x85283473fffffffL`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread rust/workspace/CMakeLists.txt Resolved
alexey-milovidov and others added 2 commits March 21, 2026 12:47
The previous vendor was incomplete — it was missing std library
dependencies needed for sanitizer builds (`-Zbuild-std`). Run the
full `vendor.sh` script which vendors from all required sources.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Change `ENABLE_H3O` default from OFF to `${ENABLE_LIBRARIES}` so that
the Rust h3o implementation is used automatically when the Rust
toolchain is available, matching the behavior of other Rust components
like PRQL, skim, and polyglot.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread contrib/h3-cmake/CMakeLists.txt Resolved
The h3o library uses more precise values from the H3 v4 specification
for average hexagon areas and edge lengths. Update test reference files
to match the new values.

Affected functions: `h3HexAreaKm2`, `h3HexAreaM2`, `h3EdgeLengthKm`,
`h3EdgeLengthM`, `h3EdgeAngle`, and tests involving these.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread rust/workspace/h3o/src/lib.rs Resolved
Pin prqlc, polyglot-sql, zerocopy, and other existing crates to their
master versions. The previous lockfile was generated from scratch by
`cargo generate-lockfile` which upgraded these unintentionally, breaking
PRQL unit tests and potentially causing other issues.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread rust/workspace/h3o/src/lib.rs Resolved
The vendor submodule and Cargo.lock now have prqlc 0.13.10,
prqlc-parser 0.13.10, and all other existing crates at their exact
master versions. Only h3o and its dependencies are added.

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

Copy link
Copy Markdown
Member Author

Curious, why rewrite in Rust introduced crashes in almost every check?

- Fix CMake ordering: declare `ENABLE_H3O` option in
  `contrib/h3-cmake/CMakeLists.txt` before the guard check, since
  `contrib/` is processed before `rust/` where it was previously
  declared. The C H3 library is now correctly skipped when h3o is
  enabled.

- Fix `stringToH3` backward compatibility: return the raw parsed u64
  value without validating it as a `CellIndex`. The original C H3
  `stringToH3` accepted any hex string; our implementation was too
  strict, causing exceptions for valid hex strings that aren't valid
  cell indexes (e.g., edge indexes or truncated values).

- Add H3 index normalization: h3o rejects indexes with non-7 unused
  digit bits, while the C H3 library was lenient. Added
  `normalize_h3_index` that sets unused digit positions to 7 before
  passing to h3o. Validation functions (`isValidCell`,
  `isValidDirectedEdge`) use strict mode to match C library behavior.

- Add bounds checking in `gridRingUnsafe`, `gridDiskUnsafe`, and
  `gridDisk` to prevent buffer overflows if h3o iterators produce more
  elements than expected.

- Update test references for h3o values: `02292_h3_unidirectional_funcs`
  (edge function results with normalization), `02223_h3_test_const_columns`
  (restore missing `h3HexRing` output lines), and `03595_funcs_on_zero`
  (h3o uses H3 v4 values for edge lengths and hex areas).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread rust/workspace/h3o/src/lib.rs Resolved
Comment thread contrib/h3-cmake/CMakeLists.txt Resolved
alexey-milovidov and others added 2 commits March 21, 2026 21:18
The h3o library computes `h3CellAreaM2` and `h3CellAreaRads2` with
slightly different precision than the C H3 library. Update the test
reference to match h3o output.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread rust/workspace/CMakeLists.txt Resolved
The FixedString(16) lines containing binary murmurHash3_128 output had
their raw bytes replaced with UTF-8 replacement characters (U+FFFD)
during the merge with master. Restore the original binary content from
master while keeping the h3o precision updates for `h3CellAreaM2` and
`h3CellAreaRads2`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread rust/workspace/h3o/src/lib.rs Resolved
alexey-milovidov added a commit that referenced this pull request Mar 22, 2026
The H3 C library fork (github.com/ClickHouse/h3) was on v3.7.1 with
2 ClickHouse-specific range-check patches. Upstream H3 v4 already
includes equivalent validation in `_h3ToFaceIjk`, so the patches are
no longer needed.

Created a clean `clickhouse-v4` branch in the fork at upstream tag
v4.4.1 with no additional patches.

This fixes two known bugs in the v3 lookup tables:
- Average hexagon edge lengths were actually inradii (apothems), not
  edge lengths (uber/h3#201, fixed in
  uber/h3#749)
- Average hexagon areas naively divided Earth surface by total cell
  count without excluding pentagon areas (fixed in
  uber/h3#529)

The v4 API changed most functions to return `H3Error` with results via
output parameters. Updated all 27 wrapper files in `src/Functions/` to
use the new calling convention. Also updated function renames:
`exactEdgeLengthM` → `edgeLengthM`, `distanceM` →
`greatCircleDistanceM`, etc.

Updated 11 test reference files to reflect the corrected values.

Reference: #100272

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits March 27, 2026 00:00
…t-h3o

# Conflicts:
#	tests/queries/0_stateless/01043_h3_edge_length_m.reference
#	tests/queries/0_stateless/01044_h3_edge_angle.reference
#	tests/queries/0_stateless/02165_h3_edge_length_km.reference
#	tests/queries/0_stateless/03233_dynamic_in_functions.reference
#	tests/queries/0_stateless/03313_h3togeo_result_order.reference
#	tests/queries/0_stateless/03595_funcs_on_zero.reference
The H3 submodule was updated to expose the V3-style API where
`stringToH3` returns `H3Index` directly instead of taking an
output pointer. Also restore the documented behavior of returning
0 for invalid input instead of throwing an exception, which fixes
the backward compatibility test failure in
`test_backward_compatibility/test_functions.py::test_string_functions`.

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

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.40% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.60% -0.10%

Changed lines: Changed C/C++ lines covered: 76/82 (92.68%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Triage (continue-pr) — public CI is green (157/157 jobs, 0 failed). Two items handled:

1. AI Review ⚠️ Request changes — the metric-compatibility Major is moot. The flagged h3HexArea* / h3EdgeLength* change (1107.712591 → 1281.256011, 4250546.848 → 4357449.416078383) is not introduced by this PR. Those functions are exact table-lookup copies of the C library's average-metric tables, and the H3 v3 → v4 transition is already on master:

  • the merge base of this PR with master (7c45c76a4fd) already has 02165_h3_edge_length_km.reference = 1281.256011 and 02160_h3_hex_area_Km2.reference = 4357449.416078383;
  • this PR's net diff touches no area/edge-length reference file, and public CI runs SELECT h3EdgeLengthKm(0..15) / h3HexAreaKm2(0..15) directly and is green against those references.

So both the old C backend (current master) and the new h3o backend return identical values — there is nothing to restore or gate. I replied on the (now stale/outdated) inline thread with the full evidence and resolved it, and tightened the PR description so the ULP-drift note no longer lumps the exact-copy h3HexArea*/h3EdgeLength* tables in with the genuinely computed functions (h3CellAreaM2, h3CellAreaRads2, h3ExactEdgeLength*, h3ToGeo, h3ToGeoBoundary) — only the latter drift by a few ULPs.

The genuinely backward-incompatible behaviors (mode 3 rejection, stringToH3 permissive parsing, H3 unavailable without Rust) are already documented in the description; the changelog category is your editorial call.

2. CH Inc sync (tests failed) — unrelated flakes, rerun triggered. Sync PR ClickHouse/clickhouse-private#53185 merged and built cleanly; the 3 failures are all on Cloud-only configs (db disk / distributed cache / meta in keeper / SharedCatalog) that an H3-only change cannot affect, and every equivalent public job is green. I reran the failed jobs.

Did not re-merge master: the merge base is ~18h old (2026-06-29 16:35Z) and public CI is green.

@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Jul 4, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Jul 5, 2026
Bump contrib/h3 to pick up combined sincos + redundant-trig removal in
the lat/lng <-> H3 cell transforms. Bit-for-bit identical output; speeds
up h3ToGeoBoundary ~14%, h3ToGeo ~9-11%, h3CellArea* ~8%, geoToH3 ~3-4%.

Recovers the coordinate-transform speedups from the Rust h3o experiment
(ClickHouse#100272) while keeping the C library backend.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Jul 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

It appeared easier to optimize H3 instead.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Bump contrib/h3 to pick up combined sincos + redundant-trig removal in
the lat/lng <-> H3 cell transforms. Bit-for-bit identical output; speeds
up h3ToGeoBoundary ~14%, h3ToGeo ~9-11%, h3CellArea* ~8%, geoToH3 ~3-4%.

Recovers the coordinate-transform speedups from the Rust h3o experiment
(ClickHouse#100272) while keeping the C library backend.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `h3o` Rust implementation produces outputs that differ from the C
H3 library in:

- `h3ToGeo`: more precise floating-point representation
  (`37.795066168302554` vs `37.79506616830249`).
- `h3GetFaces`: face indices are returned in sorted order
  (`[1,2,6,7,11]` vs `[1,6,11,7,2]`).
- `h3PolygonToCells`: cells are returned in a different order
  (same set, different permutation).

CI report: ClickHouse#100272

Co-authored-by: Alexey Milovidov <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The v4 H3 C API reports parse errors via a return code, and the documented
contract of `stringToH3` is to return 0 for invalid input, not to throw.
After the `h3o` FFI was made API-compatible with the v4 C header, the C++
caller started throwing `ILLEGAL_TYPE_OF_ARGUMENT` whenever the library
reported a failure or returned 0, which broke
`test_backward_compatibility/test_functions.py::test_string_functions`:
the old installed binary happily returned the hex prefix of `'foo'` (15),
while this branch threw an unhandled exception on the upstream server.

Two changes restore the legacy behavior:

- `FunctionStringToH3::execute` now swallows the error code from the
  underlying `stringToH3` call. The output is pre-initialized to 0, so
  invalid input silently produces 0 in line with the function docs.

- The `h3o` FFI `stringToH3` now reads the longest valid hex prefix
  (`sscanf(str, "%" PRIx64, out)` semantics) instead of rejecting the
  whole string on the first non-hex byte. This matches both the v3 and
  v4 C H3 libraries, so both backends now agree on inputs like `'foo'`
  (parsed as `0xf`).

CI report: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The Rust `h3o` `gridDisk` iterator returns cells in a different
permutation than the legacy C `H3` library (center cell first, then
elements ordered by ring index). The set of returned indexes is
unchanged.

CI report: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The AST fuzzer produced a polygon whose coordinates triggered a panic
in the line-sweep intersection algorithm of the `geo` crate (a
transitive dependency of `h3o`):

    line intersection before first line: SPt(1.7453292519943294e-6, ...)

Because `maxPolygonToCellsSize` and `polygonToCells` are declared
`extern "C"`, the panic could not unwind across the C ABI boundary and
the server aborted with signal 6 ("panic in a function that cannot
unwind").

Wrap the polygon operations in `catch_unwind` and translate panics into
`E_FAILED`, so the C++ caller observes an empty result instead of an
abort. Add `04204_h3_polygon_to_cells_panic_on_degenerate.sql` as a
regression test using the original fuzzer query.

Reference report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100272&sha=e96a06161537e78ab2d2bb73bae82a79aa845c49&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

PR: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`h3CellAreaM2` and `h3CellAreaRads2` produce slightly different
floating-point values under the new Rust `h3o` backend (last-ulp
differences only). The new values are stable across amd/arm and all
sanitizer builds — verified via CIDB across all 30 reproducing CI runs.

The test itself is `Tests/03233_dynamic_in_functions` (not an H3-specific
test), which exercises Dynamic columns through a variety of functions.

CI report:
ClickHouse#100272
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…t flap

`h3CellAreaM2`, `h3CellAreaRads2`, and `h3ToGeo` produce slightly different
last-ULP Float64 values across `h3o` builds (e.g. release vs. coverage vs.
sanitizers). The PR was repeatedly chasing those bit patterns by editing
reference files, which kept breaking on a different shard each time.

Round the outputs in SQL instead, so the test asserts the precision actually
relevant to its purpose:
- `03313_h3togeo_result_order` rounds lat/lon to 10 decimals (the test only
  verifies the tuple order under `h3togeo_lon_lat_result_order`).
- `03233_dynamic_in_functions` rounds `h3CellAreaM2` to 4 decimals and
  `h3CellAreaRads2` to 16 decimals (this is a Dynamic-column dispatch test,
  not an H3 precision test).

CIDB confirms the only varying digit is the last one for these calls;
the chosen rounding precisions are stable across all observed builds.

CI report:
ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
After bdd7573 removed `-- Tags: no-fasttest` from
`04202_string_to_h3_sscanf_compat`, the test started failing in fasttest
with `Function with name 'stringToH3' does not exist (UNKNOWN_FUNCTION)`,
because the fasttest cmake configuration uses `ENABLE_LIBRARIES=0` and
no longer enables individual rust crates by default. The same issue
affected `04204_h3_polygon_to_cells_panic_on_degenerate`.

Add `-DENABLE_H3=1` to the fasttest cmake invocation so the `h3o` Rust
crate is compiled and the H3 functions are available in the fasttest
binary. This keeps the H3 test coverage in fasttest as intended.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100272&sha=bdd757333fc769f3ed969b69ac19a15bd3de255b&name_0=PR&name_1=Fast%20test
PR: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The per-row offset was assigned inside the `for (const auto & polygon :
multi_polygon)` loop. If a row's geometry is empty, that loop never
executes and `dst_offsets[row]` stays default-initialized to `0`,
breaking `ColumnArray` offsets invariants (offsets must be
non-decreasing).

Move the assignment out of the polygon loop so it runs exactly once per
row, including for empty geometries.

PR: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Fast test enables `ENABLE_H3=1` (added in this PR), which triggers
`clickhouse_import_crate(MANIFEST_PATH Cargo.toml)` in
`rust/workspace/CMakeLists.txt`. Corrosion runs `cargo metadata` over
the entire workspace, and the `wasmtime` workspace member references
`contrib/wasmtime/crates/c-api/Cargo.toml` via a path dependency.
Without the submodule, `cargo metadata` fails with
"failed to load manifest for dependency `wasmtime-c-api-impl`".

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100272&sha=669d6eebc2ec08dc3ce29f3503c7f63b489ba454&name_0=PR&name_1=Fast%20test
PR: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The original `catch_unwind` guards in `maxPolygonToCellsSize` and
`polygonToCells` were added when `h3o` 0.6 / `geo` 0.28 panicked in the
line-sweep intersection algorithm on AST-fuzzer-generated coordinates.
`h3o` 0.9.5 now validates exterior coordinates inside `TilerBuilder::add`
and surfaces invalid geometries as an `Err`, so the unwind guard is no
longer needed.

If a future `h3o` version regresses and starts panicking again, the fix
belongs upstream rather than as a workaround in the FFI shim.

The regression test `04204_h3_polygon_to_cells_panic_on_degenerate`
still passes: `h3o` returns `Err` for the fuzzer polygon, we translate
that to `E_FAILED`, and the C++ caller surfaces it as `BAD_ARGUMENTS`.

Addresses review:
ClickHouse#100272 (comment)
Upstream confirmation: HydroniumLabs/h3o#44

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The H3 hot loops call `maxGridDiskSize` per row to compute the output
array size; the function is trivial arithmetic (`3*k*(k+1) + 1`) yet
routing it through Rust FFI costs a function call per row.

Move it next to the other inlined trivial wrappers in `h3api.h` so the
compiler folds the computation directly into the surrounding loop body,
matching how the original H3 C library exposed it as a macro. The Rust
crate keeps an internal `max_grid_disk_size` helper used by `gridDisk`
and `gridDiskUnsafe`, but no longer exports a Rust symbol — there are
no remaining FFI callers.

Targets the `h3kRing` regression observed on `arm/1` in the performance
comparison:
ClickHouse#100272
(h3_functions #6: 23.3ms -> 34.8ms before this change)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The cross-compile flow invokes a second `cmake` configure inside
`PROJECT_BINARY_DIR/native` to build host-side helper tools (`protoc`,
`grpc_cpp_plugin`, `pre_compressor`). That sub-configure passes
`-DENABLE_RUST=OFF` to avoid overriding `.cargo/config.toml` with the
native toolchain. With the recent `ENABLE_H3=ON` requires `ch_rust::h3o`
check at the top level, the native sub-configure now fatal-errors with
"ENABLE_H3=ON was requested, but H3 (via Rust h3o) is unavailable"
because Rust (and therefore `ch_rust::h3o`) is disabled there.

The native helper build does not need H3 at all - it only builds the
host-side tools listed above. Pass `-DENABLE_H3=OFF` next to
`-DENABLE_RUST=OFF` so the check is satisfied in the sub-configure.

Only AMD builds were affected because CI runs on ARM hosts: ARM target
= host means no native sub-configure runs.

CI report: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Commit 0f21529 ("Fail configuration when `ENABLE_H3=ON` cannot be
honored") moved the `ENABLE_H3` option to the top-level `CMakeLists.txt`
and added a check that aborts configuration when `ENABLE_H3=ON` was
requested but `ch_rust::h3o` is unavailable.

The default for `ENABLE_H3` is `${ENABLE_LIBRARIES}`, which is `ON` on
all platforms, so cross-compile targets that force `ENABLE_RUST=OFF`
(`FreeBSD`, `riscv64`, `s390x`, `loongarch64`) hit the fatal error
during the top-level configure even when the user did not pass
`-DENABLE_H3=ON` explicitly.

Pre-populate `ENABLE_H3=OFF` in the cache for these targets in
`cmake/target.cmake` so the default no longer requests a backend that
the platform cannot provide. The fatal-error check still fires when
`-DENABLE_H3=ON` is passed explicitly on an unsupported target, so an
explicit H3 request is never silently ignored.

CI report: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`maxPolygonToCellsSize` and `polygonToCells` are `extern "C"` entrypoints,
so a panic in transitive geometry code (e.g. the `geo` line-sweep
intersection algorithm reached via `h3o`'s `TilerBuilder`) would cross
the FFI boundary and abort the server instead of returning an `H3Error`.

We previously had a real panic in exactly this code path (`h3o` issue 44).
While `h3o` 0.9.5 now validates polygon coordinates inside `TilerBuilder::add`
and surfaces invalid geometries as `Err`, treating future panics as
impossible is unsafe. Restore the `catch_unwind` guard so malformed
inputs always surface as a normal ClickHouse exception (`E_FAILED` ->
`BAD_ARGUMENTS`), mirroring the pattern already used in
`rust/workspace/prql/src/lib.rs`.

Addresses review feedback from `clickhouse-gh` on PR ClickHouse#100272.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Commit 933a2ed ("Disable `ENABLE_H3` on cross-compile targets without
Rust") pre-populated `ENABLE_H3=OFF` for cross-compile FreeBSD targets so
the top-level `FATAL_ERROR` guard does not trip during configure. That
fix is inside the `if (CMAKE_CROSSCOMPILING)` block in
`cmake/target.cmake`, so a *native* FreeBSD build (where
`CMAKE_CROSSCOMPILING=0`) still hits the guard with the default
`ENABLE_H3=${ENABLE_LIBRARIES}`.

Compute an `ENABLE_H3_DEFAULT` value that is `OFF` on `OS_FREEBSD` and
otherwise `${ENABLE_LIBRARIES}`, and use it as the option default. A
user who passes `-DENABLE_H3=ON` explicitly on FreeBSD still fails
loudly, so an explicit H3 request is never silently ignored.

CI report: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The header comment in `src/Functions/stringToH3.cpp`, the in-code
`FunctionDocumentation::ReturnedValue`, and the entry in
`docs/en/sql-reference/functions/geo/h3.md` all claimed that
`stringToH3` returns `0` "only when the input contains no hex digit at
all". That is not accurate: valid parses such as `"0"`, `"000"`, `"0x"`,
and `"+0x"` also succeed and produce `0`, so a `0` result is ambiguous
between a successful parse to zero and the no-hex-digit error path.

Reword all three places to state that `0` is ambiguous and must not be
treated as a definite invalid-input signal — `h3IsValid` is still the
correct way to verify the result.

CI report: ClickHouse#100272

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`ENABLE_H3_DEFAULT` previously defaulted to `${ENABLE_LIBRARIES}` on
non-FreeBSD platforms.  That meant a default configure with
`-DENABLE_RUST=OFF` (e.g. `cmake -DENABLE_RUST=OFF`, as documented in
`docs/en/development/build.md` and used by
`utils/auto-bisect/helpers/compile.sh`) still saw `ENABLE_H3=ON` and
immediately tripped the `FATAL_ERROR` guard for `ENABLE_H3 AND NOT
TARGET ch_rust::h3o`.

Extend the default branch with `NOT ENABLE_RUST` so configures that did
not opt into H3 explicitly keep working when Rust is disabled.  An
explicit `-DENABLE_H3=ON` together with `-DENABLE_RUST=OFF` still hits
the guard and fails loudly, preserving the existing behaviour for
intentional requests.

Addresses review comment on PR ClickHouse#100272.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hold Skip for auto-updating. pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants