Repository navigation
Conversation
|
Workflow [PR], commit [856511c] Summary: ❌
AI ReviewSummaryAdds the persistent Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ 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. |
|
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. |
|
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. |
|
@alexey-milovidov can you unleash CI on that PR, please? |
d5a4e93 to
aceea47
Compare
Ping |
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`.
5f1d4cb to
f8102ae
Compare
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.
`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.
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
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]>
|
🕵 @groeneai, the The single unexpected example is |
|
Confirmed on attribution: One correction on the direction: the documented block is one character wider than the actual output, not narrower. In the The revert has not merged: |
|
🕵 @groeneai, thanks for the correction on the padding direction — agreed, and nothing for this branch to do there. Separately, two
The other eight shards all pass, including every sanitizer build on both architectures ( Could you take a look, and rerun those two shards if it is the infrastructure abort it looks like? |
|
Runner-side, not this branch. Neither shard produced a result at all. It is the runner and not the job script. Both jobs are Nothing points at the diff: both shards were green on the three previous heads of this branch, most recently On the rerun: |
|
Correcting my last note: no PR from me. 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 |
|
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 can you have a look? |
|
I will try to review next week. |
|
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 |
…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
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
| /// 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)) |
There was a problem hiding this comment.
[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()); |
There was a problem hiding this comment.
[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*/) |
There was a problem hiding this comment.
[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.
|
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. |
# Conflicts: # src/Common/GeoBbox.h # src/Processors/Formats/Impl/Parquet/GeoFilter.cpp
nihalzp
left a comment
There was a problem hiding this comment.
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.
Probably separate PR after.
We actually invoke UDF to get bbox, but generallly yes.
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.
UDF support is already landed as part of 104435. This PR is only wiring same functionality for native storage. |
I do not think we do. If I understand the code correctly,
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.
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 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 For Parquet, we can keep |
Part of making ClickHouse fastest spatial analytical engine on Earth https://github.com/bacek/chgeos/blob/main/BENCHMARK.md ;)
Adds a
spatial_bboxskip index forMergeTreegeometry columns, plus the shared bbox-extractioninfrastructure that also drives
Parquet/GeoParquet row-group and page pruning and Iceberg manifestpruning. A predicate opts in through
IFunctionBase::isSpatialPredicate; the consumer this PR shipsis the
LANGUAGE WASMUDF path (is_spatial_predicate = 1), alongside the native predicates thatalready 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 itis 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 thetests 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:
pointInPolygonwithvalidate_polygons = 0accepts empty rings and empty-bound polygons atexecution time; the extractor refuses to bound them.
correctan invalid constant polygon and evaluate it; the extractor validatesconstant polygon/multipolygon literals and WKB payloads the way
parseConstPolygondoes, andrefuses the ones it rejects.
Variant/Dynamicarguments resolve their overload per row, so they keep a blunt veto thatdisables 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
IFunctionhooks letting each native geometry function declare itsaccepted argument domain. Those are all gone;
isSpatialPredicateis the only spatial surface lefton
IFunction. Instead,polygonsIntersectandpolygonsWithinstate their domain once, incheckArealPredicateArgumentTypes(Functions/geometryConverters.h), and apply it fromgetReturnTypeImplrather than fromexecuteImpl. The rejection then happens during analysis, outof reach of anything that removes rows — skip-index or primary-key pruning,
PREWHERE, an emptypart — 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Adds
spatial_bboxskip 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
Workflow [PR]
Sync PR [sync-upstream/pr/104437]