Skip to content

Add native Mapbox Vector Tile (MVT) encoding functions - #106107

Merged
Algunenano merged 32 commits into
ClickHouse:masterfrom
saarthak2002:saarthak2002/mvt-encode
Jun 22, 2026
Merged

Algunenano merged 32 commits into
ClickHouse:masterfrom
saarthak2002:saarthak2002/mvt-encode

Conversation

@saarthak2002

@saarthak2002 saarthak2002 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

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 a predefined_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 by buffer pixels (default 1), and snaps to whole pixels so GROUP BY MVTEncodeGeom(...) performs pixel clustering. Returns a Geometry, or NULL when 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. properties is a named tuple whose element names become attribute keys and whose types map to MVT value types. feature_id_name optionally promotes an unsigned-integer element to the MVT Feature id; stringify_unsupported encodes otherwise-unsupported types as their text value instead of raising.
  • MVTBoundingBox(zoom, tile_x, tile_y[, margin]) and MVTBoundingBoxMercator(...) — return a tile's bounding box, so the WHERE prefilter can run against indexed longitude/latitude (or Mercator) columns.

Also available under their PostGIS names as aliases: ST_AsMVTGeom for MVTEncodeGeom and ST_AsMVT for MVTEncode. All in the Geo category. 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 = 1

Notes for reviewers

  • The MVT protobuf bytes are written directly (src/AggregateFunctions/MVTProtobuf.h) rather than via the generic protobuf library, to avoid per-feature message allocations.
  • The Web Mercator world spans exactly 2^32 so that a tile of size 2^(32 - zoom) tessellates the world without drift at high zoom.
  • Clipping lives in the scalar MVTEncodeGeom, which returns a Geometry (a Variant that carries NULL natively for fully-clipped input). This avoids a Nullable(Tuple(...)) return, which is a normally-disallowed type and faults under expression JIT.
  • The aggregate state begins with a format-version byte, and the parser used by merge/deserialize validates lengths with size-based bounds checks (length > end - pos) so a corrupted state cannot cause a pointer overflow or out-of-bounds read.
  • The properties tuple must have explicit element names; since aliases inside tuple(...) aren't propagated to element names, they're named with a cast, e.g. tuple(count())::Tuple(cluster_count UInt64).
  • Two limitations are documented: polygon clipping fixes orientation and closure but not self-intersections (a bow-tie ring is dropped or passed through, not repaired), and geometry is clipped on the floating-point projection before being rounded to the pixel grid (a coordinate that would round onto the boundary can be clipped).

Tested with stateless tests 04299_mvt_encode and 04300_mvt_clip, whose emitted bytes were decoded back and checked against the official vector_tile.proto (via protoc) and the canonical mapbox-vector-tile library, plus end-to-end by serving tiles over HTTP and rendering them in QGIS.

Changelog category (leave one):

  • New Feature

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: MVTEncodeGeom projects a geometry into the pixel space of a slippy-map tile and clips it, MVTEncode aggregates the projected geometries of a group into the binary bytes of a single-layer tile, and MVTBoundingBox / MVTBoundingBoxMercator return the bounding box of a tile for restricting rows to it. Point, line and polygon geometry is supported. Also available under the PostGIS aliases ST_AsMVTGeom and ST_AsMVT.

Version info

  • Merged into: 26.6.1.1112

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.
@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label May 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eb69563]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, 6/6) FAIL
test_database_glue/test.py::test_show_tables_optimization FAIL cidb, issue ISSUE CREATED
AST fuzzer (amd_msan) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-2cc2) FAIL cidb IGNORED

AI Review

Summary

This PR adds native Mapbox Vector Tile helpers and aggregate encoding functions: MVTEncodeGeom, MVTEncode, MVTBoundingBox, and MVTBoundingBoxMercator. The implementation has addressed many prior bounds, state-format, and feature-id issues, but one safety concern around non-finite input coordinates still exists, and the PR metadata/changelog still names the old lower-case functions.

PR Metadata
  • 💡 Changelog category: New Feature is correct.
  • 💡 Changelog entry: required and mostly user-readable, but it still lists the old names mvtEncodeGeom, mvtEncode, mvtTileBBox, and mvtTileBBoxMercator, which no longer match the registered functions.

Suggested replacement:

Added functions for serving Mapbox Vector Tiles directly from SQL: `MVTEncodeGeom` projects a longitude/latitude geometry into the pixel space of a slippy-map tile, `MVTEncode` aggregates projected geometries into the binary bytes of a single-layer tile with optional feature IDs and property encoding, and `MVTBoundingBox` / `MVTBoundingBoxMercator` return the bounding box of a tile for restricting rows to it.
Missing context / blind spots
  • ⚠️ I could not run the new stateless tests locally because this checkout has no build*/programs/clickhouse binary. The PR-form CI helper also hit a GitHub token policy error, and the direct S3 PR summary did not expose individual job results.
Findings

⚠️ Majors

  • [src/Functions/MVTEncodeGeom.cpp:62] [dismissed by author -- https://github.com/Add native Mapbox Vector Tile (MVT) encoding functions #106107#discussion_r3400229812] MVTEncodeGeom still clamps longitude/latitude before validating that the source coordinate is finite. With NaN, std::clamp returns NaN; point inputs can return tile-space Geometry containing NaN when clip = 0, and line/polygon inputs can feed non-finite coordinates into boost::geometry::intersection / boost::geometry::correct. That violates the contract that this function produces valid tile-space geometry or NULL.

Suggested fix: reject or convert to NULL any row with non-finite source coordinates before projection and before any Boost.Geometry call; add focused nan / inf regression tests for point, line, and polygon inputs.

Tests
  • ⚠️ Add the smallest stateless coverage for non-finite coordinates in MVTEncodeGeom, including at least clip = 0 for points and a clipped line or polygon path, so the function cannot emit or process NaN geometry.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: handle non-finite source coordinates before projection/Boost.Geometry, and update the PR changelog entry to use the registered MVT* function names.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 29, 2026
@Algunenano Algunenano self-assigned this May 29, 2026
Comment thread src/Functions/mvtEncodeGeom.cpp Resolved
- 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.
@CLAassistant

CLAassistant commented May 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread src/Functions/MVTEncodeGeom.cpp Resolved
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.
@saarthak2002

Copy link
Copy Markdown
Contributor Author

Hello,

Thanks for the review and assignment! The remaining red checks look like unrelated with this change:

  • Stateless tests (arm_asan_ubsan, targeted)
    [WARNING: Timeout exceeded [2818], sending SIGTERM to process group [5725]]
  • Integration tests (amd_tsan, 2/6)
    [test_kafka_read_consumers_in_parallel]

Could you re-run these two jobs when you get a chance please?

@Algunenano Algunenano 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.

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

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.

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.

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.

This is still an issue. The convention is to capitalize acronyms. Like JSONextract

Comment thread src/AggregateFunctions/MVTProtobuf.h Resolved
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
Comment thread src/Functions/MVTEncodeGeom.cpp Resolved
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 Algunenano 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.

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.
@saarthak2002

Copy link
Copy Markdown
Contributor Author

Changes as per review:

  • Functions have been renamed to follow conventions (MVTEncode, MVTEncodeGeom, MVTBoundingBox, MVTBoundingBoxMercator)
  • Feature id rejects signed integers
  • Tests have been updated to validate correct output for stringify_unsupported and feature_id_name for MVTEncode
  • Docs now describe the limitations about clipping and polygons

@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.40% 77.50% +0.10%

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

Full report · Diff report

@Algunenano Algunenano 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.

@saarthak2002 Thanks a lot. Looks great. I'll finish reviewing the (unrelated) CI failures and merge it

@Algunenano
Algunenano added this pull request to the merge queue Jun 22, 2026
Merged via the queue into ClickHouse:master with commit b162a39 Jun 22, 2026
323 of 328 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 22, 2026
@fm4v

fm4v commented Jun 30, 2026

Copy link
Copy Markdown
Member

@groeneai enrich tests: check boundary values and equivalence classes. Check results with standard.

@groeneai

Copy link
Copy Markdown
Collaborator

@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 04299_mvt_encode / 04300_mvt_clip, not weakening any existing assertion).

Plan, grounded in the actual code paths (MVTEncodeGeom.cpp, AggregateFunctionMVTEncode.cpp, MVTProtobuf.h):

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 CommandInteger/ParameterInteger geometry encoding, §4.4 the Value variants). Concretely:

  • Decode the produced tile back to a human-readable form in SQL and put the decoded command stream in the .reference (geometry type, MoveTo/LineTo/ClosePath ids + counts, zig-zag-decoded deltas, tags, value pool), so the reference shows what the spec says the bytes mean, not just an opaque hex blob.
  • Pin the spec's own example feature (the §4.3.5.1 single MoveTo point and the §4.3.5.4 polygon-with-2-rings command sequence [9 3 6 ... 15]) and assert our encoder produces exactly that command stream.

2. Boundary values. zoom 0 and 32; tile indices 0 and 2^zoom - 1 (already partly covered); extent 1 and 2147483647; buffer 0; coordinates exactly on the tile edge, one pixel inside, one pixel outside, and spanning the buffer; the Int32-delta and Int32-coordinate limits in MVTEncode; ties-to-even rounding at x.5; latitude exactly ±85.05112878; longitude wrap at ±180.

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 Int32::max); each MVTValueKind -> its Value field number (string/float/double/sint/uint/bool, FixedString trimming, stringify fallback, the Nullable/LowCardinality wrappers); feature-id present / NULL / rejected types; value interning (shared vs distinct); -State/-Merge round-trip.

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)?

@groeneai

Copy link
Copy Markdown
Collaborator

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.

pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Jul 1, 2026
….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]>
PedroTadim pushed a commit that referenced this pull request Jul 1, 2026
….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]>
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @saarthak2002 @Algunenano — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jul 20, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
….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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants