Skip to content

Add spatial_bbox skip index for MergeTree geometry columns - #104437

Open
bacek wants to merge 133 commits into
ClickHouse:masterfrom
bacek:bacek/mergetree-spatial
Open

bacek wants to merge 133 commits into
ClickHouse:masterfrom
bacek:bacek/mergetree-spatial

Conversation

@bacek

@bacek bacek commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Part of making ClickHouse fastest spatial analytical engine on Earth https://github.com/bacek/chgeos/blob/main/BENCHMARK.md ;)

Adds a spatial_bbox skip index for MergeTree geometry columns, plus the shared bbox-extraction
infrastructure that also drives Parquet/GeoParquet row-group and page pruning and Iceberg manifest
pruning. A predicate opts in through IFunctionBase::isSpatialPredicate; the consumer this PR ships
is the LANGUAGE WASM UDF path (is_spatial_predicate = 1), alongside the native predicates that
already declare it.

What this pull request is {#what-this-pull-request-is}

This is the wiring: one bbox extractor (Common/GeoBbox.h), one place where a predicate says it
is spatial, and three consumers hooked up to it. It deliberately establishes the mechanism and its
safety property first, and takes the conservative answer everywhere the two could trade off.

Extraction is fail-closed throughout. Whenever the analysis cannot prove a granule is safe to
drop, pruning is disabled for the whole conjunction. Losing pruning costs time; skipping a granule
that would otherwise have raised is a wrong answer. So the extractor bounds only what it can bound
with certainty, and reports failure — not "no information" — for everything else.

The property the whole design rests on is index-neutrality: the answer must not depend on whether
the index ran. EXPLAIN, a fully pruned query, an empty part and a full scan must all agree, and the
tests assert that by comparison rather than against a fixed outcome.

What it deliberately does not do yet {#what-it-deliberately-does-not-do-yet}

The extractor is stricter than the predicates' runtime semantics in a few places, so some supported
queries get no pruning even though there is no exception to preserve:

  • pointInPolygon with validate_polygons = 0 accepts empty rings and empty-bound polygons at
    execution time; the extractor refuses to bound them.
  • The areal predicates correct an invalid constant polygon and evaluate it; the extractor validates
    constant polygon/multipolygon literals and WKB payloads the way parseConstPolygon does, and
    refuses the ones it rejects.
  • Variant/Dynamic arguments resolve their overload per row, so they keep a blunt veto that
    disables pruning for the whole conjunction.

All three are tracked in #117163.

These are all missed pruning, never wrong answers, and each is a deliberate call rather than an
oversight — the reasoning is recorded in the code at the branches that make it. Recovering the
pruning is worth doing, but it needs each predicate's accepted domain declared once and read by the
extractor, not a second copy of those semantics living inside the extractor: every divergence between
two copies turns a missed optimization into a wrong answer. That is follow-up work, on top of the
direction #116786 asks for.

Scope note {#scope-note}

Earlier revisions added several IFunction hooks letting each native geometry function declare its
accepted argument domain. Those are all gone; isSpatialPredicate is the only spatial surface left
on IFunction. Instead, polygonsIntersect and polygonsWithin state their domain once, in
checkArealPredicateArgumentTypes (Functions/geometryConverters.h), and apply it from
getReturnTypeImpl rather than from executeImpl. The rejection then happens during analysis, out
of reach of anything that removes rows — skip-index or primary-key pruning, PREWHERE, an empty
part — so the pruning infrastructure does not have to restate their accepted domain to stay
index-neutral.

That part is split out into #117567, which generalizes
it to every geometry function; this pull request carries an earlier copy of the same code and will
absorb it when that one lands.

Related: #116786
Related: #117163
Related: #117208
Related: #117567

Changelog category (leave one):

  • Performance Improvement

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

Adds spatial_bbox skip index for MergeTree geometry columns. The index stores a bounding box per granule and skips granules whose geometry cannot intersect the query geometry, reducing work for spatial predicates.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

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

clickhouse-gh Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [856511c]

Summary: ❌

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

AI Review

Summary

Adds the persistent spatial_bbox skip index for MergeTree geometry columns and shares bbox extraction with GeoParquet pruning. Reviewing PR head 856511c7ce603a9530e4d093a2511ae6dc7dcd49 leaves two blockers and one major: valid numeric geometry arguments can be discarded before pruning, the new index has no experimental gate, and the promised analysis-time argument validation is bypassed. These are the three existing open threads; no duplicate inline comments were posted.

Missing context / blind spots
  • ⚠️ No built ClickHouse binary or build directory was available for local runtime checks. Findings were verified by tracing the current implementation and its callers. The current PR workflow remains pending; Fast test passed, but full current-head stateless results were unavailable.
Findings

❌ Blockers

  • src/Common/GeoBbox.h:633: Geometry extraction must conservatively account for every geometry argument. isNonGeometryType recognizes unnamed coordinate tuples only when both coordinates are Float64, whereas pointInPolygon accepts native numeric coordinates and converts each polygon during execution. With a point (10.5, 10.5), a floating-point polygon spanning [0, 1] and an integer-coordinate polygon spanning [10, 11], the integer polygon is skipped. The remaining single bbox prunes the matching point, changing the count from 1 to 0. The shared GeoParquet extractor is affected too. Recognize all accepted numeric geometry carriers, or decline pruning whenever an argument cannot safely be classified; never prune from a partial argument list.

  • src/Storages/MergeTree/MergeTreeIndexSpatialBbox.cpp:271: The new persistent index and row-eliminating implementation are available without an experimental gate. The validator ignores attach and settings, so ordinary CREATE TABLE and ALTER TABLE ... ADD INDEX immediately enable the new format and pruning behavior. Add a default-off experimental setting, enforce it for both creation paths, and allow existing indexes to load when the setting is disabled.

⚠️ Majors

  • src/Functions/polygonsIntersect.cpp:46, also src/Functions/polygonsWithin.cpp:60: The new getReturnTypeImpl overload taking DataTypes does not establish the promised analysis-time validation. Normal analysis calls the inherited overload taking ColumnsWithTypeAndName; IFunction.cpp:1214 returns directly from the nonempty (Any, Any) -> UInt8 signature without invoking checkArealPredicateArgumentTypes. Rejected arguments therefore still reach execution, undermining the invariant on which the simplified extractor relies. Override the column overload to forward to the validated overload, as pointInPolygon does.
Tests
  • ⚠️ Add a focused result comparison with skip indexes enabled and disabled for mixed floating-point/integer polygon arguments, in both argument orders. Cover the shared GeoParquet path as well.
  • ⚠️ Add EXPLAIN QUERY TREE coverage over a nonconstant rejected argument for both areal predicates; runtime exception assertions alone do not prove analysis-time validation.
  • ⚠️ Exercise the experimental gate through both index-creation paths and verify that disabling it does not prevent loading existing tables.
Final Verdict

Status: ❌ Block. Account for every accepted geometry argument before pruning, gate the new persistent index, route normal analysis through the new validation, and add the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 8, 2026
@shankar-iyer shankar-iyer self-assigned this Jun 8, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 4, 2026
@bacek

bacek commented Jul 4, 2026

Copy link
Copy Markdown
Contributor Author

Good catch — fixed in 2ca838f: `extractQueryBbox` now only recurses through `and`, so a spatial predicate under `or` no longer produces a bbox used to prune granules.

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Dear @shankar-iyer, 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.

@bacek

bacek commented Jul 12, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov can you unleash CI on that PR, please?

@bacek
bacek force-pushed the bacek/mergetree-spatial branch from d5a4e93 to aceea47 Compare August 5, 2026 21:05
@bacek

bacek commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov can you unleash CI on that PR, please?

Ping

@melvynator melvynator removed the manual approve Manual approve required to run CI label Aug 11, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 11, 2026
bacek and others added 3 commits August 11, 2026 17:28
Adds a new skip index type `spatial_bbox` that stores a per-granule
bounding box for geometry columns (Point, Ring, Polygon, MultiPolygon
expressed as native CH `Tuple(Float64,Float64)` / nested arrays).

At query time the index extracts the query bounding box from spatial
predicates that satisfy `IFunctionBase::isSpatialPredicate()` (e.g.
`pointInPolygon`, `polygonsIntersect`) and prunes granules whose stored
bbox is disjoint from the query bbox.

- `MergeTreeIndexGranuleSpatialBbox` — stores `xmin/ymin/xmax/ymax` as
  four `Float64` values serialised with `writeBinaryLittleEndian`.

- `MergeTreeIndexAggregatorSpatialBbox` — accumulates the bounding box
  of every point in the geometry column over a granule using
  `BboxAccumulator` and `addFromGeoColumn` (handles ColumnConst,
  ColumnTuple, and nested ColumnArray).

- `MergeTreeIndexConditionSpatialBbox` — walks the `ActionsDAG` to find
  a spatial-predicate node referencing the indexed column with a constant
  geometry argument, extracts its bbox via `tryExtractConstGeoBbox`, and
  skips granules that are disjoint.

- `MergeTreeIndexSpatialBbox` — the factory class; uses `.idx2` as the
  storage extension and overrides `getDeserializedFormat` accordingly
  (the default base-class implementation only checks `.idx`).

Verified with `EXPLAIN indexes=1`: on a 4-granule table with two spatial
clusters the index correctly reduces evaluated granules to 2/4 for a
query whose bbox covers only one cluster.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Remove comment from anonymous namespace closing brace (style fix)
- Add storage parameter to getDeserializedFormat override to match base class
- Update call to indexFileExistsInChecksums with new storage parameter
extractQueryBbox recursed into every function's children regardless
of the function, so a spatial predicate nested under `or` (e.g.
WHERE pointInPolygon(geom, far_polygon) OR id = 1) could produce a
bbox that wrongly pruned granules where the other `or` branch would
have matched. Only recurse through `and`.
@bacek
bacek force-pushed the bacek/mergetree-spatial branch from 5f1d4cb to f8102ae Compare August 11, 2026 07:31
bacek added 2 commits August 11, 2026 18:57
master changed IMergeTreeIndex since this branch was authored:
constructor now takes StorageMetadataPtr, getDeserializedFormat takes
IMergeTreeDataPart instead of checksums/storage, and Creator/Validator
take an extra MergeTreeSettings argument. Update
MergeTreeIndexSpatialBbox and its registration in MergeTreeIndices.h
to match, following the MergeTreeIndexMinMax pattern. Also drop a
stale duplicate declaration of spatialBboxIndexCreator/Validator in
MergeTreeIndexSpatialBbox.h that caused overload-resolution ambiguity.
system.data_skipping_index_types requires every registered index type
to expose non-empty description and syntax (enforced by
04306_data_skipping_index_types_documentation and
04518_every_data_skipping_index_type_must_have_documentation, both
added to master after this branch was authored). spatial_bbox was
registered without a Documentation, causing both tests to fail.
pointInPolygon is variadic: besides a single Polygon/MultiPolygon
argument, it also accepts a MultiPolygon spread across several
constant polygon arguments, e.g.
pointInPolygon(geom, poly1, poly2, ...), matching a point that falls
in ANY of them. MergeTreeIndexConditionSpatialBbox::extractQueryBbox
only used the first constant argument to build the query bbox, so
granules that only matched a later polygon argument were incorrectly
pruned by the spatial_bbox skip index, silently dropping matching
rows. Fix by unioning the bbox across all constant geometry children.

Add regression test 04838_spatial_bbox_multipolygon_pruning covering
a query where the match lies only in the second polygon argument.
bacek added 2 commits August 11, 2026 22:47
`tryExtractConstGeoBbox` built a pruning bbox directly from a constant
geometry literal without validating it, unlike `pointInPolygon` which
raises "Polygon is not valid" for a self-intersecting ring at execute
time (with `validate_polygons = 1`, the default). If all granules were
far from the bogus bbox, the index silently pruned everything and
returned 0 rows instead of surfacing the exception.

Delegate to `tryExtractBboxFromColumn` (Common/GeoBbox.h), the same
fail-closed helper already used by the Parquet geo-pruning path, so an
invalid polygon disables pruning instead of hiding the error.
`extractQueryBbox` silently ignored any predicate argument that was
neither the matching indexed-column `INPUT` nor a constant geometry
literal. A spatial predicate like `f(geom, id, const_poly)` could then
derive a pruning bbox from `geom` alone, even though the predicate's
truth may depend on `id` or on a UDF that ignores `geom` entirely,
letting pruning incorrectly skip matching rows.

Treat any such extra argument (a second/unrelated `INPUT`, or a
non-constant expression) as reason to disable pruning entirely,
matching Parquet::tryExtractSpatialFilterFromNode's "exactly one
non-constant input" guard.
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 54a6b326-f7b6-4644-b0ed-2e980a8026f1
  • MIRAI run: 3bb14fcc-61e0-461d-a853-6543ff28d938
  • PR check IDs:
    • clickbench_1118519_1788490356
    • clickbench_1118622_1788490375
    • clickbench_1118733_1788490385
    • tpch_adapted_1_official_1118850_1788490402
    • tpch_adapted_1_official_1118956_1788490439
    • tpch_adapted_1_official_1119083_1788490478

bacek added 2 commits August 12, 2026 06:21
An all-empty-Ring/Polygon/MultiPolygon granule leaves
BboxAccumulator::found == false. serializeBinary threw LOGICAL_ERROR
in that case instead of just marking the granule non-prunable. Encode
has_data explicitly as a leading flag byte instead.
extractQueryBbox's union loop over pointInPolygon's constant polygon
arguments silently skipped any argument that failed to convert to a
bbox, then unioned the remaining valid ones. If all valid arguments
were far from the granule, this could prune it even though the
skipped invalid polygon should have made pointInPolygon raise
BAD_ARGUMENTS at execute time. Track any_extraction_failed and
disable pruning when set, matching
Parquet::tryExtractSpatialFilterFromNode.
The entry had grown into a single paragraph roughly four times the length
of its siblings in the same list, restating the pruning contract several
times over. Keep what a user needs to decide whether to set it — the
contract, the two readers that consume it, the consequence of declaring
it falsely, and the one argument-shape rule that affects pruning — and
drop the repetition.

Co-Authored-By: Claude Opus 5 <[email protected]>
@bacek

bacek commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, the Docs examples failure here is unrelated to this pull request: https://github.com/ClickHouse/ClickHouse/actions/runs/33679836156/job/100482308814

The single unexpected example is Function/timeSeriesPrometheusValueToString#0, whose documented response table is one column narrower than the actual output. That example was added by #112795 (src/Functions/TimeSeries/timeSeriesPrometheusValueToString.cpp); this pull request does not touch src/Functions/TimeSeries. A revert is already open: #117789

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Confirmed on attribution: #112795 added that example, and this branch does not touch src/Functions/TimeSeries, so the red is not from this pull request.

One correction on the direction: the documented block is one character wider than the actual output, not narrower. In the FunctionDocumentation literal the header row is 54 code points while the data row and the bottom border are 55, so the check is diffing padding only. The value 0.0000001 is identical on both sides.

The revert has not merged: #117789 was still open and unmerged at 02:34Z, and Docs examples has failed on six consecutive master trees since 21:10:17Z (last green cda48f97d9728a at 20:55:06Z). So this branch keeps inheriting the red until either that revert lands or the example is corrected. A documentation-only fix from me is in flight: a two character deletion inside that literal, no source or behaviour change, so the feature does not need reverting.

@bacek

bacek commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, thanks for the correction on the padding direction — agreed, and nothing for this branch to do there.

Separately, two Stress test shards on this run are red and I do not believe they are from this pull request either:

The other eight shards all pass, including every sanitizer build on both architectures (arm_asan_ubsan, arm_asan_ubsan + s3, arm_msan, arm_tsan, amd_asan_ubsan, amd_msan, amd_tsan, amd_debug), each running 1h39m-1h47m. The two red shards ended early and uploaded no report at all: result_stress_test_arm_release.json is not in S3, and the job step API shows Set up job, Checkout code and Prepare env script succeeding, then Run ending with a null conclusion while the job is marked failure — the step was killed rather than reporting a test result.

Could you take a look, and rerun those two shards if it is the infrastructure abort it looks like?

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Runner-side, not this branch.

Neither shard produced a result at all. result_stress_test_arm_release.json and result_stress_test_arm_debug.json are absent under PRs/104437/a7f79bf6a468.../pr/ (403 on a missing key), while result_stress_test_arm_tsan.json on the same prefix returns 200, so the absence is real and not a permissions artifact. Neither published a single CIDB row of any status; the eight green shards published five each. The root result_pr.json carries praktika's own verdict on the arm_release node: status: ERROR, duration: null, links: [], ext.errors[0].message = "Job failed to produce Result due to a script error or CI runner issue". Green arm_tsan uploaded 18 artifacts (job.log, fatal.log, dmesg.log, ...); the two dead shards uploaded none, so the death precedes every reporting step. Not a timeout either: praktika's default job timeout is 5h (ci/praktika/job.py:54) and the workflow sets no timeout-minutes.

It is the runner and not the job script. Both jobs are completed/failure with step 4 Run left in_progress / conclusion: null, Post Checkout code never started, and the log blob gone (BlobNotFound on both). Two other ARM Stress test shards on unrelated pull requests carry the same praktika error in the same window: https://github.com/ClickHouse/ClickHouse/actions/runs/33681665106/job/100513197211 (arm_asan_ubsan, s3, 58m) and https://github.com/ClickHouse/ClickHouse/actions/runs/33662157326/job/100390573972 (arm_debug, 64m). Four distinct runner instances across the four dead shards, so it is not one bad host. The second link is the only victim whose log survived: the stress script is healthy to its last line (clickhouse start, SELECT 1 returns 1, then clickhouse stop --max-tries 300 --do-not-kill), then ##[error]The operation was canceled. arrives 36 minutes after the Actions service had already marked that job failed. That is a runner losing contact with the service.

Nothing points at the diff: both shards were green on the three previous heads of this branch, most recently de867c02c91c, and the only branch-side change since is a master merge plus a one-line documentation edit. A memory-driven death would take the sanitizer flavours first, and all four passed.

On the rerun: Stress test (arm_debug) is already re-running. clickhouse-gh[bot] dispatched run attempt 3 at 03:38:13Z on a different instance: https://github.com/ClickHouse/ClickHouse/actions/runs/33679836156/job/100513529895. Stress test (arm_release) was not included, and I cannot trigger it: my account holds triage and not push on this repository, and the job rerun endpoint needs write access. That one needs a maintainer, unless the bot picks it up once attempt 3 finishes.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Correcting my last note: no PR from me. #117827 already carries exactly that two code point correction and is approved, and the identical change also rides in #117816.

I verified it produces the same file bytes as the change I had built and tested here, so this branch stops inheriting the red as soon as either of those lands, or if the revert #117789 does instead.

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, 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.

@nihalzp nihalzp self-assigned this Sep 11, 2026
@bacek

bacek commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

@nihalzp can you have a look?

@nihalzp

nihalzp commented Oct 8, 2026

Copy link
Copy Markdown
Member

I will try to review next week.

@groeneai

Copy link
Copy Markdown
Collaborator

Correction to my earlier note here: #116044 only reports the failed start, it does not prevent it, and the same failure has since recurred on #118399 without any stop-grace overrun. The fix is #128323: the harness now waits until the nodes it stopped leave the container list that docker compose start reads (Docker Engine 27.0.3 updates that list after stop/kill return, moby/moby#50133).

…patial

# Conflicts:
#	src/Functions/polygonsIntersect.cpp
#	src/Functions/polygonsWithin.cpp
#	src/Processors/Formats/Impl/Parquet/GeoFilter.cpp
#	tests/queries/0_stateless/00900_long_parquet_load_2.sh
@mintlify

mintlify Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 856511c.

Approve preview

Comment thread src/Common/GeoBbox.h
/// Skipping cannot hide an exception in the other direction either: a NATIVE predicate handed
/// a non-geometry argument raises from `callOnTwoGeometryDataTypes`, which dispatches on the
/// argument TYPES and so raises even on a fully pruned, zero-row block.
if (child->result_type && GeoBboxDetail::isNonGeometryType(*child->result_type))

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.

[P1] Count numeric geometry constants before choosing a single bbox

isNonGeometryType recognizes structural geometry only when both coordinates are Float64, but pointInPolygon accepts all native numeric coordinate types and casts each polygon independently. This skips a valid integer-coordinate polygon and can prune rows that match it. For example:

CREATE TABLE t (p Point, INDEX idx p TYPE spatial_bbox GRANULARITY 1)
ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 1;
INSERT INTO t VALUES ((10.5, 10.5));
SELECT count() FROM t
WHERE pointInPolygon(p,
    [[(0.,0.),(1.,0.),(1.,1.),(0.,1.),(0.,0.)]],
    [[(10,10),(11,10),(11,11),(10,11),(10,10)]])
SETTINGS optimize_move_to_prewhere = 0, use_skip_indexes = 1;

The integer polygon is skipped here, leaving one constant geometry and a query bbox of [0,1] × [0,1]; the only granule is discarded despite its point being inside the second polygon. With skip indexes disabled the count is 1. The shared GeoParquet extractor has the same problem.

Please count all numeric geometry carriers, or conservatively disable extraction for unrecognized coordinate types, so mixed numeric arguments retain the multiple-geometry no-pruning behavior. Add a regression comparing index-enabled and index-disabled results for this case.


DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override
{
checkArealPredicateArgumentTypes<Point>(arguments[0], arguments[1], getName());

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.

[P2] Route the column overload through the new type validation

Normal analysis calls getReturnTypeImpl(const ColumnsWithTypeAndName &), which these classes still inherit from IFunction. That implementation returns directly from applyFunctionSignature when getSignatureString is nonempty (src/Functions/IFunction.cpp:1214-1222). Since the signature here is (Any, Any) -> UInt8, it never dispatches to this new DataTypes overload or calls checkArealPredicateArgumentTypes.

Consequently rejected types such as Point are still accepted during analysis and rejected only by executeImpl, contrary to the analysis-time validation that the PR relies on. FunctionPolygonsWithin has the same issue. Please add the column-overload forwarding used by pointInPolygon at src/Functions/pointInPolygon.cpp:274-280, or encode the full accepted domain in the signature. A focused EXPLAIN QUERY TREE test with a nonconstant Point column would verify that rejection happens during analysis instead of merely exercising the existing runtime check.

return std::make_shared<MergeTreeIndexSpatialBbox>(std::move(metadata_snapshot), index);
}

void spatialBboxIndexValidator(const IndexDescription & index, bool /*attach*/, const MergeTreeSettings & /*settings*/)

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.

[P1] Gate the new persistent index behind an experimental setting

spatial_bbox is registered unconditionally, and this validator ignores both attach and the settings. An ordinary CREATE TABLE or ALTER TABLE ... ADD INDEX can therefore opt directly into a new persistent .idx2 format and a new row-eliminating pruning implementation, with no experimental setting required. A pruning false negative silently drops matching rows, so this new storage feature needs a gated rollout while its correctness and format are being stabilized.

Please add a default-off experimental setting and enforce it for creation of spatial_bbox indexes through both DDL paths. Keep loading existing tables possible when the setting is disabled, and explicitly enable the setting in the feature's tests.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, 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.

@nihalzp nihalzp self-assigned this Nov 9, 2026
@nihalzp nihalzp removed manual approve Manual approve required to run CI submodule changed At least one submodule changed in this PR. labels Nov 13, 2026
# Conflicts:
#	src/Common/GeoBbox.h
#	src/Processors/Formats/Impl/Parquet/GeoFilter.cpp

@nihalzp nihalzp 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 general idea is interesting. I think we can extend it to primary key or minmax pruning in KeyCondition, maybe in a separate PR.

For UDFs, as I understand it, if a UDF declares is_spatial_predicate = 1, we take its constant argument, compute its bbox, and check it against our skip index's bounding boxes to prune. My concern is that there could be functions that widen the constant, read coordinates in the wrong order, and so on, and that this couples ClickHouse internals with the UDF implementation.

Since each of these is a major decision, let's keep UDF support out of this PR and limit it to the skip index first, with support for built-ins only.

@bacek

bacek commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

The general idea is interesting. I think we can extend it to primary key or minmax pruning in KeyCondition, maybe in a separate PR.

Probably separate PR after.

For UDFs, as I understand it, if a UDF declares is_spatial_predicate = 1, we take its constant argument, compute its bbox, and check it against our skip index's bounding boxes to prune.

We actually invoke UDF to get bbox, but generallly yes.

My concern is that there could be functions that widen the constant, read coordinates in the wrong order, and so on, and that this couples ClickHouse internals with the UDF implementation.

It is actually impossible for WASM UDF to do anything harmless for ClickHouse internals. UDF receives copy of data to work on, and returns new chunk of data. Behaviour is "Garbage In, Garbage Out". If UDF returns something stupid, it's on UDF. And this PR is actually "sister PR" for #104435 which added pruning functionality for Parquet files.

Since each of these is a major decision, let's keep UDF support out of this PR and limit it to the skip index first, with support for built-ins only.

UDF support is already landed as part of 104435. This PR is only wiring same functionality for native storage.

@nihalzp

nihalzp commented Nov 13, 2026

Copy link
Copy Markdown
Member

We actually invoke UDF to get bbox, but generallly yes.

I do not think we do. If I understand the code correctly, tryExtractConstGeoField (GeoBbox.h:524-538) reads the constant's value, and ClickHouse's own extractBboxFromFieldValue takes its minima and maxima to compute the bbox. If the constant is itself a UDF call such as st_geomfromtext(...), that UDF only builds the geometry; the bbox is still computed by ClickHouse from its result. The only WASM-related code is the flag lookup in isSpatialPredicate.

It is actually impossible for WASM UDF to do anything harmless for ClickHouse internals.

My concern is not about whether a UDF is harmful or harmless; it's about correctness. It's very easy for users to make honest mistakes and get wrong results. Since we control the API, it should make it easy for users to get pruning without risking correctness.

UDF support is already landed as part of 104435. This PR is only wiring same functionality for native storage.

You're right, the same already exists for Parquet. I think we should preferably change the API there as well, rather than extend the current one to more places. Either way, UDF support does not need to come with this PR for the skip index; it can be a separate PR.

Here is the design I was proposing. We can add a ClickHouse function with fixed bbox semantics, for example bboxIntersects(geom, shape), which returns true when the bbox of geom overlaps the bbox of shape. The skip index, the Parquet reader and later KeyCondition would then prune only on this function and on the built-in functions whose semantics we own.

A UDF can get pruning by being wrapped in a SQL UDF that adds the box test:

CREATE FUNCTION st_intersects AS (g, s) -> bboxIntersects(g, s) AND st_intersects_wasm(g, s);
CREATE FUNCTION st_dwithin AS (g, s, d) -> bboxIntersects(g, widened(s, d)) AND st_dwithin_wasm(g, s, d);

Here widened is the UDF author's own expression that grows the box of s by d, for example another SQL UDF. Users still write st_intersects(...), and since SQL UDFs are expanded before index analysis, the index sees the bboxIntersects part. I think this is safer because the box test is part of the WHERE itself, so pruning cannot change the result. Even if the box is wrong, the query returns the same result with or without the index. We also do not need to know how a UDF reads its arguments. For st_dwithin, constant expressions like widened(s, d) are folded before index analysis, so the index sees the widened box as a normal constant.

For Parquet, we can keep is_spatial_predicate working until this is ready and deprecate it after that. Either way, I think it should be a separate PR after this one.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants