Skip to content

Gis geometry engine - #24777

Merged
fengttt merged 59 commits into
matrixorigin:mainfrom
fengttt:gis-geometry-engine
Jun 8, 2026
Merged

fengttt merged 59 commits into
matrixorigin:mainfrom
fengttt:gis-geometry-engine

Conversation

@fengttt

@fengttt fengttt commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #23913

What this PR does / why we need it:

  1. Implement geometry type using WKB format. Original storage used WKT, which is not good.
  2. For SRID 4326, used google S2 to compute geodetic length and area.
  3. Added functions like convex_hull.
  4. Added a type GEOMETRY32, which use float32 instead of float64.

TODO: Add special fixed length types like POINT2D, POINT3D, POINT2D32 etc, that is more efficient for storing points.
TODO: Use ellipsoid for SRID 4326. S2 is spherical.

@fengttt
fengttt requested a review from a user June 2, 2026 06:45
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

fengttt and others added 15 commits June 1, 2026 23:47
Add the GIS design (gis.md) and a detailed, phased implementation plan
(gisimpl.md). The plan covers: a self-contained pkg/geo engine (WKT/WKB
+ Cartesian/geodetic kernels), type & DDL integration with WKB stored in
the varlena (SRID held in the column type, cells are bare WKB), and the
spatial-function set with per-SRID dispatch and a +SRID override overload.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Create the self-contained pkg/geo package: the Subtype enum (0..7 matching
WKB type codes), SRID constants, the Geometry interface, and the seven
concrete kinds (Point, LineString, Polygon, Multi*, GeometryCollection).
No dependency on pkg/sql.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Recursive-descent ParseWKT covering all seven geometry kinds, the
"<TYPE> EMPTY" forms, nested GEOMETRYCOLLECTION, and both bare and
parenthesized MULTIPOINT. Case-insensitive and whitespace-tolerant;
rejects Z/M ordinates and malformed input.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
WriteWKT renders MySQL-compatible WKT (shortest round-trippable floats,
bare MULTIPOINT form, "<TYPE> EMPTY"). Verified by golden strings and
Parse->Write->Parse round-trips.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ReadWKB/WriteWKB for standard little-endian float64 WKB (type codes 1..7).
Writes little-endian; reads both byte orders per sub-geometry. Rejects Z/M
and EWKB-flagged codes and guards against oversized element counts. Output
is byte-compatible with PostGIS/MySQL ST_AsBinary (golden hex tests).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
WriteWKBFloat32/ReadWKBFloat32 share the recursive codec with the float64
path, differing only in 4-byte ordinates. WKBFloat32ToStandard up-converts
to standard float64 WKB so ST_AsWKB always emits interoperable bytes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Planar primitives: area (shoelace with holes), length, perimeter, envelope,
centroid (OGC dimension rule), min-distance with containment, point-in-
polygon, segment intersection, and line simplicity.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
DistanceMeters, LengthMeters, AreaSquareMeters, and point-in-polygon on the
sphere using github.com/golang/geo (S2), with EarthRadiusMeters as the
documented mean radius. Adds golang/geo as a direct dependency. Verified
against known great-circle distances within tolerance.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add types.T_geometry32 (=68), the float32-coordinate GEOMETRY32 type,
mirroring T_geometry across the type system: Types map, CharsetType
(binary), ToType/TypeLen/FixedLength (varlena, -24), String()=GEOMETRY32,
OidString()=T_geometry32, and the varlen case groups in encoding.go and
vector.go. SRID/subtype metadata wiring follows in later tasks.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Migrate the geometry column metadata off the plan.Type.Enumvalues string
to Scale (geo.Subtype enum) and Width (srid+1 when an SRID is declared, 0
otherwise — preserving the defined/undefined distinction). The runtime
cast_geometry_to_subtype validator is unchanged: funcCastForGeometryType
now derives the metadata string from Scale/Width at the bind boundary.

isGeometryPlanType also recognizes T_geometry32. Existing tests updated to
the new representation; dead decodeGeometryMetadata removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…(B3)

Add the GEOMETRY32/GEOGRAPHY/GEOGRAPHY32 and POINT32..GEOMETRYCOLLECTION32
spatial type keywords (non-reserved) to the MySQL grammar. tree.NewSpatialType
resolves each alias to a base subtype, a Float32 flag, and a default SRID
(GEOGRAPHY -> generic geometry, SRID 4326), recorded on tree.GeoMetadata.
getTypeFromAst maps the Float32 flag to T_geometry32 and the subtype/SRID to
Scale/Width. Parser regenerated with zero new conflicts.

The GEOMETRY(Type=..., SRID=...) / GEOMETRY('point', 4326) argument forms are
deferred: subtype and SRID are already expressible via the type-name aliases
and the existing `SRID n` column attribute.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cut geometry storage over from WKT text to bare standard WKB via pkg/geo:
encodeGeometryPayload now writes WKB and decodeGeometryPayload reads it
(tolerating legacy WKT text for back-compat). SRID is no longer in the
payload — it lives in the column/expression type (Width):

  - ST_SRID reads the input vector's type Width.
  - Geometry-producing functions copy the source SRID via retType
    (geometryResultType), so it propagates through ST_Centroid/ST_Boundary/...
  - ST_GeomFromText(wkt, srid) with a constant SRID records it in the result
    type Width via a binder hook in BindFuncExprImplByPlanExpr.
  - Binary spatial functions reject mismatched SRIDs at the type level
    (checkBinaryGeometryTypeSRID) instead of from the payload.

The function-test framework canonicalizes geometry (WKB or WKT) to WKT before
comparing, so existing WKT-based expectations still hold. Full function
package test suite passes.

Note: insert-time subtype/SRID enforcement (runtime cast_geometry_to_subtype)
and BVT .result regeneration for the new WKB representation are follow-ups.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add test/distributed/cases/geo/ covering the implemented GIS surface:
WKT/WKB I/O round-trips, GEOMETRY + subtype/GEOMETRY32/GEOGRAPHY DDL,
SHOW CREATE, storage and subtype enforcement, the unary accessors/measures/
derived-geometry functions, the binary distance and relationship predicates,
and SRID-in-type behavior (ST_GeomFromText(wkt, srid) + ST_SRID propagation,
binary SRID-mismatch rejection).

These are .sql inputs; .result files are generated with mo-tester (-m genrs)
against a running server, per the directory README. Tests deliberately avoid
the not-yet-implemented paths (insert into SRID-constrained columns,
GEOMETRY32 value storage, geodetic computation).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Remove github.com/ashvardanian/stringzilla/golang, which is not imported
anywhere in the module, bringing go.mod/go.sum to the `go mod tidy` state.
The golang/geo dependency used by pkg/geo was added in the geodetic-kernel
commit and remains.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Martinez-Rueda overlay backed the event queue and status line with sorted
slices: queue push was O(n) (so just loading n edges was O(n^2), even with no
intersections), and the status line did O(n) insert/remove plus a linear
indexOf. Large boolean ops degraded toward O(n^2).

- Event queue -> container/heap min-heap (compareEvents): O(log n) push/pop.
- Status line -> hand-rolled AVL keyed by compareSegments (+monotonic seq
  tiebreaker for a strict total order); each event stores its node, so removal
  and prev/next neighbor lookup are O(log n) with no linear scan.

pkg/geo stays dependency-free (only container/heap). Behavior is unchanged;
overlay_test.go and the geo BVT (ST_Union/Intersection/Difference/SymDifference,
ST_Buffer) pass. Added BenchmarkOverlayUnion{256,1024,4096}: 16x input size now
costs ~23x time (was ~256x for O(n^2)), confirming O(n log n).

Addresses @XuPeng-SH's review note on the overlay hot path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@fengttt

fengttt commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH — re: the overlay sweep-line complexity (pkg/geo/overlay.go), the comment was valid, so I went ahead and fixed it in ff8a03d rather than leaving it as-is:

  • Event queue → container/heap min-heap (ordered by compareEvents): O(log n) push/pop. The old sorted-slice push was O(n), so just loading n edges was O(n²) even with zero intersections — that unconditional quadratic term is gone.
  • Status line → a hand-rolled AVL keyed by compareSegments (with a monotonic seq tiebreaker for a strict total order). Each event stores its tree node, so removal and prev/next neighbor lookup are O(log n) — replacing the O(n) slice insert/remove and the linear indexOf.

pkg/geo stays dependency-free (only container/heap). Behavior is unchanged: overlay_test.go and the geo BVT (ST_Union/Intersection/Difference/SymDifference, ST_Buffer) all pass. Added BenchmarkOverlayUnion{256,1024,4096} as a regression guard — 16× input size now costs ~23× wall-clock (vs ~256× for the previous O(n²)), confirming O((n+k) log n).

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

独立深审结论:请求修改(Request changes)

在 @XuPeng-SH 已提的两点(overlay O(n²)、SRID 4326 平面→大地行为变更)之外,我对 WKB/WKT 解析、存储/类型/cast 集成、计算几何算法、函数注册与 bootstrap 升级做了一轮独立审查,核实出以下问题(已逐一对照代码确认,部分经构造输入实测复现)。

🔴 Blocking — 可被恶意/异常输入触发整个 CN 进程崩溃

  1. pkg/geo/wkb_read.go:179 readGeometry 对嵌套 GeometryCollection 无限递归,无深度上限。构造层层嵌套的 GEOMETRYCOLLECTION(每层仅 9 字节)即可让 goroutine 栈增长到 Go 1GB 硬上限,触发 fatal error: stack overflow。这是 runtime fatal error,recover() 无法捕获 → 整个 server 进程被杀。经由 ST_GeomFromWKB / 存储列值可达,已构造 payload 实测复现。建议:在 wkbReader 上传递并校验递归深度(参考 PostGIS/GEOS 的上限)。
  2. pkg/geo/wkt_parse.go:220 parseGeometryCollection→parseGeometry 同样无界递归,文本路径相同崩溃,经 ST_GeomFromText 可达,已实测复现。建议同上,与 WKB 共用深度限制。
    • 备注:GeoJSON 路径不受影响,encoding/json 自带最大嵌套深度,会被干净拒绝。

🟠 High — GEOMETRY32 结果集输出报错

  1. pkg/frontend/output.go convertVectorToSlice(约 768 行)漏了 T_geometry32。本 PR 已把三个消费端(extractRowFromVector2、GetBytesBased 等,见 96/225/599 行)更新为 case T_geometry, T_geometry32,但生产端 convertVectorToSlice 仍只有 T_geometry,GEOMETRY32 落入 default 返回 convertVectorToSlice : unsupported type。任何含 GEOMETRY32 列、走 column-slice 输出路径的查询都会直接报错。建议在该 case 补上 types.T_geometry32。

�� Medium

  1. pkg/sql/plan/function/func_cast.go strToStr:CAST(geometry AS CHAR/VARCHAR/TEXT) 输出原始 WKB 字节而非 WKT。WKB→WKT 解码只在“目标类型是 geometry/geometry32”分支里做;当“源是 geometry、目标是字符类型”时直接落到通用拷贝路径吐出存储的裸 WKB(乱码)。本 PR 显式开放了 geometry→char/varchar/text 这条 cast(supportedTypeCast 367-376),理应解码成 WKT。建议:源为 geometry/geometry32 且目标为字符/文本类型时,走 decodeGeometryPayload 输出 WKT(转 binary/varbinary 保留裸 WKB 可接受)。
  2. pkg/geo/simplify.go:91 douglasPeucker 会改写调用方输入切片。append(left[:len(left)-1], right...) 在 left 别名原始 pts 时(base case len(pts)<3 直接 return pts)会写入调用方的 backing array。Simplify 直接传入几何自身的坐标切片;尤其 simplifyRings(58-62 行)在退化分支 out[i] = r 会把被污染的原始 ring 作为输出返回,导致结果错误。已构造输入实测复现(约 23% 随机输入触发输入被改写)。建议 base case 返回拷贝,或将结果写入新分配的切片,确保不写入输入。

关联提示(非本 PR diff 内,供参考)

  • pkg/frontend/data_branch_helpers.go:657 的 compareSingleValInVector 同样只列了 T_geometry、未含 T_geometry32,data-branch 比较涉及 GEOMETRY32 列时会落 default 报错。该文件本 PR 未改动,属新类型暴露出的既有缺口,建议一并补齐。

✅ 已核实无问题

函数 ID 分配(严格追加未重排,FUNCTION_END_NUMBER 一致)、ST_* 注册与实现的入参/返回类型匹配、bootstrap 升级幂等;类型系统元数据(types.go/encoding.go/vector.go)对 GEOMETRY32 处理一致;hull/cartesian/geodetic/buffer 等算法的退化输入与除零保护;WKB reader 的 count/长度字段均有 remaining() 边界校验,无 OOB/OOM。

Comment thread pkg/geo/wkb_read.go Resolved
Comment thread pkg/geo/wkt_parse.go Resolved
Comment thread pkg/frontend/output.go Resolved
Comment thread pkg/sql/plan/function/func_cast.go Resolved
Comment thread pkg/geo/simplify.go Resolved
@LeftHandCold

Copy link
Copy Markdown
Collaborator

更新:已对照最新 head(ff8a03d3d6)复核我上一轮 review 的 5 条。新推的 913103bd89/ff8a03d3d6 是针对 @XuPeng-SH 第二轮的修改,恰好覆盖了我的其中一条。逐条状态:

  • 🟡 More documents are needed in Github REPO #4 CAST(geometry AS CHAR/VARCHAR/TEXT) 输出 WKT — ✅ 已由 913103bd89(geometryToTextCast)修复。
  • 🔴 Add README.md #1 pkg/geo/wkb_read.go:179 嵌套 GeometryCollection 无界递归 → 栈溢出 fatal(不可 recover) — ❗仍未处理(readGeometry() 签名/实现未变,无深度上限)。
  • 🔴 integrate mysql parser from pingcap #2 pkg/geo/wkt_parse.go WKT 路径同样无界递归 — ❗仍未处理。
  • 🟠 Add PR template file #3 pkg/frontend/output.go:768 convertVectorToSlice 仍只列 T_geometry、漏 T_geometry32(消费端 94/225/599 已支持)→ GEOMETRY32 列走 column-slice 输出仍会 unsupported type 报错 — ❗仍未处理。913103bd89 补的是若干 ST_* 函数的 geometry32 overload,未覆盖此处。
  • 🟡 [#4] Add a new document: CHANGELOG.md #5 pkg/geo/simplify.go:91 douglasPeucker 复用 left backing array 改写输入,simplifyRings 退化分支 out[i]=r 会输出被污染的 ring — ❗仍未处理(实现未变)。

#1/#2 是 blocking,建议优先补递归深度上限。

…ify aliasing

Addresses @LeftHandCold's review:

- (blocking) WKB/WKT parsers recursed without bound on nested GEOMETRYCOLLECTION,
  reaching Go's hard stack limit -> uncatchable `fatal error: stack overflow`
  (process killed), reachable via ST_GeomFromWKB / ST_GeomFromText and column
  values. Thread a depth through wkbReader.readGeometry and wktParser parse,
  rejecting nesting beyond maxGeometryNestingDepth (64, matching the SQL layer)
  with a clear error before any overflow.
- (high) convertVectorToSlice's varlena case omitted T_geometry32, so any query
  emitting a GEOMETRY32 column via the column-slice path failed with
  "unsupported type". Added T_geometry32.
- (medium) douglasPeucker's base case returned the input's backing array, and
  the recursive append(left[:len(left)-1], ...) then overwrote the caller's
  coordinates; simplifyRings' degenerate branch emitted the corrupted ring.
  The base case now returns a copy.

Adds regression tests (nesting bounded + no crash for both parsers, Simplify
non-mutation). geo dir 378 + func_geometry 763 BVT pass; static-check clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@fengttt

fengttt commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @LeftHandCold — all five points are now handled (#4 was already covered by the earlier geometryToTextCast change):

  • 🔴 Add README.md #1 WKB unbounded recursion & 🔴 integrate mysql parser from pingcap #2 WKT unbounded recursion — 9c10fcff9c. Both parsers now thread a depth and reject GEOMETRYCOLLECTION nesting beyond a shared maxGeometryNestingDepth (64, matching the SQL layer's maxGeometryCollectionNestingDepth) before recursing, returning a normal error instead of reaching the unrecoverable fatal error: stack overflow. Regression tests cover 64 (ok) / 65 (error) / 200000 (error, no crash) for both ReadWKB and ParseWKT.
  • 🟠 Add PR template file #3 GEOMETRY32 column output — 9c10fcff9c. Added types.T_geometry32 to the varlena case in convertVectorToSlice; a query selecting a GEOMETRY32 column via the column-slice path no longer fails with "unsupported type".
  • 🟡 More documents are needed in Github REPO #4 CAST(geometry AS CHAR/VARCHAR/TEXT) → WKT — already fixed in 913103bd89 (geometryToTextCast).
  • 🟡 [#4] Add a new document: CHANGELOG.md #5 douglasPeucker input aliasing — 9c10fcff9c. The base case returns a copy instead of the input backing array, so the recursive append can't overwrite the caller's coordinates and simplifyRings no longer emits a corrupted ring. Regression test asserts Simplify doesn't mutate its input.

geo dir (378) and func_geometry (763) BVT pass; pkg/geo/function/plan unit tests and make static-check are clean.

@aunjgr aunjgr left a comment

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.

Impressive breadth — ~30 new pkg/geo/ primitives, full WKB/WKT round-trip, function registration for 100+ spatial functions. A few concerns:

Correctness

1. Spatial predicates are Cartesian-only; no SRID dispatch (pkg/sql/plan/function/func_binary.go).

All 10 relationship predicates (ST_Contains, ST_Within, ST_Intersects, ST_Disjoint, ST_Touches, ST_Crosses, ST_Overlaps, ST_Equals, ST_Covers, ST_CoveredBy) call checkBinaryGeometryTypeSRID to validate matching SRIDs, then always execute Cartesian math. For SRID 4326 columns, ST_Contains/ST_Within/etc. silently return planar results instead of geodetic. The design doc (gisimpl.md) explicitly requires Cartesian+geodetic dispatch for these. The ST_Distance/ST_Length/ST_Area functions correctly dispatch on SRID via geometryDistanceBySRID etc. — the predicates should follow the same pattern.

Scope concerns

2. geometryToTextCast drops SRID prefix (pkg/sql/plan/function/func_cast.go). decodeGeometryPayload discards the SRID return value (_). MySQL emits SRID=4326;POINT(1 2) for SRID-carrying values. Reasonable to defer, but a follow-up issue should track this.

3. WKB constructor functions return T_geometry with Width=0 (pkg/sql/plan/function/list_builtIn.go). ST_PointFromWKB, ST_GeomFromWKB, etc. always produce a type with no SRID, regardless of the WKB contents. Since bare WKB has no SRID field, this is correct — but consider an ST_PointFromWKB(wkb, srid) overload for parity with MySQL.

4. Phase C +SRID override overloads not implemented (gisimpl.md D6). Measurement/predicate functions lack the [geometry, int64] trailing-SRID-argument overload. Scope gap relative to the design.

Hardening

5. pointInRing ray-casting lacks epsilon (pkg/geo/cartesian.go). The comparison c.X < xint uses exact float64. When xint is within machine epsilon of c.X (ray passes near a vertex), floating-point noise can flip the result. Standard practice adds xint + epsilon.

6. ringSignedArea does not enforce ring closure (pkg/geo/cartesian.go). WKB requires first==last for rings; the shoelace loop wraps via % n which treats any ring as closed, silently accepting non-conformant input.

7. ST_X/ST_Y return float32 for GEOMETRY32 (pkg/sql/plan/function/list_builtIn.go). MySQL always returns DOUBLE. This is a deliberate MatrixOne extension but diverges from MySQL. Worth a comment in the code or docs.

Verified correct

  • WKB read/write with endianness handling. SRID encoding via Width = srid + 1 avoids 0-vs-undefined collision.
  • Cartesian kernel covers area, length, distance, bearing, line intersection, ring orientation, polygon validation, convex hull, Douglas-Peucker simplification.
  • Geodetic kernel has distance/length/area on the WGS84 ellipsoid and point-in-polygon.
  • Parser grammar for spatial type syntax (GEOMETRY, POINT, LINESTRING, etc.) is backward-compatible.
  • Bootstrap upgrade for geometry type registration and COLUMNS/DATA_TYPE display.

…QL DOUBLE

Per @aunjgr's review: document that the GEOMETRY32 coordinate-accessor
overloads intentionally return float32 (matching the stored coordinate width),
unlike MySQL's ST_X/ST_Y which always return DOUBLE. Plain GEOMETRY still
returns float64.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@fengttt

fengttt commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @aunjgr — point by point:

Correctness

1. Geodetic dispatch for the relationship predicates — valid gap vs. gisimpl.md D5/§1.5. It's a deliberate scoping choice for this PR, not an oversight: the geodetic kernel currently has the metric operations (distance/length/area) and point-in-polygon, but not a full spherical relationship engine (geodetic segment/segment and polygon/polygon intersection for ST_Touches/ST_Crosses/ST_Overlaps/line-line ST_Intersects, etc.). Doing only the point-in-polygon-reducible predicates geodetically would be inconsistent (some pairs geodetic, some planar), so it's all-or-nothing and a sizable follow-up phase. The current planar behavior for SRID 4326 predicates is what the existing BVT encodes. I'll track geodetic predicate dispatch (+ the §1.5 +SRID overload for predicates, see #4) as a follow-up issue rather than land a partial/risky version here.

Scope

2. geometryToTextCast drops the SRID prefix — intentional for now: it mirrors ST_AsText, which also returns plain WKT (POINT(1 2)), as does MySQL's ST_AsText/CAST … AS CHAR. Emitting EWKT (SRID=4326;…) would make the cast diverge from ST_AsText; I'll track an EWKT-output option as a follow-up.

3. WKB constructors → Width=0 — agreed it's correct (bare WKB has no SRID). An ST_PointFromWKB(wkb, srid) / ST_GeomFromWKB(wkb, srid) overload for MySQL parity is a reasonable follow-up; tracking it.

4. Phase-C +SRID overloads — present for the measures (ST_Area/ST_Length/ST_Distance have the [geometry, int64] form, bc523fc06e). The predicate +SRID overloads are coupled to #1 (they only mean something once predicates dispatch on SRID), so they go in the same follow-up.

Hardening

5. pointInRing epsilon — this is the standard PNPOLY (W. R. Franklin) ray test; its robustness comes from the half-open crossing rule (yi > c.Y) != (yj > c.Y), which gives a consistent answer at vertices, rather than from an epsilon on c.X < xint. Boundary points (where the near-edge ambiguity actually matters) are handled separately with tolerance via pointOnRing/pointOnSegment before the interior test. Adding an epsilon to PNPOLY can double-flip parity, so I'd prefer to leave the algorithm intact.

6. ringSignedArea closure — the shoelace loop's j = (i+1) % n computes the correct signed area for both closed and open rings (a properly closed ring's first==last vertex makes the wrap edge contribute zero), so it's tolerant rather than wrong. Ring closure conformance is validated at the WKB/WKT parse layer, so the kernel helper doesn't re-reject it.

7. ST_X/ST_Y float32 for GEOMETRY32 — documented in 284af6ace8: added a comment on StX32/StY32 noting it's a deliberate MatrixOne extension (float32 to match the stored coordinate width) vs. MySQL's DOUBLE; plain GEOMETRY still returns float64.

@fengttt

fengttt commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

Impressive breadth — ~30 new pkg/geo/ primitives, full WKB/WKT round-trip, function registration for 100+ spatial functions. A few concerns:

Correctness

1. Spatial predicates are Cartesian-only; no SRID dispatch (pkg/sql/plan/function/func_binary.go).

All 10 relationship predicates (ST_Contains, ST_Within, ST_Intersects, ST_Disjoint, ST_Touches, ST_Crosses, ST_Overlaps, ST_Equals, ST_Covers, ST_CoveredBy) call checkBinaryGeometryTypeSRID to validate matching SRIDs, then always execute Cartesian math. For SRID 4326 columns, ST_Contains/ST_Within/etc. silently return planar results instead of geodetic. The design doc (gisimpl.md) explicitly requires Cartesian+geodetic dispatch for these. The ST_Distance/ST_Length/ST_Area functions correctly dispatch on SRID via geometryDistanceBySRID etc. — the predicates should follow the same pattern.

Scope concerns

2. geometryToTextCast drops SRID prefix (pkg/sql/plan/function/func_cast.go). decodeGeometryPayload discards the SRID return value (_). MySQL emits SRID=4326;POINT(1 2) for SRID-carrying values. Reasonable to defer, but a follow-up issue should track this.

3. WKB constructor functions return T_geometry with Width=0 (pkg/sql/plan/function/list_builtIn.go). ST_PointFromWKB, ST_GeomFromWKB, etc. always produce a type with no SRID, regardless of the WKB contents. Since bare WKB has no SRID field, this is correct — but consider an ST_PointFromWKB(wkb, srid) overload for parity with MySQL.

4. Phase C +SRID override overloads not implemented (gisimpl.md D6). Measurement/predicate functions lack the [geometry, int64] trailing-SRID-argument overload. Scope gap relative to the design.

Hardening

5. pointInRing ray-casting lacks epsilon (pkg/geo/cartesian.go). The comparison c.X < xint uses exact float64. When xint is within machine epsilon of c.X (ray passes near a vertex), floating-point noise can flip the result. Standard practice adds xint + epsilon.

6. ringSignedArea does not enforce ring closure (pkg/geo/cartesian.go). WKB requires first==last for rings; the shoelace loop wraps via % n which treats any ring as closed, silently accepting non-conformant input.

7. ST_X/ST_Y return float32 for GEOMETRY32 (pkg/sql/plan/function/list_builtIn.go). MySQL always returns DOUBLE. This is a deliberate MatrixOne extension but diverges from MySQL. Worth a comment in the code or docs.

Verified correct

  • WKB read/write with endianness handling. SRID encoding via Width = srid + 1 avoids 0-vs-undefined collision.
  • Cartesian kernel covers area, length, distance, bearing, line intersection, ring orientation, polygon validation, convex hull, Douglas-Peucker simplification.
  • Geodetic kernel has distance/length/area on the WGS84 ellipsoid and point-in-polygon.
  • Parser grammar for spatial type syntax (GEOMETRY, POINT, LINESTRING, etc.) is backward-compatible.
  • Bootstrap upgrade for geometry type registration and COLUMNS/DATA_TYPE display.

Regarding to Correctness.

For all the function mentioned the result should be SAME regardless if the computation is done in Cartesian or geodetic -- unless the there is a polygon near/contains north or south pole, or cross the longitude line +- 180 (roughly IDL). We will take this implementation for now, defer these corner case handling.

@fengttt

fengttt commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

Impressive breadth — ~30 new pkg/geo/ primitives, full WKB/WKT round-trip, function registration for 100+ spatial functions. A few concerns:

Correctness

1. Spatial predicates are Cartesian-only; no SRID dispatch (pkg/sql/plan/function/func_binary.go).
All 10 relationship predicates (ST_Contains, ST_Within, ST_Intersects, ST_Disjoint, ST_Touches, ST_Crosses, ST_Overlaps, ST_Equals, ST_Covers, ST_CoveredBy) call checkBinaryGeometryTypeSRID to validate matching SRIDs, then always execute Cartesian math. For SRID 4326 columns, ST_Contains/ST_Within/etc. silently return planar results instead of geodetic. The design doc (gisimpl.md) explicitly requires Cartesian+geodetic dispatch for these. The ST_Distance/ST_Length/ST_Area functions correctly dispatch on SRID via geometryDistanceBySRID etc. — the predicates should follow the same pattern.

Scope concerns

2. geometryToTextCast drops SRID prefix (pkg/sql/plan/function/func_cast.go). decodeGeometryPayload discards the SRID return value (_). MySQL emits SRID=4326;POINT(1 2) for SRID-carrying values. Reasonable to defer, but a follow-up issue should track this.
3. WKB constructor functions return T_geometry with Width=0 (pkg/sql/plan/function/list_builtIn.go). ST_PointFromWKB, ST_GeomFromWKB, etc. always produce a type with no SRID, regardless of the WKB contents. Since bare WKB has no SRID field, this is correct — but consider an ST_PointFromWKB(wkb, srid) overload for parity with MySQL.
4. Phase C +SRID override overloads not implemented (gisimpl.md D6). Measurement/predicate functions lack the [geometry, int64] trailing-SRID-argument overload. Scope gap relative to the design.

Hardening

5. pointInRing ray-casting lacks epsilon (pkg/geo/cartesian.go). The comparison c.X < xint uses exact float64. When xint is within machine epsilon of c.X (ray passes near a vertex), floating-point noise can flip the result. Standard practice adds xint + epsilon.
6. ringSignedArea does not enforce ring closure (pkg/geo/cartesian.go). WKB requires first==last for rings; the shoelace loop wraps via % n which treats any ring as closed, silently accepting non-conformant input.
7. ST_X/ST_Y return float32 for GEOMETRY32 (pkg/sql/plan/function/list_builtIn.go). MySQL always returns DOUBLE. This is a deliberate MatrixOne extension but diverges from MySQL. Worth a comment in the code or docs.

Verified correct

  • WKB read/write with endianness handling. SRID encoding via Width = srid + 1 avoids 0-vs-undefined collision.
  • Cartesian kernel covers area, length, distance, bearing, line intersection, ring orientation, polygon validation, convex hull, Douglas-Peucker simplification.
  • Geodetic kernel has distance/length/area on the WGS84 ellipsoid and point-in-polygon.
  • Parser grammar for spatial type syntax (GEOMETRY, POINT, LINESTRING, etc.) is backward-compatible.
  • Bootstrap upgrade for geometry type registration and COLUMNS/DATA_TYPE display.

Regarding to Correctness.

For all the function mentioned the result should be SAME regardless if the computation is done in Cartesian or geodetic -- unless the there is a polygon near/contains north or south pole, or cross the longitude line +- 180 (roughly IDL). We will take this implementation for now, defer these corner case handling.

True/Robust computing of these should happen in S2 geometry. For example, see discussions in golang/geo#44

@aunjgr aunjgr left a comment

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.

Re-reviewed. Updates since my last review:

Addressed:

  • ringSignedArea now handles both closed and unclosed rings (comment says "may or may not repeat its first point").
  • Epsilon constant (1e-12) added to pkg/geo/cartesian.go for floating-point comparisons.
  • checkBinaryGeometryTypeSRID added to all 10 spatial predicates — SRID mismatch now returns an error instead of silently mixing SRIDs.
  • ST_X/ST_Y GEOMETRY32 float32 return documented per the latest commit.
  • Parser nesting depth bounded, GEOMETRY32 column output fixed.

Still pending (Phase C per design doc):

  • Predicate SRID dispatch: predicates now validate matching SRIDs but still use Cartesian math for all SRIDs. Geodetic predicates (ST_Contains on SRID 4326) are explicitly Phase C in gisimpl.md.
  • +SRID override overloads, WKT SRID prefix on text cast.

Given the design doc phases these remaining items into Phase C, this is a clean Phase A/B implementation. LGTM.

@XuPeng-SH XuPeng-SH left a comment

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.

这轮我按高标准多角度看下来,有几处我认为需要在这个 PR 里修掉的实质问题:

  1. ST_Distance_Sphere 现在没有执行它应有的 SRID / 类型 / 坐标范围约束
    pkg/sql/plan/function/func_binary.go 里 stDistanceSphere 直接 decodeGeoGeometry() 后就调用 geo.DistanceMeters() 了,但这条路径没有像 ST_Distance 那样做 checkBinaryGeometryTypeSRID(),也没有限制输入只能是 Point / MultiPoint,更没有检查经纬度范围。

    现在的实现实际上会把任意 geometry 都当作 geodetic kernel 的输入去算,而且对 SRID 0 / 4326 / mixed SRID / projected SRS 也不拦。MySQL 对 ST_Distance_Sphere 的约束要严格得多,这里会产生明显的语义偏差。

  2. 显式 SRID 参数有无符号截断问题
    stDistanceWithSRID / stLengthWithSRID / stAreaWithSRID 都把 int64 srid 直接做了 uint32(srid) 转换。这样负 SRID 或超出 uint32 的值会静默 wrap/truncate,而不是报错。比如 -1 会变成 4294967295,然后直接走错误的 kernel 选择。这里至少应该在 cast 前做范围校验。

  3. geodetic ring 上无条件 Normalize() 会把大于半球的 polygon 反成补集
    pkg/geo/geodetic.go 的 loopFromRing() 里直接对用户 ring 做 loop.Normalize()。S2 的这个 API 会选择“较小的那个区域”,所以对于 exterior 覆盖超过半球的 polygon,几何语义会被翻成补集,进而影响 geodetic area / containment / distance(contains short-circuit) 这些结果。这不是小误差,而是区域语义被反了。

  4. WKB 读取仍然接受半个 NaN 点
    pkg/geo/wkb_read.go 里 point 只把 (NaN, NaN) 识别成 empty point,但 (NaN, 1) 或 (1, NaN) 会被当成普通 point 返回。这样 malformed / hostile WKB 可以构造出带单边 NaN 的几何,后续很多几何计算都会被污染。这里至少应该拒绝“不是 empty-point 模式的任何 NaN 坐标”。

  5. overlay snap rounding 对大坐标会发生整数溢出
    pkg/geo/overlay.go 里 ovRound() 通过 int64(x +/- 0.5) 做 rounding,而调用方先把坐标乘了 1e9。这意味着只要原始坐标量级超过大约 9.22e9,这里就会在 cast 到 int64 时溢出,overlay 结果会直接错掉。geometry 坐标现在并没有这样的输入上界保护,所以这不是纯理论问题。

我建议先把这几处收敛掉,再继续往后看。

… SRID range, geodetic winding, NaN/overflow guards

Resolves XuPeng-SH's review on PR matrixorigin#24777:

1. ST_Distance_Sphere now enforces matching SRID, POINT/MULTIPOINT-only
   inputs, and valid lon/lat ranges instead of feeding any geometry to the
   geodetic kernel.
2. Explicit SRID arguments (ST_Distance/ST_Length/ST_Area) are range-checked
   before narrowing to uint32, rejecting negative/oversized values that used
   to silently wrap (-1 -> 4294967295).
3. loopFromRing follows the ring's winding instead of unconditional
   s2.Loop.Normalize(), which turned larger-than-hemisphere polygons into
   their complement (inverted area/containment).
4. WKB reader rejects half-NaN points and NaN coordinates in any sequence;
   only (NaN, NaN) remains the empty-point sentinel.
5. overlay ovRound uses math.Round, so large coordinates no longer overflow
   int64 after the 1e9 snap scaling and corrupt the result.

Adds geo_review_fixes2 BVT coverage for all five.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@fengttt

fengttt commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @XuPeng-SH — all five addressed in 63e4d75.

  1. ST_Distance_Sphere 约束 — now calls checkBinaryGeometryTypeSRID (matching SRID), restricts inputs to POINT/MULTIPOINT via validateDistanceSphereGeometry, and validates lon ∈ [-180,180] / lat ∈ [-90,90]. Anything else errors instead of being fed to the geodetic kernel.

  2. 显式 SRID 截断 — added sridFromInt64Arg, which range-checks [0, 4294967295] before narrowing to uint32. stDistanceWithSRID / stLengthWithSRID / stAreaWithSRID all use it, so -1 / oversized SRIDs now error rather than wrapping.

  3. geodetic ring Normalize() — loopFromRing no longer calls s2.Loop.Normalize(); it orients the loop by the ring's planar winding (CCW = interior on the left) so a larger-than-hemisphere polygon keeps its true region instead of flipping to the complement. (Pole/antimeridian spanning rings remain the deferred corner case.)

  4. 半个 NaN 点 — wkb_read.go now rejects any single-NaN point (only (NaN, NaN) stays the empty-point sentinel) and rejects NaN in readCoords, so malformed WKB can't inject NaN into linestrings/rings either.

  5. overlay ovRound 溢出 — switched to math.Round (pure float64), so coordinates beyond ~9.22e9 no longer overflow int64 after the 1e9 snap scaling.

Added geo_review_fixes2 BVT coverage for all five. Full geo suite: 395/395 pass.

# Conflicts:
#	pkg/sql/parsers/dialect/mysql/mysql_sql.go
#	pkg/sql/plan/function/function_id.go
#	pkg/sql/plan/function/function_id_test.go
#	pkg/sql/plan/mysql_special_types.go

@LeftHandCold LeftHandCold left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我又复核了一轮最新 head,还有一个我认为需要在这个 PR 里收掉的 correctness 问题:

ST_Length / ST_Area / ST_Distance 的 SRID dispatch 现在只对 4326 走 geodetic,其它任何 SRID 都静默落回 Cartesian:

  • geometryLengthBySRID: if srid == geo.SRIDWGS84 { ... } return geometryLength(...)
  • geometryAreaBySRID: if srid == geo.SRIDWGS84 { ... } return geometryArea(...)
  • geometryDistanceBySRID: if srid == geo.SRIDWGS84 { ... } return geometryDistance(...)

这会让 ST_Area(g, 3857)、ST_Distance(a, b, 3857),以及两个 geometry srid 3857 输入在没有任何 warning/error 的情况下按 unitless planar 逻辑计算。PR 自带的设计文档仍然明确写了 dispatch 规则是 0 -> Cartesian、4326 -> geodetic、other -> error,pkg/geo/consts.go 里的 SupportedSRID 注释也说其它 SRID 应该被 computation kernels reject。最新的 sridFromInt64Arg 只校验了 uint32 范围,没有校验 supported set,所以 3857 这类值仍会穿透。

建议把计算 SRID 的校验集中到一个 shared helper,所有从 type Width 读取 SRID 和显式 +SRID 参数的路径都先要求 srid == 0 || srid == 4326,否则返回 unsupported SRID error。同时补上 BVT/UT 覆盖:显式 ST_Area(..., 3857) / ST_Distance(..., ..., 3857),以及 matching type SRID 3857 的输入不应静默返回 Cartesian 结果。

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

…T_Distance

Resolves LeftHandCold's review on PR matrixorigin#24777.

The SRID dispatch only routed 4326 to the geodetic kernel; every other SRID
(e.g. the projected system 3857) silently fell back to unitless Cartesian math,
returning a semantically wrong result with no warning. The design doc and
pkg/geo/consts.go SupportedSRID contract require 0 -> Cartesian, 4326 ->
geodetic, other -> error.

Add a single shared gate, validateComputationSRID, called at the top of the
three *BySRID dispatch helpers (geometryLengthBySRID / geometryAreaBySRID /
geometryDistanceBySRID). Every ST_Length/ST_Area/ST_Distance path funnels
through these, so both the type-Width SRID and the explicit +SRID argument are
now validated against {0, 4326}; anything else returns an unsupported-SRID error.

Adds geo_review_fixes3 BVT coverage for explicit and type-carried 3857 on all
three functions, plus the supported 0/4326 happy paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@fengttt

fengttt commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @LeftHandCold — fixed in 1ef4726.

Added a single shared gate validateComputationSRID(srid) (backed by the existing geo.SupportedSRID) and call it at the top of the three dispatch helpers geometryLengthBySRID / geometryAreaBySRID / geometryDistanceBySRID. Every ST_Length / ST_Area / ST_Distance path funnels through these, so both the type-Width SRID and the explicit +SRID argument are now validated against {0, 4326}; anything else (e.g. 3857) returns:

unsupported SRID 3857 for spatial computation; only 0 and 4326 are supported

instead of silently falling back to unitless Cartesian. sridFromInt64Arg still handles the uint32-range check first, then this gate enforces the supported set.

BVT coverage in geo_review_fixes3: explicit ST_Area/ST_Length/ST_Distance(..., 3857) and type-carried SRID 3857 inputs on all three functions all error; the 0/4326 happy paths still compute. Full geo suite: 409/409 pass.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/refactor Code refactor size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants