Repository navigation
Add native Mapbox Vector Tile (MVT) encoding functions - #106107
Conversation
Add `mvtEncodeGeom` (scalar) and `mvtEncode` (aggregate) for producing Mapbox Vector Tiles directly in SQL, analogous to PostGIS `ST_AsMVTGeom` and `ST_AsMVT`. `mvtEncodeGeom` projects a (longitude, latitude) point into the tile-local pixel space of a slippy-map tile using the Web Mercator projection and returns the pixel coordinates as a `Tuple(Float64, Float64)`. `mvtEncode` aggregates the projected points of a group into the binary bytes of a single-layer tile; feature attributes are supplied as a named tuple whose element names become the attribute keys. Clustering is expressed in SQL by grouping on the rounded pixel geometry, so the encoder is agnostic to clustered versus unclustered input. Property values are interned into a per-layer value pool; a `NULL` property omits that attribute for the feature. The MVT protobuf wire bytes are written directly (see `MVTProtobuf.h`) instead of going through the generic protobuf library. This version supports point geometry only, without geometry clipping (the caller restricts rows to the tile with a `WHERE` predicate). Includes a stateless test and documentation for the geo functions reference.
Add an optional clip `buffer` parameter to the aggregate function
`mvtEncode` and two scalar helpers, `mvtTileBBox` and
`mvtTileBBoxMercator`, that return the bounding box of a slippy-map tile.
`mvtEncode('layer', extent, buffer)` drops point features whose tile-pixel
coordinates fall outside `[-buffer, extent + buffer]`, enforcing the exact
tile boundary during aggregation. `mvtTileBBox(zoom, tile_x, tile_y[, margin])`
returns the tile's `(min_lon, min_lat, max_lon, max_lat)` bounding box in
degrees, and `mvtTileBBoxMercator` returns it in the full-`UInt32` Web
Mercator space used internally by `mvtEncodeGeom`. The optional `margin`
expands the box on every side by that fraction of the tile size.
Together these mirror the PostGIS pattern: a cheap, index-using bounding-box
predicate in the `WHERE` clause (from `mvtTileBBox`) restricts rows to the
tile for performance, while the `mvtEncode` clip enforces the boundary for
correctness, so a loose prefilter cannot leak out-of-tile points into the
result.
Clipping is implemented in the aggregate (rather than as a `Nullable` return
from `mvtEncodeGeom`) because `Nullable(Tuple)` is an experimental,
normally-disallowed type that is not fully supported and faults under
expression JIT compilation.
Includes a stateless test and documentation.
Drop the comparative references to another spatial database from the `mvtEncode` documentation string and the geo functions reference page, so the documentation describes the ClickHouse functions on their own terms.
The value-length bounds check in the mvtEncode state parser used pointer arithmetic (`pos + length > end`), where `length` is a varint read from the (possibly corrupted) aggregate state. A crafted state passed to `mvtEncodeMerge` could set a huge `length`, overflowing the pointer (undefined behavior) and bypassing the check, leading to an out-of-bounds read. Compare sizes instead (`length > end - pos`); the coordinate read uses the same size-based form. Verified with ASan+UBSan fuzzing of the parser.
|
Workflow [PR], commit [eb69563] Summary: ❌
AI ReviewSummaryThis PR adds native Mapbox Vector Tile helpers and aggregate encoding functions: PR Metadata
Suggested replacement: Missing context / blind spots
Findings
Suggested fix: reject or convert to Tests
Final VerdictStatus: Minimum required actions: handle non-finite source coordinates before projection/Boost.Geometry, and update the PR changelog entry to use the registered |
- Validate tile_x and tile_y against 2^zoom in mvtEncodeGeom, mvtTileBBox and mvtTileBBoxMercator. Previously only zoom was checked, so out-of-range tile requests (e.g. tile_x=1 at zoom 0) produced degenerate tiles instead of an exception. - Store feature pixel coordinates as Int64 instead of Int32 so the documented extent range (up to 2^32) round-trips exactly. Coordinates above Int32::max were previously narrowed and wrapped negative, then dropped by the clip. - Use VectorWithMemoryTracking / UnorderedMapWithMemoryTracking instead of std::vector / std::unordered_map so the value pool is tracked against the query memory limit (style check). - Access the static data() through the base class to satisfy clang-tidy readability-static-accessed-through-instance. - Docs: the clip buffer is a parameter of mvtEncode, not mvtEncodeGeom. Adds stateless coverage for out-of-range tile indices and the large-extent/coordinate boundary.
The page linked to the HTTP interface with a relative path (`../../../interfaces/http.md`) that does not resolve in the docs site (the interface page lives in a separate docs repository), which broke the Docusaurus build. Use the absolute slug `/interfaces/http`, matching how other pages reference it.
The "shared attribute value" case compared the exact bytes of a two-feature tile, but mvtEncode is order-dependent: under parallel execution and various query-plan settings the two feature messages can be emitted in either order, so the bytes (though not the total length) vary. This made 04299_mvt_encode flaky in the debug stateless and flaky-check jobs. Compare tile lengths instead: a shared value interns to a single value-pool entry, yielding a shorter tile than two distinct values, which demonstrates the interning without depending on feature order.
|
Hello, Thanks for the review and assignment! The remaining red checks look like unrelated with this change:
Could you re-run these two jobs when you get a chance please? |
Algunenano
left a comment
There was a problem hiding this comment.
Partial review. Only up to the aggregation
I don't quite understand why you decided to use a manual write instead of using protobuf, which with your architecture is only used at the end (in insertResultInto). What benefits those is bring? Because the need to review and verify for correctness is a clear drawback, specially when the behaviour is not set and proven.
Please pay attention to the AI review comments and either address them or dismiss them.
Also, please consider carefully what functions you are adding (many already existed in the project) and follow a similar architecture and setup as other functions, reusing existing code, data structures, etc.
| clients such as MapLibre and Mapbox GL render natively. ClickHouse can build such tiles entirely in SQL with a pair of | ||
| cooperating functions: | ||
|
|
||
| - `mvtEncodeGeom` — a scalar function that projects a geographic point into the tile-local pixel space of a slippy-map |
There was a problem hiding this comment.
These names are incorrect:
- MVT is an acronym and it should be in all caps.
- There is already standard names in PostGIS, then adopted by others like DuckDB, to use ST_AsMVT / ST_AsMVTGeom. We can have other names if we need to, simpler ones, but keep the alias and have a similar parameter order and names.
There was a problem hiding this comment.
This is still an issue. The convention is to capitalize acronyms. Like JSONextract
Rework `mvtEncodeGeom` and `mvtEncode` to operate on the `Geometry` type
instead of point tuples, so points, lines and polygons (and their ring and
multi- variants) can be encoded into a single vector tile.
- `mvtEncodeGeom(geometry, zoom, tile_x, tile_y[, extent[, buffer[, clip]]])`
projects any geometry to Web Mercator tile pixels, clips it to the tile
(returning a `Geometry`, or `NULL` when fully clipped), and snaps it to the
pixel grid. Clipping moved here from `mvtEncode` and uses a native `NULL`
rather than a `Nullable(Tuple)`.
- `mvtEncode('layer'[, extent])(geometry[, properties])` consumes the
tile-space `Geometry`, emits the MVT geometry command stream for point,
line and polygon features with the specification's ring winding, and skips
`NULL` geometry.
- Reuse the existing geometry infrastructure (`geometryConverters.h`, the geo
serializers and Boost.Geometry) and the `Geometry` variant.
- Register the PostGIS-compatible aliases `ST_AsMVTGeom`, `ST_AsMVT` and
`ST_TileEnvelope`.
- Map the `Bool` and `Date32` property types to the `bool` and `sint` vector
tile value types.
Update the documentation and the `04299_mvt_encode` / `04300_mvt_clip`
stateless tests for the new API.
Lead the "Serving tiles over HTTP" section with the simplest handler: serve one feature per row straight from a `Geometry` column, letting `mvtEncodeGeom` project and clip each geometry to the requested tile. Clustering and the index-using bounding-box prefilter are now referenced as optional extensions rather than shown up front.
Drop the redundant `typename` flagged by `readability-redundant-typename`, and allocate the per-feature point buffer through `VectorWithMemoryTracking` so a large geometry's vertices count against the query memory limit, consistent with the value pool.
The fast build (-Werror) and the clang-tidy build flag issues that ccache hid on the unchanged files but surface on a fresh compile of these new ones: - Forward-declare `registerAggregateFunctionMvtEncode` so its definition has a prior prototype (-Wmissing-prototypes). - Initialize the local `x`/`y` pixel coordinates, the `bits` reinterpret buffers in the protobuf writers, the `clip` flag, and give the `Projection` struct default member initializers (cppcoreguidelines-init-variables and -pro-type-member-init). CI report: ClickHouse#106107
Address review feedback: instead of reimplementing varint, zigzag and little-endian serialization, reuse the existing ClickHouse helpers. - `MVT::writeVarint` now delegates to `writeVarUInt`, and the geometry/property encoders use `encodeZigZag` from `IO/VarInt.h` instead of a local `zigzag`. - The aggregate-state parser reads its length prefixes with the bounds-checked `readVarUInt(x, pos, size)` overload rather than a hand-written varint loop. - `writeFloatField` / `writeDoubleField` use `unalignedStoreLittleEndian` instead of a manual byte loop. The on-the-wire encoding is unchanged; the stateless tests still pass. Review: ClickHouse#106107
…d, stringify
Following review of the MVT functions:
- `mvtEncode`: trim the trailing NUL padding of `FixedString` property values (matching ClickHouse's `FixedString`-to-`String` conversion), so `toFixedString('ab', 4)` and `'ab'` encode to the same `string_value`; interior NULs are preserved.
- `mvtEncodeGeom`: return `NULL` for empty `LineString`/`Polygon`/`MultiPolygon` inputs instead of an empty container. The dispatch wraps a single input in a Multi container, so the previous `result.empty()` guard saw one empty element; it now checks the vertex count (`bg::num_points`).
- `mvtEncode`: add an optional `feature_id_name` parameter (PostGIS `ST_AsMVT` analogue) naming an integer property element to emit as the MVT Feature `id` (`uint64`) and exclude from the tags; a `NULL` or negative id is omitted.
- `mvtEncode`: add an optional `stringify_unsupported` flag that encodes otherwise-unsupported property types (big integers, `UUID`, `Decimal`, ...) as their text `string_value` instead of raising an error.
All four are opt-in or behaviour-preserving for existing calls. Adds stateless coverage and updates the documentation.
The `feature_id_name` parameter added to `mvtEncode` supports the MVT Feature `id`, so the "No explicit feature id field" limitation no longer applies.
The Web Mercator world spans 2^32 units per axis in the standard XYZ tile scheme; `mercator_max` used 2^32 - 1, which scaled the world one unit short and drifted projected coordinates at high zoom (e.g. `(0, 0)` projected to pixel `(-1, -1)` at zoom 20 instead of `(0, 0)`, and `mvtTileBBoxMercator`'s last-tile width came out one unit short). Correct the constant in `mvtEncodeGeom` and `mvtTileBBox` and add regression tests covering the `(0, 0)` invariant and the last-tile width across zooms.
Algunenano
left a comment
There was a problem hiding this comment.
Review:
Function naming:
- ClickHouse keeps uppercase for acronyms in function names (JSONEncode, URLHash, MACNumToString). Let's call functions MVTEncode and so on.
- Also, unless the name is clear or known we also avoid truncating words. Geom is understandable, Bbox isn't unless you already know. mvtTileBBox -> MVTBoundingBox (Tile is the T), mvtTileBBoxMercator -> MVTBoundingBoxMercator
Docs:
- Please document the limitations of the current approach to clipping and validating the geometries in the docs.
Other:
- Let's accept just unsigned integers of the id.
- Tests should not simply compare feature enabled != feature disabled. They should verify the output is correct according to the spec. Please generate them, verify them and put them in the reference file.
…gned feature ids Address review feedback on the native Mapbox Vector Tile functions. Function naming now follows the ClickHouse convention of capitalizing acronyms and avoiding cryptic truncations (cf. `JSONExtract`, `URLHash`): `mvtEncode` -> `MVTEncode` `mvtEncodeGeom` -> `MVTEncodeGeom` `mvtTileBBox` -> `MVTBoundingBox` `mvtTileBBoxMercator` -> `MVTBoundingBoxMercator` The `ST_AsMVT` / `ST_AsMVTGeom` PostGIS aliases are unchanged. The C++ class, struct and enum identifiers and the source file names are renamed to match. `MVTEncode`'s optional `feature_id_name` now accepts only unsigned integer elements and rejects signed ones. The MVT Feature `id` is a `uint64`, so a signed column could only ever drop its negative ids, leaving some features with an id and some without depending on the column type. Rejecting signed integers makes the validation explicit and the behaviour predictable.
Address review feedback: the `feature_id_name` and `stringify_unsupported`
tests asserted only that the output differed from (or equalled) a tile
without the feature, which does not check that the bytes are correct.
Replace those comparisons with `hex(MVTEncode(...))` of single-feature
tiles whose exact bytes are locked in the reference file. Each tile was
decoded against the MVT spec to confirm it is correct:
- feature id 42 emitted as Feature.id, the `fid` element excluded from
the tags (keys = [name] only);
- a NULL feature id omitted, encoding identically to declaring no id;
- an Int128 rendered as its decimal string_value under stringify_unsupported.
Also add a signed-integer feature-id case that is now rejected.
…Geom Add two entries to the Limitations section of the MVT functions docs: self-intersecting rings are not repaired (a bow-tie is either emitted invalid or dropped to NULL), and geometry is clipped before it is rounded to the integer pixel grid (unlike PostGIS, which rounds first), which can drop a coordinate near a tile edge that would otherwise round onto the boundary pixel. Each entry has a small verified example.
|
Changes as per review:
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 758/884 (85.75%) | Lost baseline coverage: none · Uncovered code |
Algunenano
left a comment
There was a problem hiding this comment.
@saarthak2002 Thanks a lot. Looks great. I'll finish reviewing the (unrelated) CI failures and merge it
b162a39
|
@groeneai enrich tests: check boundary values and equivalence classes. Check results with standard. |
|
@fm4v on it. Since this PR is merged and lives on a fork, I'll deliver the enrichment as a separate follow-up PR against master (extending Plan, grounded in the actual code paths ( 1. Check results against the standard. The strongest "verify against spec" we can do without a new dependency is to assert the emitted bytes against the worked examples in vector-tile-spec 2.1 (§4.1 layer/feature structure, §4.3 the
2. Boundary values. zoom 0 and 32; tile indices 3. Equivalence classes. geometry kind (Point / Line / MultiLine / Ring / Polygon-with-hole / MultiPolygon); clip outcome (fully inside / fully outside -> NULL / partially clipped / on boundary); degenerate (collinear ring, sub-pixel line, zero-area near I'll build and run locally, then open the follow-up PR and link it here. Anything you want weighted differently (e.g. a specific reference decoder you'd prefer over an in-SQL decode)? |
|
Follow-up PR with the enriched tests: #108929 — decodes MVTEncode output through the official vector_tile.proto and asserts the §4.3.5 worked examples byte-for-byte, plus equivalence classes and boundary values. |
….proto The existing MVT tests (04299/04300) assert the encoder output as opaque hex. This adds a test that decodes the bytes produced by MVTEncode back through the official Mapbox Vector Tile 2.1 wire schema and asserts the decoded structure, so the output is verified to be correct according to the standard rather than merely stable. The geometry command streams are checked against the worked examples in the specification (vector-tile-spec 2.1, section 4.3.5): the point, linestring, polygon and multilinestring examples reproduce byte-for-byte. The test also covers equivalence classes (each property type to its Value variant, the feature id, value interning, stringify_unsupported) and boundary values (zoom 0 and 32, extent extremes), and the assertions are demonstrated to fail on a wrong command stream. Requested by @ fm4v on PR ClickHouse#106107. Co-Authored-By: Claude Opus 4.8 <[email protected]>
….proto The existing MVT tests (04299/04300) assert the encoder output as opaque hex. This adds a test that decodes the bytes produced by MVTEncode back through the official Mapbox Vector Tile 2.1 wire schema and asserts the decoded structure, so the output is verified to be correct according to the standard rather than merely stable. The geometry command streams are checked against the worked examples in the specification (vector-tile-spec 2.1, section 4.3.5): the point, linestring, polygon and multilinestring examples reproduce byte-for-byte. The test also covers equivalence classes (each property type to its Value variant, the feature id, value interning, stringify_unsupported) and boundary values (zoom 0 and 32, extent extremes), and the assertions are demonstrated to fail on a wrong command stream. Requested by @ fm4v on PR #106107. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Hi @saarthak2002 @Algunenano — while reviewing this PR I found the following:
Could you review the test PR and add the |
….proto The existing MVT tests (04299/04300) assert the encoder output as opaque hex. This adds a test that decodes the bytes produced by MVTEncode back through the official Mapbox Vector Tile 2.1 wire schema and asserts the decoded structure, so the output is verified to be correct according to the standard rather than merely stable. The geometry command streams are checked against the worked examples in the specification (vector-tile-spec 2.1, section 4.3.5): the point, linestring, polygon and multilinestring examples reproduce byte-for-byte. The test also covers equivalence classes (each property type to its Value variant, the feature id, value interning, stringify_unsupported) and boundary values (zoom 0 and 32, extent extremes), and the assertions are demonstrated to fail on a wrong command stream. Requested by @ fm4v on PR ClickHouse#106107. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Motivation
Web map clients (MapLibre GL, Mapbox GL) render Mapbox Vector Tiles (MVT) — a protobuf format — natively. Serving data from ClickHouse as slippy-map tiles currently requires an external service that reads rows out of ClickHouse and re-encodes them into MVT bytes, adding a network hop and a separate component to operate even though the data and aggregation already live in ClickHouse.
These functions let a complete vector tile be produced entirely in SQL and served straight off the HTTP interface with
FORMAT RawBLOB, so a/tile/{z}/{x}/{y}endpoint becomes a single parameterized query behind apredefined_query_handler.What's added
MVTEncodeGeom(geometry, zoom, tile_x, tile_y[, extent[, buffer[, clip]]])— scalar; projects a geometry given in longitude/latitude into the tile-local pixel space (Web Mercator, top-left origin), clips it to the tile expanded bybufferpixels (default1), and snaps to whole pixels soGROUP BY MVTEncodeGeom(...)performs pixel clustering. Returns aGeometry, orNULLwhen the input is fully clipped out. Point, line and polygon geometry is supported (Point,LineString,MultiLineString,Ring,Polygon,MultiPolygon,Geometry).MVTEncode('layer'[, extent[, feature_id_name[, stringify_unsupported]]])(geometry[, properties])— aggregate; collects one feature per row into the bytes of a single-layer tile.propertiesis a named tuple whose element names become attribute keys and whose types map to MVT value types.feature_id_nameoptionally promotes an unsigned-integer element to the MVT Featureid;stringify_unsupportedencodes otherwise-unsupported types as their text value instead of raising.MVTBoundingBox(zoom, tile_x, tile_y[, margin])andMVTBoundingBoxMercator(...)— return a tile's bounding box, so theWHEREprefilter can run against indexedlongitude/latitude(or Mercator) columns.Also available under their PostGIS names as aliases:
ST_AsMVTGeomforMVTEncodeGeomandST_AsMVTforMVTEncode. All in theGeocategory. Documentation:docs/en/sql-reference/functions/geo/mvt.md. Clustering is expressed in SQL (GROUP BY+count()), not as a function parameter.Example
WITH 1 AS buffer, 4096 AS extent, MVTBoundingBox({z:UInt8}, {x:UInt32}, {y:UInt32}, buffer / extent) AS bb SELECT MVTEncode('points')(geom, tuple(cluster_count)::Tuple(cluster_count UInt64)) FROM ( SELECT MVTEncodeGeom((lon, lat)::Point, {z:UInt8}, {x:UInt32}, {y:UInt32}) AS geom, count() AS cluster_count FROM points WHERE lon BETWEEN bb.1 AND bb.3 AND lat BETWEEN bb.2 AND bb.4 GROUP BY geom ) SETTINGS allow_suspicious_types_in_group_by = 1Notes for reviewers
src/AggregateFunctions/MVTProtobuf.h) rather than via the generic protobuf library, to avoid per-feature message allocations.2^32so that a tile of size2^(32 - zoom)tessellates the world without drift at high zoom.MVTEncodeGeom, which returns aGeometry(aVariantthat carriesNULLnatively for fully-clipped input). This avoids aNullable(Tuple(...))return, which is a normally-disallowed type and faults under expression JIT.merge/deserializevalidates lengths with size-based bounds checks (length > end - pos) so a corrupted state cannot cause a pointer overflow or out-of-bounds read.tuple(...)aren't propagated to element names, they're named with a cast, e.g.tuple(count())::Tuple(cluster_count UInt64).Tested with stateless tests
04299_mvt_encodeand04300_mvt_clip, whose emitted bytes were decoded back and checked against the officialvector_tile.proto(viaprotoc) and the canonicalmapbox-vector-tilelibrary, plus end-to-end by serving tiles over HTTP and rendering them in QGIS.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added functions for serving Mapbox Vector Tiles directly from SQL:
MVTEncodeGeomprojects a geometry into the pixel space of a slippy-map tile and clips it,MVTEncodeaggregates the projected geometries of a group into the binary bytes of a single-layer tile, andMVTBoundingBox/MVTBoundingBoxMercatorreturn the bounding box of a tile for restricting rows to it. Point, line and polygon geometry is supported. Also available under the PostGIS aliasesST_AsMVTGeomandST_AsMVT.Version info
26.6.1.1112