Skip to main content

waratah_geo/
encode.rs

1//! Geo literal encode: WKT/WKB parse → CRS84 transform → validation →
2//! native [`EncodedTerm`] (+ blob EWKB + S2 postings) or hashed typed
3//! literal fallback.
4//!
5//! Locked decisions (GeoSPARQL plan §1):
6//! - internal coordinates / blob EWKB / S2 cells are **always CRS84 f64**
7//!   (lon/lat);
8//! - the ingest `CrsId` rides the term so output can transform back;
9//! - parse-well-formed is NOT enough: [`geo::algorithm::Validation`] runs
10//!   after the transform. The validation wrapper tolerates within-threshold
11//!   `MultiPolygon` member contact and exactly collinear zero-area ring spikes;
12//!   every other failure is a hard stored-geometry error, so a trusted index
13//!   never silently omits a geo literal. A tolerated spike keeps its original
14//!   EWKB and sets `LiteralGeometry::requires_spike_reduction`; only its spatial
15//!   execution geometry is reduced. Query-authored constants may still use the
16//!   hashed typed literal fallback because they are not index entries;
17//! - `Other`/untransformable CRS and unsupported storage shapes follow the
18//!   same stored-geometry error rule.
19//!
20//! Z / M / EMPTY routing contract (owner decision — routing is by STORAGE
21//! SHAPE, never a rejection of higher dimensions):
22//! - a point with only 2 axes stays the inline [`EncodedTerm::LiteralPoint`]
23//!   (unchanged);
24//! - everything else — Z/M points and all non-point geometries — becomes
25//!   [`EncodedTerm::LiteralGeometry`] with an **axis-preserving canonical
26//!   EWKB blob** (`waratah_geo/src/canonical.rs`): CRS84 x/y per the
27//!   axis-order contract below, with **z and m passed through unchanged**.
28//!   Z is NOT datum-transformed (the PROJ pipelines are 2D; a documented v1
29//!   approximation); m is not a spatial axis at all. The 2D projection, after
30//!   any tolerated spike reduction, continues to drive validity, envelope, S2
31//!   postings, and Relate;
32//! - EMPTY geometries (both syntaxes) are NOT native: they take the hashed
33//!   typed-literal fallback (plain String+Datatype `EncodedTerm`, original
34//!   lexical preserved byte-exactly by the registry) — no EWKB blob, no
35//!   postings, no S2 index, and the geo custom fns treat them as type
36//!   errors by design;
37//! - mixed-dimension collections are canonicalized with the TOP-LEVEL
38//!   dimensions applied uniformly (geozero's `WkbWriter` stamps dims into
39//!   every nested header and defaults missing z/m to 0.0) — a documented
40//!   edge case.
41//!
42//! WKT prepass bound (owner decision): all WKT prepass work — the
43//! CRS-prefix detach ([`split_crs_prefix`]) and the shape-trait detect
44//! ([`detect_wkt_shape_traits`]) — is O(window) on the leading bytes
45//! (256-byte CRS window, 1000-byte normalized detect window), never a
46//! full-text pass. Residual miss class, silent by design: CRS prefixes
47//! beginning after the 256-byte window, and shape markers outside the
48//! paren-bounded 1000-byte region (pathological leading whitespace, or
49//! nested members — the latter by design), are not detected; such literals
50//! ingest as 2D or fall back via the parse.
51//!
52//! Axis order is a property of the SERIALIZATION FORMAT, not the CRS:
53//! `geo:wktLiteral` text follows the CRS's EPSG axis definition (lat/lon for
54//! EPSG:4326, lon/lat for CRS84); `geo:wkbLiteral` binary is ALWAYS lon/lat
55//! (x = longitude) regardless of SRID — the SRID on WKB is CRS identity
56//! metadata only.
57
58use std::collections::HashMap;
59
60use geo::{Coord, Geometry, Point};
61use oxrdf::NamedNode;
62use waratah_storage::{
63    CrsId, EncodedTerm, GeoDatatype, GeoEnvelope, GeoIndexPut, GeomKind, StorageOp, StrHash,
64    VisibilityLabel,
65};
66
67use crate::covering::{
68    MAX_COLLECTION_COVERING_CELLS, geometry_covering, geometry_envelope, point_leaf_cell,
69    should_store_envelope,
70};
71use crate::crs::{crs_from_srid, parse_crs_uri, wkt_axis_is_lat_lon};
72use crate::validation::{SpikeReduction, reduce_tolerated_spikes, validate_geometry};
73
74/// `geo:wktLiteral` datatype IRI.
75pub const GEO_WKT_LITERAL: &str = "http://www.opengis.net/ont/geosparql#wktLiteral";
76/// `geo:wkbLiteral` datatype IRI.
77pub const GEO_WKB_LITERAL: &str = "http://www.opengis.net/ont/geosparql#wkbLiteral";
78
79/// The two geo datatype IRIs as named nodes.
80pub fn geo_datatypes() -> [NamedNode; 2] {
81    [
82        NamedNode::new_unchecked(GEO_WKT_LITERAL),
83        NamedNode::new_unchecked(GEO_WKB_LITERAL),
84    ]
85}
86
87/// Whether `datatype` is one of the two geo literal datatypes.
88pub fn is_geo_datatype(datatype: oxrdf::NamedNodeRef<'_>) -> bool {
89    datatype.as_str() == GEO_WKT_LITERAL || datatype.as_str() == GEO_WKB_LITERAL
90}
91
92/// Encode failure reasons. Query constants fall back to a hashed typed
93/// literal; stored geometry writes treat these as hard errors.
94#[derive(Debug, Clone, PartialEq, thiserror::Error)]
95pub enum GeoError {
96    /// Lexical form is not parseable WKT/WKB.
97    #[error("unparseable geometry literal: {0}")]
98    Parse(String),
99    /// The literal names an unsupported (`Other`) CRS.
100    #[error("unsupported CRS: {0}")]
101    UnsupportedCrs(String),
102    /// The datum transform to CRS84 failed (missing grid / proj error).
103    #[error("CRS transform to CRS84 failed: {0}")]
104    Transform(String),
105    /// The geometry parsed but failed `geo::Validation`.
106    #[error("invalid geometry: {0}")]
107    InvalidGeometry(String),
108    /// Shape classes that stay on the typed-literal fallback (EMPTY
109    /// geometries, non-finite coordinates). Z/M is NOT a rejection — it
110    /// takes the native `LiteralGeometry` blob route with an
111    /// axis-preserving canonical EWKB (see the module docs).
112    #[error("unsupported geometry shape: {0}")]
113    UnsupportedShape(String),
114    /// A blob payload above the registry store's 64 MiB limit.
115    #[error("EWKB payload too large for the blob store: {0} bytes")]
116    TooLarge(usize),
117}
118
119/// Direction of a datum transform.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121enum TransformDirection {
122    /// Ingest: source CRS → CRS84 (normalized lon/lat in, lon/lat out).
123    ToCrs84,
124    /// Materialize: CRS84 → ingest CRS (lon/lat in, normalized lon/lat out;
125    /// the WKT text order is restored by the caller).
126    FromCrs84,
127}
128
129// Per-thread cache of `proj::Proj` per (CRS, direction). Constructing a
130// transform object is expensive — never per quad — but a `PJ*` is not
131// thread-safe (`proj::Proj` is deliberately not `Send`/`Sync`), so the cache
132// is thread-local rather than process-global. One ingest parser thread or
133// eval worker pays the construction once per CRS pair.
134thread_local! {
135    static PROJ_CACHE: std::cell::RefCell<
136        HashMap<(CrsId, TransformDirection), std::rc::Rc<proj::Proj>>,
137    > = std::cell::RefCell::new(HashMap::new());
138}
139
140fn proj_for(
141    crs: CrsId,
142    direction: TransformDirection,
143) -> Result<std::rc::Rc<proj::Proj>, GeoError> {
144    if let Some(proj) = PROJ_CACHE.with(|cache| cache.borrow().get(&(crs, direction)).cloned()) {
145        return Ok(proj);
146    }
147    let (from, to) = match direction {
148        // Both legs pivot through axis-order-explicit CRS strings: OGC:CRS84
149        // is lon/lat by definition; EPSG:NNNN geographic CRSs are lat/lon.
150        TransformDirection::ToCrs84 => (epsg_string(crs), "OGC:CRS84".to_owned()),
151        TransformDirection::FromCrs84 => ("OGC:CRS84".to_owned(), epsg_string(crs)),
152    };
153    let proj = std::rc::Rc::new(
154        proj::Proj::new_known_crs(&from, &to, None)
155            .map_err(|error| GeoError::Transform(error.to_string()))?,
156    );
157    PROJ_CACHE.with(|cache| {
158        cache.borrow_mut().insert((crs, direction), proj.clone());
159    });
160    Ok(proj)
161}
162
163fn epsg_string(crs: CrsId) -> String {
164    format!("EPSG:{}", epsg_number(crs))
165}
166
167/// EPSG number of the equivalent datum (CRS84 → 4326 — numerically
168/// identical; it is never transformed through it). Used for the `EPSG:`
169/// string forms such as the PROJ known-CRS names in `proj_for`; WKB storage
170/// SRIDs come from [`wkb_srid`], which maps CRS84 to SRID-less.
171pub fn epsg_number(crs: CrsId) -> u16 {
172    match crs {
173        CrsId::Crs84 => 4326,
174        CrsId::Epsg4326 => 4326,
175        CrsId::Epsg4283 => 4283,
176        CrsId::Epsg7844 => 7844,
177        CrsId::Epsg9309 => 9309,
178        CrsId::Epsg4167 => 4167,
179        CrsId::Epsg4272 => 4272,
180        CrsId::Other => 0,
181    }
182}
183
184/// WKB storage SRID of a CRS at materialize time: `None` (SRID-less) for
185/// [`CrsId::Crs84`] and [`CrsId::Other`], `Some(epsg_number(crs))` otherwise.
186///
187/// Round-trip invariant: `wkb_srid` and [`crate::crs::crs_from_srid`] must
188/// be mutual inverses over the supported set — a materialized
189/// `geo:wkbLiteral` must re-ingest as the same [`CrsId`]. CRS84 deliberately
190/// does NOT stamp SRID 4326: it is the GeoSPARQL default CRS and is stored
191/// SRID-less (the decoder maps absent/0 → CRS84, so SRID-less *is* the CRS84
192/// mapping), while SRID 4326 decodes to [`CrsId::Epsg4326`] — stamping 4326
193/// would make CRS84 output re-ingest as a *different* [`CrsId`] and later
194/// WKT-materialize with the EPSG lat/lon text order instead of CRS84's
195/// lon/lat. The SRID is CRS identity metadata only; the binary coordinate
196/// order itself is always lon/lat and plays no part in this choice.
197pub fn wkb_srid(crs: CrsId) -> Option<i32> {
198    match crs {
199        CrsId::Crs84 | CrsId::Other => None,
200        _ => Some(epsg_number(crs) as i32),
201    }
202}
203
204/// Transform one datum-transformed coordinate into CRS84, PRESERVING
205/// lon/lat order in and out — the WKB binary convention
206/// ([`GEO_WKB_LITERAL`]).
207///
208/// `(lon, lat)` is the coordinate in normalized lon/lat order (what a WKB
209/// payload or geozero's x/y reader produces, regardless of SRID). Returns
210/// `(lon, lat)` CRS84. Identity for CRS84 and EPSG:4326 (the same datum);
211/// a proj datum transform for the other listed CRSs.
212pub(crate) fn transform_to_crs84_normalized(
213    crs: CrsId,
214    lon: f64,
215    lat: f64,
216) -> Result<(f64, f64), GeoError> {
217    match crs {
218        // CRS84 and EPSG:4326 share the same datum, and the input is already
219        // lon/lat — nothing to do.
220        CrsId::Crs84 | CrsId::Epsg4326 => Ok((lon, lat)),
221        CrsId::Other => Err(GeoError::UnsupportedCrs("Other".into())),
222        _ => {
223            let proj = proj_for(crs, TransformDirection::ToCrs84)?;
224            // The proj crate NORMALIZES pipelines to x/y (lon/lat) input and
225            // output regardless of the CRS's declared axis order (verified
226            // empirically by `gda94_point_shares_crs84_sphere`): feed it
227            // (lon, lat), get (lon, lat) back.
228            proj.convert((lon, lat))
229                .map_err(|error| GeoError::Transform(error.to_string()))
230        }
231    }
232}
233
234/// Mirror image of [`transform_to_crs84_normalized`]: CRS84 lon/lat into
235/// `crs`'s normalized lon/lat terms — the WKB binary convention.
236///
237/// Identity for CRS84 and EPSG:4326 (the same datum); a proj datum
238/// transform for the other listed CRSs.
239pub(crate) fn transform_from_crs84_normalized(
240    crs: CrsId,
241    lon: f64,
242    lat: f64,
243) -> Result<(f64, f64), GeoError> {
244    match crs {
245        CrsId::Crs84 | CrsId::Epsg4326 => Ok((lon, lat)),
246        CrsId::Other => Err(GeoError::UnsupportedCrs("Other".into())),
247        _ => {
248            let proj = proj_for(crs, TransformDirection::FromCrs84)?;
249            // Normalized pipeline: (lon, lat) in, (lon, lat) out — in the
250            // TARGET CRS's terms.
251            proj.convert((lon, lat))
252                .map_err(|error| GeoError::Transform(error.to_string()))
253        }
254    }
255}
256
257/// Transform one coordinate into CRS84 lon/lat.
258///
259/// `(a, b)` is the coordinate in the SOURCE CRS's WKT text order — (lat,
260/// lon) for every listed EPSG geographic CRS, (lon, lat) for CRS84 —
261/// exactly what a WKT parser produced. Returns `(lon, lat)` CRS84.
262pub fn transform_to_crs84(crs: CrsId, a: f64, b: f64) -> Result<(f64, f64), GeoError> {
263    match crs {
264        // Text order is already (lon, lat).
265        CrsId::Crs84 => Ok((a, b)),
266        // EPSG geodetic text order is (lat, lon); 4326 shares CRS84's datum,
267        // so a pure swap.
268        CrsId::Epsg4326 => Ok((b, a)),
269        CrsId::Other => Err(GeoError::UnsupportedCrs("Other".into())),
270        // Text (lat, lon) → the normalized core's (lon, lat) input.
271        _ => transform_to_crs84_normalized(crs, b, a),
272    }
273}
274
275/// Transform CRS84 lon/lat into `crs`'s WKT text order.
276///
277/// Returns `(a, b)` — the pair to print, i.e. `(lat, lon)` for EPSG
278/// geographic CRSs, `(lon, lat)` for CRS84.
279pub fn transform_from_crs84(crs: CrsId, lon: f64, lat: f64) -> Result<(f64, f64), GeoError> {
280    match crs {
281        CrsId::Crs84 => Ok((lon, lat)),
282        CrsId::Epsg4326 => Ok((lat, lon)),
283        CrsId::Other => Err(GeoError::UnsupportedCrs("Other".into())),
284        _ => {
285            let (out_lon, out_lat) = transform_from_crs84_normalized(crs, lon, lat)?;
286            // The WKT text order comes from the one axis-order rule: swap
287            // iff that CRS is latitude-first.
288            if wkt_axis_is_lat_lon(crs) {
289                Ok((out_lat, out_lon))
290            } else {
291                Ok((out_lon, out_lat))
292            }
293        }
294    }
295}
296
297/// A parsed, CRS84-transformed, validated geometry plus everything the
298/// write path needs for it.
299#[derive(Debug, Clone)]
300pub struct PreparedGeometryLiteral {
301    /// Native term (or hashed typed literal on the fallback path — check
302    /// [`Self::is_native`]).
303    pub term: EncodedTerm,
304    /// Content-addressed blob puts (canonical CRS84 EWKB). Empty only for
305    /// 2-axis inline points; Z/M points and all non-point geometries carry
306    /// one blob.
307    pub blobs: Vec<(StrHash, Vec<u8>)>,
308    /// Geometry-index postings for the term (empty on the fallback path).
309    pub postings: Vec<GeoIndexPut>,
310    /// CRS84 envelope (the query side reuses it for the AABB reject).
311    pub envelope: Option<GeoEnvelope>,
312    /// The CRS84 geometry used for envelopes, S2 postings, and Relate. For a
313    /// tolerated zero-area spike this is the reduced valid-region geometry;
314    /// the blob above still retains the original coordinates.
315    pub geometry: Geometry<f64>,
316    /// Number of exactly collinear backtracking vertices removed from
317    /// `geometry`. Zero for ordinary valid geometries.
318    pub removed_spike_vertices: usize,
319}
320
321impl PreparedGeometryLiteral {
322    /// True when a native term was minted (not the typed-literal fallback).
323    pub fn is_native(&self) -> bool {
324        matches!(
325            self.term,
326            EncodedTerm::LiteralPoint { .. } | EncodedTerm::LiteralGeometry { .. }
327        )
328    }
329}
330
331/// Raw ingest payload retained for the Z/M canonical chain: the 2D geo
332/// projection has already dropped the z/m values, so the blob route
333/// re-streams the ORIGINAL source through `canonical`'s forwarding
334/// processor.
335#[derive(Debug, Clone)]
336enum RawGeoSource {
337    Wkb {
338        bytes: Vec<u8>,
339        header: WkbDialectHeader,
340    },
341    Wkt {
342        body: String,
343        traits: SourceShapeTraits,
344    },
345}
346
347/// Dimension traits of an ingest source (which of z / m the original
348/// lexical or WKB header carried).
349#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
350pub(crate) struct SourceShapeTraits {
351    pub has_z: bool,
352    pub has_m: bool,
353}
354
355/// A parsed geo literal: the 2D projection in its SOURCE CRS, the ingest
356/// CRS, the source's dimension traits, and the raw payload for the Z/M
357/// canonical chain.
358#[derive(Debug, Clone)]
359struct ParsedGeometryLiteral {
360    geometry: Geometry<f64>,
361    crs: CrsId,
362    traits: SourceShapeTraits,
363    raw: RawGeoSource,
364}
365
366/// Parse a `geo:wktLiteral` / `geo:wkbLiteral` into a geometry in its
367/// SOURCE CRS and axis order (WKT text: the CRS's EPSG axis definition;
368/// WKB binary: always lon/lat — see [`read_wkb_dialect_header`]).
369pub fn parse_geometry_literal(
370    literal: &oxrdf::Literal,
371) -> Result<(Geometry<f64>, CrsId), GeoError> {
372    parse_geometry_literal_source(literal).map(|parsed| (parsed.geometry, parsed.crs))
373}
374
375/// Full parse: like [`parse_geometry_literal`] but keeps the dimension
376/// traits and the raw source for the Z/M canonical blob chain.
377fn parse_geometry_literal_source(
378    literal: &oxrdf::Literal,
379) -> Result<ParsedGeometryLiteral, GeoError> {
380    let datatype = literal.datatype();
381    let value = literal.value();
382    if datatype.as_str() == GEO_WKT_LITERAL {
383        // Optional `<crs-uri> ` prefix; absent prefix = CRS84. Detachment is
384        // a bounded byte-window prepass (`split_crs_prefix`) — O(256), never
385        // a full-text scan — and leading whitespace before the `<` is
386        // tolerated. A `<` preceded by non-whitespace is body junk: the
387        // whole value stays the body, so the geozero parse fails naturally,
388        // which is the honest outcome for invalid input.
389        let (crs, wkt_body) = split_crs_prefix(value)?;
390        // Shape routing (owner contract): detect the dimension markers
391        // BEFORE the 2D parse. Z / M is NOT a rejection — the traits select
392        // the canonical blob route; EMPTY is (both syntaxes stay on the
393        // hashed typed-literal fallback).
394        let detected = detect_wkt_shape_traits(wkt_body);
395        if detected.is_empty {
396            return Err(GeoError::UnsupportedShape(format!(
397                "EMPTY geometry: {wkt_body}"
398            )));
399        }
400        let geometry = wkt_str_to_geometry(wkt_body)?;
401        Ok(ParsedGeometryLiteral {
402            geometry,
403            crs,
404            traits: detected.traits,
405            raw: RawGeoSource::Wkt {
406                body: wkt_body.to_owned(),
407                traits: detected.traits,
408            },
409        })
410    } else if datatype.as_str() == GEO_WKB_LITERAL {
411        // Input contract (owner decision, see `read_wkb_dialect_header`):
412        // hex EWKB always, hex OGC WKB when the flag-bit sniff finds no EWKB
413        // flag bits. One header read decides both the CRS (an EWKB SRID is
414        // CRS IDENTITY metadata only — the binary payload is ALWAYS lon/lat
415        // regardless of SRID, so no axis reorder ever happens here; absent /
416        // zero SRID = CRS84), the geozero reader dialect in
417        // `wkb_bytes_to_geometry`, and the Z / M shape traits for the
418        // routing contract (a flagged Z point takes the blob route, NOT a
419        // rejection).
420        let bytes = hex_decode(value).ok_or_else(|| GeoError::Parse("bad WKB hex".into()))?;
421        let header = read_wkb_dialect_header(&bytes);
422        let crs = crs_from_srid(header.srid)
423            .ok_or_else(|| GeoError::UnsupportedCrs(format!("WKB SRID {:?}", header.srid)))?;
424        let geometry = wkb_bytes_to_geometry(&bytes, header)?;
425        Ok(ParsedGeometryLiteral {
426            geometry,
427            crs,
428            traits: SourceShapeTraits {
429                has_z: header.has_z,
430                has_m: header.has_m,
431            },
432            raw: RawGeoSource::Wkb { bytes, header },
433        })
434    } else {
435        Err(GeoError::Parse(format!(
436            "datatype {} is not a geo literal",
437            datatype.as_str()
438        )))
439    }
440}
441
442/// Byte-window bound for the WKT CRS-prefix prepass (owner decision): the
443/// `<` is searched within the first [`CRS_PREFIX_WINDOW_BYTES`] bytes and
444/// the closing `>` within the next [`CRS_PREFIX_WINDOW_BYTES`] bytes
445/// (256 + 256 total). Both searches are bounded — a hostile blob that
446/// starts with `<` and never contains `>` errors after a 256-byte scan
447/// instead of reading the whole literal.
448const CRS_PREFIX_WINDOW_BYTES: usize = 256;
449
450/// Detach the optional `<crs-uri> ` prefix from a `geo:wktLiteral` value,
451/// returning the ingest CRS and the WKT body.
452///
453/// Byte-windowed prepass (owner decision): the search runs on
454/// `value.as_bytes()` — never on `&str` slices at fixed offsets, which
455/// panic on non-char-boundaries for untrusted input; every operation here
456/// is ASCII. Behavior:
457/// - no `<` within the first [`CRS_PREFIX_WINDOW_BYTES`] bytes → no prefix;
458///   the whole value is the body (CRS84), exactly as the old byte-0
459///   `strip_prefix` no-prefix path;
460/// - a `<` preceded by anything but whitespace (`' ' | '\t' | '\r' | '\n'`)
461///   is body junk, not a prefix marker — also treated as no-prefix, so the
462///   geozero parse fails naturally (the honest outcome for invalid input);
463/// - otherwise the first `>` within the next 256 bytes closes the URI
464///   (invalid UTF-8 → [`GeoError::Parse`]); `uri.trim()` then the existing
465///   rules verbatim — `<> ` empty prefix means CRS84 (GeoSPARQL), any other
466///   URI goes through `parse_crs_uri` (unknown →
467///   [`GeoError::UnsupportedCrs`]) — and the body is `value[j+1..]`
468///   `trim_start()`-ed;
469/// - no `>` in the window → [`GeoError::Parse`] ("unterminated CRS URI
470///   prefix") — bounded now, no full-text scan.
471///
472/// Leading whitespace before the prefix is tolerated: `<crs> WKT` literals
473/// with leading spaces/tabs/newlines parse (the old byte-0 check silently
474/// fell back to a typed literal for them).
475fn split_crs_prefix(value: &str) -> Result<(CrsId, &str), GeoError> {
476    let bytes = value.as_bytes();
477    let open = match bytes[..bytes.len().min(CRS_PREFIX_WINDOW_BYTES)]
478        .iter()
479        .position(|&byte| byte == b'<')
480    {
481        Some(open) => open,
482        // No `<` in the window → no prefix: the whole value is the body.
483        None => return Ok((CrsId::Crs84, value)),
484    };
485    // A prefix marker is a PREFIX marker: everything before the `<` must be
486    // whitespace. A `<` preceded by non-whitespace is body content — treat
487    // as no-prefix (the geozero parse then fails naturally on the invalid
488    // literal).
489    if !bytes[..open]
490        .iter()
491        .all(|&byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n'))
492    {
493        return Ok((CrsId::Crs84, value));
494    }
495    // Search the closing `>` bounded to the 256 bytes after the `<`.
496    let close_end = (open + 1 + CRS_PREFIX_WINDOW_BYTES).min(bytes.len());
497    let close = bytes[open + 1..close_end]
498        .iter()
499        .position(|&byte| byte == b'>')
500        .map(|offset| open + 1 + offset);
501    let Some(close) = close else {
502        return Err(GeoError::Parse("unterminated CRS URI prefix".into()));
503    };
504    // `open` / `close` point at ASCII `<` / `>` bytes, so `open + 1` /
505    // `close` / `close + 1` are char boundaries; the URI bytes themselves
506    // are validated, not assumed.
507    let uri = std::str::from_utf8(&bytes[open + 1..close])
508        .map_err(|_| GeoError::Parse("CRS URI prefix is not valid UTF-8".into()))?;
509    let uri = uri.trim();
510    let crs = if uri.is_empty() {
511        CrsId::Crs84 // `<> ` empty prefix means CRS84 (GeoSPARQL)
512    } else {
513        parse_crs_uri(uri).ok_or_else(|| GeoError::UnsupportedCrs(uri.to_owned()))?
514    };
515    Ok((crs, value[close + 1..].trim_start()))
516}
517
518/// Byte-window bound for the WKT shape-trait prepass (owner decision): only
519/// the first [`WKT_DETECT_WINDOW_BYTES`] bytes are normalized and scanned,
520/// with the marker region cut at the first `(` (top-level tag + dims
521/// only).
522const WKT_DETECT_WINDOW_BYTES: usize = 1000;
523
524/// Shape traits detected from a WKT lexical's dimension markers (the same
525/// case-insensitive marker scan the former `reject_zm_empty_wkt` used —
526/// repurposed from rejection to ROUTING per the Z/M contract in the module
527/// docs).
528///
529/// `has_z` / `has_m` say which canonical coordinate dimensions the source
530/// carries (Z vs M vs ZM are distinguished so the canonical blob stamps the
531/// right dims); `is_empty` routes to the typed-literal fallback — EMPTY has
532/// no CRS84 image, so it is never a native term (owner decision).
533///
534/// Detection is deliberately lexical (marker list, not the parsed coords):
535/// geozero's 2D readers silently map z / m into the same x/y slots, so the
536/// markers are the only place the source dims survive the 2D projection.
537///
538/// Detection is also deliberately BOUNDED and NORMALIZED (owner decision):
539/// it works on a byte copy of at most the first
540/// [`WKT_DETECT_WINDOW_BYTES`] bytes (`make_ascii_uppercase` in place — no
541/// full-size allocation for a huge literal; non-ASCII bytes pass through
542/// untouched), maps every whitespace run to a single space in one pass (so
543/// `Z  (`, `Z⇥(`, `Z\n(` all normalize to `Z (`), and scans only the
544/// region up to and including the FIRST `(` — the top-level tag, its
545/// dimension markers, and the paren opening the top-level coordinate list.
546/// That makes detection top-level-only by construction: nested members'
547/// markers are never seen, matching the WKB side, which reads top-level
548/// dims only. A body with no paren in the window (e.g. `POINT EMPTY`)
549/// scans the whole normalized window.
550///
551/// RESIDUAL MISS CLASS (silent by design, stated in the module docs): CRS
552/// prefixes beginning after the 256-byte window, and shape markers outside
553/// the paren-bounded 1000-byte region (pathological leading whitespace, or
554/// nested members — the latter by design), are not detected; such literals
555/// ingest as 2D or fall back via the parse.
556fn detect_wkt_shape_traits(wkt: &str) -> WktLexicalTraits {
557    let bytes = wkt.as_bytes();
558    let mut normalized = bytes[..bytes.len().min(WKT_DETECT_WINDOW_BYTES)].to_vec();
559    normalized.make_ascii_uppercase();
560    // One pass: map every whitespace byte to a space and collapse runs into
561    // a single space (write-index compaction).
562    let mut write = 0;
563    for read in 0..normalized.len() {
564        let byte = normalized[read];
565        let byte = if matches!(byte, b' ' | b'\t' | b'\r' | b'\n') {
566            b' '
567        } else {
568            byte
569        };
570        if byte == b' ' && write > 0 && normalized[write - 1] == b' ' {
571            continue;
572        }
573        normalized[write] = byte;
574        write += 1;
575    }
576    normalized.truncate(write);
577    // Marker region: the normalized prefix up to and including the first
578    // `(`. (The paren byte is included so the paren-terminated spaced
579    // markers below — `Z (`, `EMPTY(` — can match; nested markers sit
580    // strictly after the first paren and stay excluded.)
581    let region = match normalized.iter().position(|&byte| byte == b'(') {
582        Some(paren) => &normalized[..=paren],
583        None => &normalized[..],
584    };
585    let any_of = |markers: &[&str]| {
586        markers.iter().any(|marker| {
587            region
588                .windows(marker.len())
589                .any(|window| window == marker.as_bytes())
590        })
591    };
592    let is_empty = any_of(&[" EMPTY", "EMPTY("]);
593    let has_zm = any_of(&["ZM (", "ZM("]);
594    let has_z = has_zm || any_of(&["Z (", "Z("]);
595    let has_m = has_zm || any_of(&["M (", "M("]);
596    WktLexicalTraits {
597        traits: SourceShapeTraits { has_z, has_m },
598        is_empty,
599    }
600}
601
602/// [`SourceShapeTraits`] plus the EMPTY marker flag (a routing decision,
603/// not a coordinate dimension).
604#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
605struct WktLexicalTraits {
606    traits: SourceShapeTraits,
607    is_empty: bool,
608}
609
610/// geozero-based WKT → geo_types conversion.
611fn wkt_str_to_geometry(wkt: &str) -> Result<Geometry<f64>, GeoError> {
612    use geozero::ToGeo;
613    let parsed = geozero::wkt::Wkt(wkt)
614        .to_geo()
615        .map_err(|error| GeoError::Parse(error.to_string()))?;
616    ensure_2d_xy(&parsed)?;
617    Ok(parsed)
618}
619
620/// geozero-based (E)WKB → geo_types conversion.
621///
622/// The reader dialect is dispatched on the pre-parsed header
623/// ([`read_wkb_dialect_header`]): a type word with any EWKB flag bit set
624/// (SRID `0x2000_0000` / Z `0x8000_0000` / M `0x4000_0000` — geozero's
625/// `read_ewkb_header` is the authority) goes through geozero's PostGIS
626/// `Ewkb` reader; a plain numeric-dimension type word goes through the
627/// strict OGC `Wkb` reader. The dialect itself is an internal dispatch
628/// detail — the return type is the same 2D projection either way (z / m
629/// values degrade into the 2D slots; the header's `has_z` / `has_m` carry
630/// the true dims to the router).
631fn wkb_bytes_to_geometry(
632    bytes: &[u8],
633    header: WkbDialectHeader,
634) -> Result<Geometry<f64>, GeoError> {
635    use geozero::ToGeo;
636    let parsed = if header.is_ewkb {
637        geozero::wkb::Ewkb(bytes)
638            .to_geo()
639            .map_err(|error| GeoError::Parse(error.to_string()))?
640    } else {
641        geozero::wkb::Wkb(bytes)
642            .to_geo()
643            .map_err(|error| GeoError::Parse(error.to_string()))?
644    };
645    ensure_2d_xy(&parsed)?;
646    Ok(parsed)
647}
648
649/// Reject empty / non-finite geometries in the 2D projection. geozero's 2D
650/// readers map Z / M values into the same x/y slots, so a Z/M coordinate's
651/// x/y are checked here like any other — the dims themselves are routed by
652/// the lexical marker detector ([`detect_wkt_shape_traits`]) or the WKB
653/// header flags ([`WkbDialectHeader::has_z`]) instead. An EMPTY geometry
654/// (zero coordinates, or the all-NaN WKB encoding) fails here and falls
655/// back to a plain typed literal per the module's Z/M/EMPTY contract.
656fn ensure_2d_xy(geometry: &Geometry<f64>) -> Result<(), GeoError> {
657    use geo::CoordsIter;
658    if geometry.coords_count() == 0 {
659        return Err(GeoError::UnsupportedShape("empty geometry".into()));
660    }
661    for coord in geometry.coords_iter() {
662        if coord.x.is_nan() || coord.y.is_nan() || coord.x.is_infinite() || coord.y.is_infinite() {
663            return Err(GeoError::UnsupportedShape("non-finite coordinate".into()));
664        }
665    }
666    Ok(())
667}
668
669/// Decode lowercase/uppercase hex into bytes.
670fn hex_decode(hex: &str) -> Option<Vec<u8>> {
671    if !hex.len().is_multiple_of(2) {
672        return None;
673    }
674    let bytes = hex.as_bytes();
675    (0..bytes.len() / 2)
676        .map(|i| {
677            let hi = (bytes[2 * i] as char).to_digit(16)?;
678            let lo = (bytes[2 * i + 1] as char).to_digit(16)?;
679            Some(((hi << 4) | lo) as u8)
680        })
681        .collect()
682}
683
684/// The facts a WKB header pre-parse yields, read exactly once per payload:
685/// the EWKB SRID (when flagged), the dialect classification for
686/// [`wkb_bytes_to_geometry`] and the blob-route routing, and the payload's
687/// coordinate-dimension shape metadata (base type + Z / M flags) for the
688/// Z/M contract in the module docs.
689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
690pub struct WkbDialectHeader {
691    /// EWKB SRID of the payload (`Some(0)` means "no CRS named"; the
692    /// CRS84 mapping happens in [`crate::crs::crs_from_srid`]).
693    pub srid: Option<i32>,
694    /// `true` when the type word carries any EWKB flag bit (SRID
695    /// `0x2000_0000` / Z `0x8000_0000` / M `0x4000_0000` — geozero's
696    /// `read_ewkb_header` is the authority) — PostGIS EWKB; `false` means
697    /// strict OGC WKB (numeric dimension type word). OGC type words never
698    /// set these bits (they top out ≈ 0x0BC9), so the sniff is
699    /// unambiguous, and flagless EWKB is byte-identical to OGC WKB anyway.
700    pub is_ewkb: bool,
701    /// Geometry base type: EWKB `type_word & 0xFF`, OGC `type_word % 1000`
702    /// (1 = Point, 2 = LineString, 3 = Polygon, ...). Shape metadata for
703    /// the Z/M routing contract.
704    pub base_type: u32,
705    /// Z coordinate dimension: EWKB flag bit `0x8000_0000`, or an OGC
706    /// numeric dimension of 1 or 3.
707    pub has_z: bool,
708    /// M coordinate dimension: EWKB flag bit `0x4000_0000`, or an OGC
709    /// numeric dimension of 2 or 3.
710    pub has_m: bool,
711}
712
713/// Pre-parse a (E)WKB header: byte-order byte + type word (+ SRID when the
714/// EWKB SRID flag is set).
715///
716/// Lenient failure shape (unchanged from the former `ewkb_srid`): a short
717/// buffer or a bad byte-order byte yields `{ srid: None, is_ewkb: false }`,
718/// i.e. CRS84 / OGC reader — the loud [`GeoError::Parse`] then comes from the
719/// geometry parse itself, not from the header sniff.
720///
721/// This is the ingest half of the `geo:wkbLiteral` contract (owner decision):
722/// hex **EWKB** is always accepted, and hex **OGC WKB** is accepted when the
723/// sniff finds no EWKB flag bits. An EWKB SRID is CRS **identity** metadata
724/// only — the binary payload is ALWAYS lon/lat (x = longitude) regardless of
725/// SRID, matching the de-facto WKB ecosystem convention (PostGIS, GDAL,
726/// GEOS; the WKB spec itself carries no axis metadata). The sole ecosystem
727/// exception is MySQL 8, which reorders WKB coordinates per the EPSG axis
728/// definition — a documented, accepted incompatibility. Absent / zero SRID
729/// maps to CRS84. Output always re-emits EWKB hex in lon/lat with the SRID
730/// from [`wkb_srid`] (SRID-less for CRS84), so materialized wkbLiterals
731/// round-trip.
732pub fn read_wkb_dialect_header(bytes: &[u8]) -> WkbDialectHeader {
733    const NONE: WkbDialectHeader = WkbDialectHeader {
734        srid: None,
735        is_ewkb: false,
736        base_type: 0,
737        has_z: false,
738        has_m: false,
739    };
740    if bytes.len() < 5 {
741        return NONE;
742    }
743    let little_endian = match bytes[0] {
744        0x00 => false,
745        0x01 => true,
746        _ => return NONE,
747    };
748    let type_bytes = [bytes[1], bytes[2], bytes[3], bytes[4]];
749    let type_word = if little_endian {
750        u32::from_le_bytes(type_bytes)
751    } else {
752        u32::from_be_bytes(type_bytes)
753    };
754    // Flag-bit meanings per PostGIS EWKB / geozero's `read_ewkb_header`
755    // (the pre-0.15 labeling in our docs had Z and M swapped — harmless
756    // while the sniff ORed all bits, but wrong once Z-aware routing reads
757    // them individually).
758    const EWKB_SRID_FLAG: u32 = 0x2000_0000;
759    const EWKB_Z_FLAG: u32 = 0x8000_0000;
760    const EWKB_M_FLAG: u32 = 0x4000_0000;
761    let is_ewkb = type_word & (EWKB_SRID_FLAG | EWKB_Z_FLAG | EWKB_M_FLAG) != 0;
762    let (base_type, has_z, has_m) = if is_ewkb {
763        (
764            type_word & 0xFF,
765            type_word & EWKB_Z_FLAG != 0,
766            type_word & EWKB_M_FLAG != 0,
767        )
768    } else {
769        // OGC numeric dimension prefix: 1000 = Z, 2000 = M, 3000 = ZM.
770        let dim = type_word / 1000;
771        (type_word % 1000, matches!(dim, 1 | 3), matches!(dim, 2 | 3))
772    };
773    if type_word & EWKB_SRID_FLAG == 0 {
774        return WkbDialectHeader {
775            srid: None,
776            is_ewkb,
777            base_type,
778            has_z,
779            has_m,
780        };
781    }
782    let Some(srid_bytes): Option<[u8; 4]> = bytes.get(5..9).and_then(|slice| slice.try_into().ok())
783    else {
784        // Flagged but the SRID integer is truncated: classify as EWKB and let
785        // the geometry parse fail loudly on the truncated payload.
786        return WkbDialectHeader {
787            srid: None,
788            is_ewkb,
789            base_type,
790            has_z,
791            has_m,
792        };
793    };
794    let srid = if little_endian {
795        i32::from_le_bytes(srid_bytes)
796    } else {
797        i32::from_be_bytes(srid_bytes)
798    };
799    WkbDialectHeader {
800        srid: Some(srid),
801        is_ewkb,
802        base_type,
803        has_z,
804        has_m,
805    }
806}
807
808/// Decode a canonical CRS84 EWKB payload back to a geometry (rebuild and
809/// executor candidate path). Z/M canonical blobs degrade to their 2D
810/// projection here — the reader dialect dispatch lives in
811/// [`crate::relate::candidate_from_ewkb`], which this delegates to.
812pub fn geometry_from_crs84_ewkb(ewkb: &[u8]) -> Result<Geometry<f64>, GeoError> {
813    crate::relate::candidate_from_ewkb(ewkb)
814}
815
816/// Canonical CRS84 EWKB of a geometry (little-endian, no SRID — the blob
817/// payload is content-addressed, the term carries the CRS).
818pub fn geometry_to_crs84_ewkb(geometry: &Geometry<f64>) -> Result<Vec<u8>, GeoError> {
819    use geozero::CoordDimensions;
820    use geozero::ToWkb;
821    geometry
822        .to_ewkb(CoordDimensions::xy(), None)
823        .map_err(|error| GeoError::Parse(error.to_string()))
824}
825
826/// Transform every coordinate of a source-CRS geometry into CRS84.
827pub fn transform_geometry_to_crs84(
828    geometry: &Geometry<f64>,
829    crs: CrsId,
830) -> Result<Geometry<f64>, GeoError> {
831    if matches!(crs, CrsId::Crs84) {
832        return Ok(geometry.clone());
833    }
834    let map_point = |point: Point<f64>| -> Result<Point<f64>, GeoError> {
835        // geozero produced (x, y) in the source CRS's WKT text order;
836        // transform_to_crs84 takes exactly that pair.
837        let (lon, lat) = transform_to_crs84(crs, point.x(), point.y())?;
838        // CRS84 geometry convention: x = lon, y = lat.
839        Ok(Point::new(lon, lat))
840    };
841    use geo::MapCoords;
842    geometry.try_map_coords(|coord| -> Result<Coord<f64>, GeoError> {
843        let point = Point::from(coord);
844        map_point(point).map(geo::Point::into)
845    })
846}
847
848/// Transform every coordinate of a lon/lat (WKB convention) source geometry
849/// into CRS84 lon/lat — the `geo:wkbLiteral` ingest transform.
850///
851/// The payload is already lon/lat regardless of SRID (binary-format
852/// convention), so only the datum normalizes; no axis reorder ever happens.
853pub fn transform_geometry_to_crs84_normalized(
854    geometry: &Geometry<f64>,
855    crs: CrsId,
856) -> Result<Geometry<f64>, GeoError> {
857    if matches!(crs, CrsId::Crs84) {
858        return Ok(geometry.clone());
859    }
860    use geo::MapCoords;
861    geometry.try_map_coords(|coord| -> Result<Coord<f64>, GeoError> {
862        // geozero's x/y reader produced (x, y) = (lon, lat) — exactly the
863        // normalized core's input order.
864        let (lon, lat) = transform_to_crs84_normalized(crs, coord.x, coord.y)?;
865        // CRS84 geometry convention: x = lon, y = lat.
866        Ok(Coord { x: lon, y: lat })
867    })
868}
869
870/// Transform every coordinate of a CRS84 geometry into `crs`'s normalized
871/// lon/lat terms — the `geo:wkbLiteral` output transform (binary-format
872/// convention: lon/lat always, only the datum transforms).
873pub fn transform_geometry_from_crs84_normalized(
874    geometry: &Geometry<f64>,
875    crs: CrsId,
876) -> Result<Geometry<f64>, GeoError> {
877    if matches!(crs, CrsId::Crs84) {
878        return Ok(geometry.clone());
879    }
880    use geo::MapCoords;
881    geometry.try_map_coords(|coord| -> Result<Coord<f64>, GeoError> {
882        // (lon, lat) in, (lon, lat) out; geozero's x/y writer emits Coord.x
883        // first, so the normalized order maps straight into (x, y).
884        let (lon, lat) = transform_from_crs84_normalized(crs, coord.x, coord.y)?;
885        Ok(Coord { x: lon, y: lat })
886    })
887}
888
889/// Whether geometry preparation retains index artifacts.
890#[derive(Debug, Clone, Copy, PartialEq, Eq)]
891pub(crate) enum PrepareGeometryMode {
892    /// Build the blob payload and S2 postings used by puts and query constants.
893    Index,
894    /// Derive only the native term key used to tombstone a stored row on delete.
895    RewriteOnly,
896}
897
898/// Full encode path: parse → transform → validate → native term (+ blobs +
899/// postings), or the hashed typed-literal fallback.
900///
901/// Routing is by STORAGE SHAPE (owner contract, see the module docs): a
902/// 2-axis point stays the inline `LiteralPoint`; a Z/M point and every
903/// non-point geometry take the `LiteralGeometry` blob route — with the
904/// canonical blob built by the axis-preserving chain in `canonical` when
905/// the source carries Z/M (the 2D projection has lost those values), and
906/// by [`geometry_to_crs84_ewkb`] otherwise.
907pub fn prepare_geometry_literal(
908    literal: &oxrdf::Literal,
909) -> Result<PreparedGeometryLiteral, GeoError> {
910    prepare_geometry_literal_with_mode(literal, PrepareGeometryMode::Index)
911}
912
913/// Prepare the native term key for a delete without retaining blob payloads
914/// or index postings. Canonical EWKB is still constructed when needed to
915/// derive the content-addressed `LiteralGeometry` identity.
916pub(crate) fn prepare_geometry_literal_for_rewrite(
917    literal: &oxrdf::Literal,
918) -> Result<PreparedGeometryLiteral, GeoError> {
919    prepare_geometry_literal_with_mode(literal, PrepareGeometryMode::RewriteOnly)
920}
921
922fn prepare_geometry_literal_with_mode(
923    literal: &oxrdf::Literal,
924    mode: PrepareGeometryMode,
925) -> Result<PreparedGeometryLiteral, GeoError> {
926    let parsed = parse_geometry_literal_source(literal)?;
927    let crs = parsed.crs;
928    if crs == CrsId::Other {
929        return Err(GeoError::UnsupportedCrs("Other".into()));
930    }
931    // The transform is selected by SERIALIZATION FORMAT, not by CRS:
932    // wktLiteral text arrives in the source CRS's EPSG text order (the
933    // text-order transform reorders it), while wkbLiteral binary is ALWAYS
934    // lon/lat regardless of SRID — only the datum normalizes, never an axis
935    // swap.
936    let is_wkb = literal.datatype().as_str() == GEO_WKB_LITERAL;
937    let original_geometry = if is_wkb {
938        transform_geometry_to_crs84_normalized(&parsed.geometry, crs)?
939    } else {
940        transform_geometry_to_crs84(&parsed.geometry, crs)?
941    };
942    // Validation and its area/length thresholds deliberately run after the
943    // CRS84 transform. Moving this before the transform would mix coordinate
944    // units and magnify measurement error for large source coordinates.
945    // Exact zero-area ring spikes are reduced only for spatial evaluation;
946    // the canonical blob and native term identity retain the original shape.
947    let reduction = if validate_geometry(&original_geometry).is_ok() {
948        None
949    } else {
950        Some(reduce_tolerated_spikes(&original_geometry).map_err(GeoError::InvalidGeometry)?)
951    };
952    let requires_spike_reduction = reduction
953        .as_ref()
954        .is_some_and(|reduction| reduction.removed_vertices != 0);
955    let removed_spike_vertices = reduction
956        .as_ref()
957        .map_or(0, |reduction| reduction.removed_vertices);
958    let geometry = reduction
959        .as_ref()
960        .map_or(&original_geometry, |reduction| &reduction.geometry);
961    let geo_datatype = if is_wkb {
962        GeoDatatype::WkbLiteral
963    } else {
964        GeoDatatype::WktLiteral
965    };
966    let envelope = geometry_envelope(geometry);
967    // The 2D projection drives validity / envelope / postings / Relate for
968    // BOTH routes; only the blob payload differs between 2D and Z/M.
969    let carries_zm = parsed.traits.has_z || parsed.traits.has_m;
970    match &original_geometry {
971        Geometry::Point(point) if !carries_zm => {
972            let term = EncodedTerm::LiteralPoint {
973                x: point.x(),
974                y: point.y(),
975                crs,
976                geo_datatype,
977            };
978            let postings = if mode == PrepareGeometryMode::Index {
979                vec![GeoIndexPut {
980                    cell_id: point_leaf_cell(point.x(), point.y()).id(),
981                    term: encode_term_bytes_of(&term),
982                    commit_ts: waratah_storage::CommitTs::default(),
983                    op: StorageOp::Put,
984                    visibility: VisibilityLabel::default(),
985                    envelope: None, // points never carry an envelope
986                }]
987            } else {
988                Vec::new()
989            };
990            Ok(PreparedGeometryLiteral {
991                term,
992                blobs: Vec::new(),
993                postings,
994                envelope,
995                geometry: into_execution_geometry(original_geometry, reduction),
996                removed_spike_vertices,
997            })
998        }
999        other => {
1000            let ewkb = if carries_zm {
1001                canonical_source_to_crs84_ewkb(&parsed.raw, crs)?
1002            } else {
1003                geometry_to_crs84_ewkb(other)?
1004            };
1005            if ewkb.len() > waratah_registry::MAX_BLOB_BYTES {
1006                return Err(GeoError::TooLarge(ewkb.len()));
1007            }
1008            let blob_id = StrHash::from_bytes(&ewkb);
1009            let geom_kind = geom_kind_of(other);
1010            let term = EncodedTerm::LiteralGeometry {
1011                geom_kind,
1012                crs,
1013                geo_datatype,
1014                blob_id,
1015                requires_spike_reduction,
1016            };
1017            let is_collection = matches!(other, Geometry::GeometryCollection(_));
1018            // Rewrite-only deletes skip covering construction except where it
1019            // is needed to preserve the GeometryCollection eligibility rule.
1020            // The execution geometry is reduced when the term carries the
1021            // spike flag; the EWKB above remains the original representation.
1022            let covering = (mode == PrepareGeometryMode::Index || is_collection)
1023                .then(|| geometry_covering(geometry));
1024            // GeometryCollection covering limit (owner decision): a
1025            // collection's covering is the normalized union of its members'
1026            // coverings — multiplicative per-key row multiplicity (members ×
1027            // per-member cells) that is unbounded by construction. Above
1028            // `MAX_COLLECTION_COVERING_CELLS` distinct cells a stored put
1029            // fails as an unsupported shape; a query-authored constant may
1030            // use the typed-literal fallback because it creates no index
1031            // entry.
1032            // MultiPoint is not subject to this limit: its row multiplicity
1033            // is linear (one exact leaf row per point) and the >1024-point
1034            // tier takes a single budgeted covering. The check lives here
1035            // rather than in `geometry_covering` so that function stays
1036            // infallible for rebuild and tests. A rebuild can still see a
1037            // legacy over-limit typed literal and aborts rather than
1038            // stamping an index that omits it.
1039            if is_collection
1040                && covering
1041                    .as_ref()
1042                    .is_some_and(|covering| covering.len() > MAX_COLLECTION_COVERING_CELLS)
1043            {
1044                return Err(GeoError::UnsupportedShape(format!(
1045                    "geometry collection covering has {} distinct cells, above the {} cell limit",
1046                    covering.as_ref().expect("collection covering").len(),
1047                    MAX_COLLECTION_COVERING_CELLS
1048                )));
1049            }
1050            let postings = if mode == PrepareGeometryMode::Index {
1051                let covering = covering.expect("indexed geometry covering");
1052                let term_bytes = encode_term_bytes_of(&term);
1053                let mut postings = Vec::with_capacity(covering.len());
1054                for cell in &covering {
1055                    let cell_id = cell.id();
1056                    postings.push(GeoIndexPut {
1057                        cell_id,
1058                        term: term_bytes.clone(),
1059                        commit_ts: waratah_storage::CommitTs::default(),
1060                        op: StorageOp::Put,
1061                        visibility: VisibilityLabel::default(),
1062                        envelope: envelope
1063                            .filter(|envelope| should_store_envelope(cell_id, envelope)),
1064                    });
1065                }
1066                postings
1067            } else {
1068                Vec::new()
1069            };
1070            let blobs = if mode == PrepareGeometryMode::Index {
1071                vec![(blob_id, ewkb)]
1072            } else {
1073                Vec::new()
1074            };
1075            Ok(PreparedGeometryLiteral {
1076                term,
1077                blobs,
1078                postings,
1079                envelope,
1080                geometry: into_execution_geometry(original_geometry, reduction),
1081                removed_spike_vertices,
1082            })
1083        }
1084    }
1085}
1086
1087/// Move the original geometry on the ordinary valid path. Only an invalid
1088/// geometry with a tolerated spike owns a second, reduced geometry.
1089fn into_execution_geometry(
1090    original: Geometry<f64>,
1091    reduction: Option<SpikeReduction>,
1092) -> Geometry<f64> {
1093    reduction.map_or(original, |reduction| reduction.geometry)
1094}
1095
1096/// Canonical CRS84 EWKB of a raw ingest source carrying Z / M: dispatch on
1097/// the serialization format (the chain re-streams the ORIGINAL source —
1098/// text order for WKT, lon/lat binary for WKB — see `canonical`).
1099fn canonical_source_to_crs84_ewkb(raw: &RawGeoSource, crs: CrsId) -> Result<Vec<u8>, GeoError> {
1100    match raw {
1101        RawGeoSource::Wkb { bytes, header } => {
1102            crate::canonical::canonicalize_wkb_to_crs84(bytes, *header, crs)
1103        }
1104        RawGeoSource::Wkt { body, traits } => {
1105            crate::canonical::canonicalize_wkt_to_crs84(body, *traits, crs)
1106        }
1107    }
1108}
1109
1110/// Encoded term bytes (the postings carry the term inline).
1111fn encode_term_bytes_of(term: &EncodedTerm) -> Vec<u8> {
1112    waratah_storage::encode_term_bytes(term)
1113}
1114
1115/// Shape class for the term's inline `GeomKind` byte.
1116fn geom_kind_of(geometry: &Geometry<f64>) -> GeomKind {
1117    match geometry {
1118        Geometry::Point(_) => GeomKind::Point,
1119        Geometry::Line(_) | Geometry::LineString(_) => GeomKind::LineString,
1120        Geometry::Polygon(_) => GeomKind::Polygon,
1121        Geometry::MultiPoint(_) => GeomKind::MultiPoint,
1122        Geometry::MultiLineString(_) => GeomKind::MultiLineString,
1123        Geometry::MultiPolygon(_) => GeomKind::MultiPolygon,
1124        Geometry::GeometryCollection(_) => GeomKind::GeometryCollection,
1125        Geometry::Rect(_) | Geometry::Triangle(_) => GeomKind::Polygon,
1126    }
1127}
1128
1129/// Encode a geo literal for the datatype map: native term on success, the
1130/// same hashed typed literal storage `From<&Literal>` would produce on any
1131/// failure (ingest and query constants cannot diverge — one path).
1132///
1133/// On native success the mint's content-addressed payload pairs
1134/// (`blob_id → canonical CRS84 EWKB`) are returned alongside the term:
1135/// the query-const seeding installs them in the query-local blob map
1136/// (query constants never reach the registry blob store, so the pairs are
1137/// the only copy of the payload — the geo relate loop's fetch reads them
1138/// there). Ingest takes the same pairs from [`PreparedGeometryLiteral`]
1139/// and writes them to the store.
1140pub fn encode_literal(literal: &oxrdf::Literal) -> (EncodedTerm, Vec<(StrHash, Vec<u8>)>) {
1141    match prepare_geometry_literal(literal) {
1142        Ok(prepared) if prepared.is_native() => {
1143            let PreparedGeometryLiteral { term, blobs, .. } = prepared;
1144            (term, blobs)
1145        }
1146        Ok(_) | Err(_) => (EncodedTerm::from(literal), Vec::new()),
1147    }
1148}
1149
1150#[cfg(test)]
1151mod tests {
1152    use super::*;
1153    use geo::algorithm::Validation;
1154    use pretty_assertions::assert_eq;
1155
1156    fn wkt_literal(value: &str) -> oxrdf::Literal {
1157        oxrdf::Literal::new_typed_literal(value, NamedNode::new_unchecked(GEO_WKT_LITERAL))
1158    }
1159
1160    #[test]
1161    fn crs84_point_encodes_inline() {
1162        let prepared = prepare_geometry_literal(&wkt_literal("POINT(153.025 -27.47)")).unwrap();
1163        let EncodedTerm::LiteralPoint {
1164            x,
1165            y,
1166            crs,
1167            geo_datatype,
1168        } = prepared.term
1169        else {
1170            panic!("expected LiteralPoint, got {:?}", prepared.term);
1171        };
1172        assert_eq!(x, 153.025);
1173        assert_eq!(y, -27.47);
1174        assert_eq!(crs, CrsId::Crs84);
1175        assert_eq!(geo_datatype, GeoDatatype::WktLiteral);
1176        assert!(prepared.blobs.is_empty());
1177        assert_eq!(prepared.postings.len(), 1);
1178    }
1179
1180    #[test]
1181    fn epsg4326_point_swaps_to_crs84_stored() {
1182        // WKT in EPSG:4326 is lat/lon.
1183        let prepared = prepare_geometry_literal(&wkt_literal(
1184            "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.47 153.025)",
1185        ))
1186        .unwrap();
1187        let EncodedTerm::LiteralPoint { x, y, crs, .. } = prepared.term else {
1188            panic!("expected LiteralPoint");
1189        };
1190        assert_eq!(x, 153.025, "stored x is CRS84 lon");
1191        assert_eq!(y, -27.47, "stored y is CRS84 lat");
1192        assert_eq!(crs, CrsId::Epsg4326);
1193        // Ingest CRS preserved: WKT out is lat/lon again with the default URI.
1194        let lexical = crate::materialize::materialize_lexical(&prepared.term, None)
1195            .unwrap()
1196            .unwrap();
1197        assert_eq!(
1198            lexical,
1199            "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.47 153.025)"
1200        );
1201    }
1202
1203    #[test]
1204    fn gda94_point_shares_crs84_sphere() {
1205        crate::test_support::require_proj_data();
1206        // GDA94 (4283) Brisbane ≈ CRS84 Brisbane (null-ish datum shift).
1207        let prepared = prepare_geometry_literal(&wkt_literal(
1208            "<http://www.opengis.net/def/crs/EPSG/0/4283> POINT(-27.47 153.025)",
1209        ))
1210        .unwrap();
1211        let EncodedTerm::LiteralPoint { x, y, crs, .. } = prepared.term else {
1212            panic!("expected LiteralPoint");
1213        };
1214        assert_eq!(crs, CrsId::Epsg4283);
1215        let crs84 = prepare_geometry_literal(&wkt_literal("POINT(153.025 -27.47)")).unwrap();
1216        let EncodedTerm::LiteralPoint { x: x2, y: y2, .. } = crs84.term else {
1217            panic!();
1218        };
1219        assert!((x - x2).abs() < 1e-6, "lon {x} vs {x2}");
1220        assert!((y - y2).abs() < 1e-6, "lat {y} vs {y2}");
1221        // Same S2 leaf after the transform.
1222        assert_eq!(prepared.postings[0].cell_id, crs84.postings[0].cell_id);
1223    }
1224
1225    #[test]
1226    fn polygon_mints_blob_and_coverings() {
1227        let prepared = prepare_geometry_literal(&wkt_literal(
1228            "POLYGON((152.0 -28.0, 153.0 -28.0, 153.0 -27.0, 152.0 -27.0, 152.0 -28.0))",
1229        ))
1230        .unwrap();
1231        let EncodedTerm::LiteralGeometry {
1232            geom_kind,
1233            crs,
1234            blob_id,
1235            ..
1236        } = prepared.term
1237        else {
1238            panic!("expected LiteralGeometry");
1239        };
1240        assert_eq!(geom_kind, GeomKind::Polygon);
1241        assert_eq!(crs, CrsId::Crs84);
1242        assert_eq!(prepared.blobs.len(), 1);
1243        assert_eq!(prepared.blobs[0].0, blob_id);
1244        // Content addressing: the blob id hashes the payload.
1245        assert_eq!(StrHash::from_bytes(&prepared.blobs[0].1), blob_id);
1246        assert!(!prepared.postings.is_empty());
1247        // The coverer's own slack rule: a covering may exceed max_cells by
1248        // a few cells (see `covering::tests`). Config-driven so a budget
1249        // change cannot rot this bound.
1250        assert!(prepared.postings.len() <= crate::covering::coverer_config().max_cells + 6);
1251    }
1252
1253    #[test]
1254    fn clip_edge_spike_preserves_blob_and_marks_reduced_execution_geometry() {
1255        let literal = wkt_literal(
1256            "POLYGON((154.000000 -28.797429, 154.000000 -27.760501, \
1257             153.834707 -27.678942, 153.018589 -27.558772, \
1258             152.746796 -28.041757, 152.170156 -29.032803, \
1259             153.097669 -29.526447, 154.000000 -29.270522, \
1260             154.000000 -29.550790, 154.000000 -28.797429))",
1261        );
1262        let prepared = prepare_geometry_literal(&literal).unwrap();
1263        let EncodedTerm::LiteralGeometry {
1264            blob_id,
1265            requires_spike_reduction,
1266            ..
1267        } = &prepared.term
1268        else {
1269            panic!("expected LiteralGeometry");
1270        };
1271        assert!(*requires_spike_reduction);
1272        assert_eq!(prepared.removed_spike_vertices, 1);
1273        assert!(prepared.geometry.is_valid());
1274        assert!(!prepared.postings.is_empty());
1275
1276        let original = crate::relate::candidate_from_ewkb(&prepared.blobs[0].1).unwrap();
1277        assert!(!original.is_valid(), "the stored blob retains the spike");
1278        assert_eq!(StrHash::from_bytes(&prepared.blobs[0].1), *blob_id);
1279
1280        let lexical =
1281            crate::materialize::materialize_lexical(&prepared.term, Some(&prepared.blobs[0].1))
1282                .unwrap()
1283                .unwrap();
1284        assert!(lexical.contains("-29.55079"), "{lexical}");
1285        let reparsed = prepare_geometry_literal(&wkt_literal(&lexical)).unwrap();
1286        assert_eq!(reparsed.term, prepared.term);
1287        assert_eq!(reparsed.blobs[0].1, prepared.blobs[0].1);
1288
1289        let rewrite = prepare_geometry_literal_for_rewrite(&literal).unwrap();
1290        assert_eq!(rewrite.term, prepared.term);
1291        assert!(rewrite.blobs.is_empty());
1292        assert!(rewrite.postings.is_empty());
1293    }
1294
1295    #[test]
1296    fn z_spike_reduces_only_the_execution_projection() {
1297        let literal = wkt_literal("POLYGON Z((0 0 1, 2 0 2, 2 -1 3, 2 2 4, 0 2 5, 0 0 1))");
1298        let prepared = prepare_geometry_literal(&literal).unwrap();
1299        assert!(prepared.term.requires_spike_reduction());
1300        assert_eq!(prepared.removed_spike_vertices, 1);
1301        assert!(prepared.geometry.is_valid());
1302        assert!(read_wkb_dialect_header(&prepared.blobs[0].1).has_z);
1303
1304        let lexical =
1305            crate::materialize::materialize_lexical(&prepared.term, Some(&prepared.blobs[0].1))
1306                .unwrap()
1307                .unwrap();
1308        let reparsed = prepare_geometry_literal(&wkt_literal(&lexical)).unwrap();
1309        assert_eq!(reparsed.term, prepared.term);
1310        assert_eq!(reparsed.blobs[0].1, prepared.blobs[0].1);
1311    }
1312
1313    #[test]
1314    fn rewrite_only_geometry_skips_postings_and_blob_payloads() {
1315        let literal = wkt_literal(
1316            "POLYGON((152.0 -28.0, 153.0 -28.0, 153.0 -27.0, 152.0 -27.0, 152.0 -28.0))",
1317        );
1318        let indexed = prepare_geometry_literal(&literal).unwrap();
1319        assert!(!indexed.postings.is_empty());
1320        assert_eq!(indexed.blobs.len(), 1);
1321
1322        let rewrite = prepare_geometry_literal_for_rewrite(&literal).unwrap();
1323        assert_eq!(rewrite.term, indexed.term);
1324        assert!(rewrite.postings.is_empty());
1325        assert!(rewrite.blobs.is_empty());
1326    }
1327
1328    #[test]
1329    fn invalid_polygon_query_constant_falls_back_to_typed_literal() {
1330        // Bow-tie polygon: parses fine, fails Validation. Stored puts reject
1331        // it; the query-constant encoder remains total.
1332        let prepared = prepare_geometry_literal(&wkt_literal("POLYGON((0 0, 2 2, 2 0, 0 2, 0 0))"))
1333            .unwrap_err();
1334        assert!(matches!(prepared, GeoError::InvalidGeometry(_)));
1335        let (encoded, payloads) =
1336            encode_literal(&wkt_literal("POLYGON((0 0, 2 2, 2 0, 0 2, 0 0))"));
1337        assert!(
1338            matches!(
1339                encoded,
1340                EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
1341            ),
1342            "fallback is a hashed typed literal"
1343        );
1344        assert!(payloads.is_empty(), "the fallback mints no payload pairs");
1345    }
1346
1347    #[test]
1348    fn unknown_crs_falls_back() {
1349        let literal = oxrdf::Literal::new_typed_literal(
1350            "<http://example.org/mars> POINT(1 2)",
1351            NamedNode::new_unchecked(GEO_WKT_LITERAL),
1352        );
1353        assert!(matches!(
1354            prepare_geometry_literal(&literal),
1355            Err(GeoError::UnsupportedCrs(_))
1356        ));
1357        assert!(matches!(
1358            encode_literal(&literal).0,
1359            EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
1360        ));
1361    }
1362
1363    #[test]
1364    fn z_point_becomes_geometry_literal() {
1365        // Owner contract: Z is never rejected — a Z point takes the native
1366        // LiteralGeometry blob route with an axis-preserving canonical EWKB
1367        // (z passthrough, no rejection).
1368        let prepared = prepare_geometry_literal(&wkt_literal("POINT Z(1 2 3)")).unwrap();
1369        let EncodedTerm::LiteralGeometry {
1370            geom_kind,
1371            crs,
1372            geo_datatype,
1373            blob_id,
1374            ..
1375        } = prepared.term
1376        else {
1377            panic!("expected LiteralGeometry, got {:?}", prepared.term);
1378        };
1379        assert_eq!(geom_kind, GeomKind::Point);
1380        assert_eq!(crs, CrsId::Crs84);
1381        assert_eq!(geo_datatype, GeoDatatype::WktLiteral);
1382        assert_eq!(prepared.blobs.len(), 1);
1383        assert_eq!(prepared.blobs[0].0, blob_id);
1384        // The canonical blob carries the EWKB Z flag (0x8000_0000 — geozero's
1385        // `read_ewkb_header` labeling) and the z value.
1386        let header = read_wkb_dialect_header(&prepared.blobs[0].1);
1387        assert!(header.is_ewkb);
1388        assert!(header.has_z);
1389        assert!(!header.has_m);
1390        assert_eq!(header.base_type, 1, "POINT base type");
1391        // LE point Z: 1 order byte + 4 type bytes + x + y + z.
1392        let payload = &prepared.blobs[0].1;
1393        assert_eq!(payload.len(), 1 + 4 + 8 * 3);
1394        let x = f64::from_le_bytes(payload[5..13].try_into().unwrap());
1395        let y = f64::from_le_bytes(payload[13..21].try_into().unwrap());
1396        let z = f64::from_le_bytes(payload[21..29].try_into().unwrap());
1397        assert_eq!((x, y, z), (1.0, 2.0, 3.0));
1398        // Postings exist (the point leaf — the 2D projection drives S2).
1399        assert_eq!(prepared.postings.len(), 1);
1400        // Materialized wktLiteral carries the dimension marker and
1401        // re-ingests to the same canonical blob (lexical round-trip).
1402        let out = crate::materialize::materialize_lexical(&prepared.term, Some(payload))
1403            .unwrap()
1404            .unwrap();
1405        assert_eq!(out, "POINT Z(1 2 3)");
1406        let reparsed = prepare_geometry_literal(&wkt_literal(&out)).unwrap();
1407        assert_eq!(reparsed.blobs[0].1, prepared.blobs[0].1);
1408    }
1409
1410    #[test]
1411    fn zm_and_m_points_take_the_blob_route() {
1412        // ZM and M distinguish the canonical dims (xyzm vs xym); the marker
1413        // spelling with the space before the paren also routes.
1414        for (lexical, has_z, has_m) in [
1415            ("POINT ZM(1 2 3 4)", true, true),
1416            ("POINT M(1 2 4)", false, true),
1417            ("POINT Z (1 2 3)", true, false),
1418        ] {
1419            let prepared = prepare_geometry_literal(&wkt_literal(lexical)).unwrap();
1420            let EncodedTerm::LiteralGeometry { .. } = prepared.term else {
1421                panic!("expected LiteralGeometry for {lexical}");
1422            };
1423            let header = read_wkb_dialect_header(&prepared.blobs[0].1);
1424            assert_eq!(header.has_z, has_z, "{lexical}");
1425            assert_eq!(header.has_m, has_m, "{lexical}");
1426        }
1427    }
1428
1429    #[test]
1430    fn wkt_polygon_z_round_trips_through_marked_output() {
1431        let prepared = prepare_geometry_literal(&wkt_literal(
1432            "POLYGON Z((152.0 -28.0 5, 153.0 -28.0 6, 153.0 -27.0 7, 152.0 -27.0 8, 152.0 -28.0 5))",
1433        ))
1434        .unwrap();
1435        let EncodedTerm::LiteralGeometry { geom_kind, .. } = prepared.term else {
1436            panic!("expected LiteralGeometry");
1437        };
1438        assert_eq!(geom_kind, GeomKind::Polygon);
1439        let payload = &prepared.blobs[0].1;
1440        // Materialized wktLiteral carries the Z marker after the keyword and
1441        // re-ingests to the SAME canonical blob (the acceptance criterion).
1442        let out = crate::materialize::materialize_lexical(&prepared.term, Some(payload))
1443            .unwrap()
1444            .unwrap();
1445        assert_eq!(
1446            out,
1447            "POLYGON Z((152 -28 5,153 -28 6,153 -27 7,152 -27 8,152 -28 5))"
1448        );
1449        let reparsed = prepare_geometry_literal(&wkt_literal(&out)).unwrap();
1450        assert_eq!(reparsed.blobs[0].1, prepared.blobs[0].1);
1451    }
1452
1453    #[test]
1454    fn epsg4326_wkt_polygon_z_swaps_xy_keeps_z_and_round_trips() {
1455        // WKT in EPSG:4326 is lat/lon text order: the canonical blob's x/y
1456        // are CRS84 lon/lat while z passes through unchanged; the
1457        // materialized lexical restores the lat/lon text order (with the
1458        // canonical CRS URI) and re-ingests to the same blob.
1459        let prepared = prepare_geometry_literal(&wkt_literal(
1460            "<http://www.opengis.net/def/crs/EPSG/0/4326> POLYGON Z((-28.0 152.0 5, -28.0 153.0 6, -27.0 153.0 7, -27.0 152.0 8, -28.0 152.0 5))",
1461        ))
1462        .unwrap();
1463        assert!(prepared.is_native());
1464        let payload = &prepared.blobs[0].1;
1465        let header = read_wkb_dialect_header(payload);
1466        assert!(header.has_z);
1467        // First ring vertex of the canonical blob (LE polygon Z header).
1468        // Type word is at 1..5; ring count/vertex counts precede the coords.
1469        let x = f64::from_le_bytes(payload[13..21].try_into().unwrap());
1470        let y = f64::from_le_bytes(payload[21..29].try_into().unwrap());
1471        let z = f64::from_le_bytes(payload[29..37].try_into().unwrap());
1472        assert_eq!((x, y, z), (152.0, -28.0, 5.0), "x/y are CRS84, z kept");
1473        let out = crate::materialize::materialize_lexical(&prepared.term, Some(payload))
1474            .unwrap()
1475            .unwrap();
1476        assert_eq!(
1477            out,
1478            "<http://www.opengis.net/def/crs/EPSG/0/4326> POLYGON Z((-28 152 5,-28 153 6,-27 153 7,-27 152 8,-28 152 5))"
1479        );
1480        let reparsed = prepare_geometry_literal(&wkt_literal(&out)).unwrap();
1481        assert_eq!(reparsed.blobs[0].1, prepared.blobs[0].1);
1482    }
1483
1484    #[test]
1485    fn wkb_polygon_z_ingests_natively_and_round_trips_both_outputs() {
1486        use geozero::{CoordDimensions, ToWkb};
1487        // A Z-flagged EWKB polygon (the case the strict OGC reader and the
1488        // old rejection-free-but-silently-flattened path mishandled).
1489        let polygon: geo::Geometry<f64> = geo::wkt!(POLYGON((
1490            152.0 - 28.0,
1491            153.0 - 28.0,
1492            153.0 - 27.0,
1493            152.0 - 27.0,
1494            152.0 - 28.0
1495        )))
1496        .into();
1497        let ewkb = polygon.to_ewkb(CoordDimensions::xyz(), None).unwrap();
1498        let hex: String = ewkb.iter().map(|byte| format!("{byte:02x}")).collect();
1499        let literal =
1500            oxrdf::Literal::new_typed_literal(hex, NamedNode::new_unchecked(GEO_WKB_LITERAL));
1501        let prepared = prepare_geometry_literal(&literal).unwrap();
1502        let EncodedTerm::LiteralGeometry {
1503            crs, geo_datatype, ..
1504        } = prepared.term
1505        else {
1506            panic!("expected LiteralGeometry");
1507        };
1508        assert_eq!(crs, CrsId::Crs84);
1509        assert_eq!(geo_datatype, GeoDatatype::WkbLiteral);
1510        let payload = &prepared.blobs[0].1;
1511        assert!(read_wkb_dialect_header(payload).has_z);
1512        // For CRS84 the wkbLiteral output is byte-identical to the canonical
1513        // blob (identity datum, SRID-less) and re-ingests to the same blob.
1514        let out = crate::materialize::materialize_lexical(&prepared.term, Some(payload))
1515            .unwrap()
1516            .unwrap();
1517        assert_eq!(
1518            out,
1519            payload
1520                .iter()
1521                .map(|b| format!("{b:02x}"))
1522                .collect::<String>()
1523        );
1524        let reparsed = prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
1525            &out,
1526            NamedNode::new_unchecked(GEO_WKB_LITERAL),
1527        ))
1528        .unwrap();
1529        assert_eq!(reparsed.blobs[0].1, prepared.blobs[0].1);
1530    }
1531
1532    #[test]
1533    fn wkb_polygon_z_srid4326_output_carries_the_srid_rule() {
1534        use geozero::{CoordDimensions, ToWkb};
1535        // The wkbLiteral output stamps the ingest SRID per `wkb_srid`
1536        // (Some(4326) here) while the canonical blob stays SRID-less; the
1537        // datum transform is the identity for 4326, so re-ingesting the
1538        // output reproduces the same canonical blob.
1539        let polygon: geo::Geometry<f64> = geo::wkt!(POLYGON((
1540            152.0 - 28.0,
1541            153.0 - 28.0,
1542            153.0 - 27.0,
1543            152.0 - 27.0,
1544            152.0 - 28.0
1545        )))
1546        .into();
1547        let ewkb = polygon.to_ewkb(CoordDimensions::xyz(), Some(4326)).unwrap();
1548        let hex: String = ewkb.iter().map(|byte| format!("{byte:02x}")).collect();
1549        let literal =
1550            oxrdf::Literal::new_typed_literal(hex, NamedNode::new_unchecked(GEO_WKB_LITERAL));
1551        let prepared = prepare_geometry_literal(&literal).unwrap();
1552        let EncodedTerm::LiteralGeometry { crs, .. } = prepared.term else {
1553            panic!("expected LiteralGeometry");
1554        };
1555        assert_eq!(crs, CrsId::Epsg4326);
1556        let out =
1557            crate::materialize::materialize_lexical(&prepared.term, Some(&prepared.blobs[0].1))
1558                .unwrap()
1559                .unwrap();
1560        let out_bytes = hex_decode(&out).unwrap();
1561        let out_header = read_wkb_dialect_header(&out_bytes);
1562        assert!(out_header.has_z);
1563        assert_eq!(out_header.srid, Some(4326));
1564        let reparsed = prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
1565            &out,
1566            NamedNode::new_unchecked(GEO_WKB_LITERAL),
1567        ))
1568        .unwrap();
1569        assert_eq!(reparsed.blobs[0].1, prepared.blobs[0].1);
1570    }
1571
1572    #[test]
1573    fn empty_geometries_fall_back_to_plain_typed_literals() {
1574        // Owner contract: EMPTY (both syntaxes) is NOT native — no blob, no
1575        // postings, no S2 index; the original lexical is preserved
1576        // byte-exactly by the plain typed-literal fallback.
1577        for lexical in ["POINT EMPTY", "POINT Z EMPTY", "MULTIPOINT EMPTY"] {
1578            let literal = wkt_literal(lexical);
1579            assert!(matches!(
1580                prepare_geometry_literal(&literal),
1581                Err(GeoError::UnsupportedShape(_))
1582            ));
1583            let (encoded, payloads) = encode_literal(&literal);
1584            assert!(
1585                matches!(
1586                    encoded,
1587                    EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
1588                ),
1589                "{lexical} falls back to a hashed typed literal"
1590            );
1591            assert!(payloads.is_empty(), "the fallback mints no payload pairs");
1592        }
1593    }
1594
1595    #[test]
1596    fn wkb_empty_point_falls_back() {
1597        // The WKB EMPTY encoding: a POINT whose coordinates are all NaN.
1598        let mut bytes = vec![1u8]; // little-endian
1599        bytes.extend_from_slice(&1u32.to_le_bytes()); // POINT
1600        bytes.extend_from_slice(&f64::NAN.to_le_bytes());
1601        bytes.extend_from_slice(&f64::NAN.to_le_bytes());
1602        let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
1603        let literal =
1604            oxrdf::Literal::new_typed_literal(hex, NamedNode::new_unchecked(GEO_WKB_LITERAL));
1605        // The reader errors on the empty point before `ensure_2d_xy` runs
1606        // (geozero's default `empty_point` rejects it), so the error kind is
1607        // `Parse`, not `UnsupportedShape` — either way it is a hard error,
1608        // which is what routes EMPTY to the plain typed-literal fallback.
1609        assert!(prepare_geometry_literal(&literal).is_err());
1610        assert!(matches!(
1611            encode_literal(&literal).0,
1612            EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
1613        ));
1614    }
1615
1616    #[test]
1617    fn wkb_literal_round_trip() {
1618        // Encode a point as WKB hex (little-endian, no SRID).
1619        let mut hex = String::new();
1620        for b in point_wkb(153.025, -27.47) {
1621            hex.push_str(&format!("{b:02x}"));
1622        }
1623        let literal =
1624            oxrdf::Literal::new_typed_literal(hex, NamedNode::new_unchecked(GEO_WKB_LITERAL));
1625        let prepared = prepare_geometry_literal(&literal).unwrap();
1626        let EncodedTerm::LiteralPoint {
1627            x, y, geo_datatype, ..
1628        } = prepared.term
1629        else {
1630            panic!("expected LiteralPoint");
1631        };
1632        assert_eq!(x, 153.025);
1633        assert_eq!(y, -27.47);
1634        assert_eq!(geo_datatype, GeoDatatype::WkbLiteral);
1635    }
1636
1637    #[test]
1638    fn wkb_srid_is_none_for_crs84_and_other() {
1639        // CRS84 is stored SRID-less (see `wkb_srid`'s doc): SRID 4326 would
1640        // re-ingest as the axis-swapped Epsg4326 variant.
1641        assert_eq!(wkb_srid(CrsId::Crs84), None);
1642        assert_eq!(wkb_srid(CrsId::Other), None);
1643        assert_eq!(wkb_srid(CrsId::Epsg4326), Some(4326));
1644        assert_eq!(wkb_srid(CrsId::Epsg7844), Some(7844));
1645    }
1646
1647    #[test]
1648    fn wkb_literal_srid4326_ewkb_round_trips() {
1649        use geozero::{CoordDimensions, ToWkb};
1650        // WKB binary convention: lon/lat ALWAYS, regardless of SRID — the
1651        // SRID is CRS identity metadata only (see `read_wkb_dialect_header`).
1652        // Brisbane: x = lon = 153.025, y = lat = -27.47.
1653        let source = geo::Geometry::Point(geo::Point::new(153.025, -27.47));
1654        let ewkb = source.to_ewkb(CoordDimensions::xy(), Some(4326)).unwrap();
1655        let hex: String = ewkb.iter().map(|byte| format!("{byte:02x}")).collect();
1656        let literal = oxrdf::Literal::new_typed_literal(
1657            hex.clone(),
1658            NamedNode::new_unchecked(GEO_WKB_LITERAL),
1659        );
1660        let (geometry, crs) = parse_geometry_literal(&literal).unwrap();
1661        assert_eq!(crs, CrsId::Epsg4326);
1662        // The payload is already lon/lat, so the ingest transform is the
1663        // IDENTITY (4326 shares CRS84's datum) — no axis swap anywhere.
1664        let geo::Geometry::Point(source_point) = geometry else {
1665            panic!("expected a point, got {geometry:?}");
1666        };
1667        assert_eq!(source_point.x(), 153.025, "source x is lon (binary order)");
1668        assert_eq!(source_point.y(), -27.47, "source y is lat (binary order)");
1669        // Materialize back: the term re-emits the same SRID'd EWKB hex in
1670        // lon/lat order, which re-ingests as the same CRS and point
1671        // (round-trip).
1672        let prepared = prepare_geometry_literal(&literal).unwrap();
1673        let EncodedTerm::LiteralPoint {
1674            x: stored_lon,
1675            y: stored_lat,
1676            ..
1677        } = prepared.term
1678        else {
1679            panic!("expected LiteralPoint, got {:?}", prepared.term);
1680        };
1681        assert_eq!(
1682            stored_lon, 153.025,
1683            "stored CRS84 x is lon, identity-mapped"
1684        );
1685        assert_eq!(stored_lat, -27.47, "stored CRS84 y is lat, identity-mapped");
1686        let out = crate::materialize::materialize_lexical(&prepared.term, None)
1687            .unwrap()
1688            .unwrap();
1689        assert_eq!(out, hex, "SRID'd EWKB materializes byte-identically");
1690        let (geometry, crs) = parse_geometry_literal(&oxrdf::Literal::new_typed_literal(
1691            &out,
1692            NamedNode::new_unchecked(GEO_WKB_LITERAL),
1693        ))
1694        .unwrap();
1695        assert_eq!(crs, CrsId::Epsg4326);
1696        let geo::Geometry::Point(point) = geometry else {
1697            panic!("expected a point, got {geometry:?}");
1698        };
1699        assert_eq!(point.x(), 153.025);
1700        assert_eq!(point.y(), -27.47);
1701    }
1702
1703    #[test]
1704    fn wkb_and_wkt_ingest_of_same_non4326_point_agree() {
1705        crate::test_support::require_proj_data();
1706        use geozero::{CoordDimensions, ToWkb};
1707        // Axis order is a property of the serialization format: the same
1708        // GDA94 (EPSG:4283) Brisbane point ingested once as `geo:wktLiteral`
1709        // (text order lat/lon) and once as `geo:wkbLiteral` (lon/lat payload
1710        // + SRID 4283) must produce the SAME CRS84 geometry — the WKB path
1711        // datum-transforms without an axis double-swap.
1712        let wkt = oxrdf::Literal::new_typed_literal(
1713            "<http://www.opengis.net/def/crs/EPSG/0/4283> POINT(-27.47 153.025)",
1714            NamedNode::new_unchecked(GEO_WKT_LITERAL),
1715        );
1716        let source = geo::Geometry::Point(geo::Point::new(153.025, -27.47)); // lon/lat
1717        let ewkb = source.to_ewkb(CoordDimensions::xy(), Some(4283)).unwrap();
1718        let hex: String = ewkb.iter().map(|byte| format!("{byte:02x}")).collect();
1719        let wkb = oxrdf::Literal::new_typed_literal(hex, NamedNode::new_unchecked(GEO_WKB_LITERAL));
1720        let wkt_prepared = prepare_geometry_literal(&wkt).unwrap();
1721        let wkb_prepared = prepare_geometry_literal(&wkb).unwrap();
1722        assert_eq!(wkt_prepared.geometry, wkb_prepared.geometry);
1723        // Same S2 leaf after the (equivalent) transforms.
1724        assert_eq!(
1725            wkt_prepared.postings[0].cell_id,
1726            wkb_prepared.postings[0].cell_id
1727        );
1728    }
1729
1730    #[test]
1731    fn wkb_literal_ogc_wkb_ingests_as_crs84() {
1732        use geozero::{CoordDimensions, ToWkb};
1733        // Plain OGC WKB (numeric type word, no SRID) sniffs as OGC and
1734        // ingests as CRS84 — pins the sniff's OGC branch.
1735        let source = geo::Geometry::Point(geo::Point::new(153.025, -27.47));
1736        let wkb = source.to_wkb(CoordDimensions::xy()).unwrap();
1737        let hex: String = wkb.iter().map(|byte| format!("{byte:02x}")).collect();
1738        let literal =
1739            oxrdf::Literal::new_typed_literal(hex, NamedNode::new_unchecked(GEO_WKB_LITERAL));
1740        let (geometry, crs) = parse_geometry_literal(&literal).unwrap();
1741        assert_eq!(crs, CrsId::Crs84);
1742        let geo::Geometry::Point(point) = geometry else {
1743            panic!("expected a point, got {geometry:?}");
1744        };
1745        assert_eq!(point.x(), 153.025);
1746        assert_eq!(point.y(), -27.47);
1747    }
1748
1749    #[test]
1750    fn wkb_dialect_header_sniffs_flag_bits() {
1751        // Each EWKB flag bit — SRID (0x2000_0000), Z (0x8000_0000),
1752        // M (0x4000_0000), per geozero's `read_ewkb_header` (an older
1753        // comment here had Z and M swapped) — and their combination classify
1754        // the payload as EWKB; the SRID flag additionally extracts the SRID
1755        // integer, and the new dims fields expose Z / M / base type.
1756        for (flags, has_z, has_m) in [
1757            (0x2000_0000u32, false, false),
1758            (0x4000_0000, false, true),
1759            (0x8000_0000, true, false),
1760            (0xE000_0000, true, true),
1761        ] {
1762            let mut bytes = vec![1u8]; // little-endian
1763            bytes.extend_from_slice(&(flags | 1).to_le_bytes()); // POINT | flags
1764            bytes.extend_from_slice(&4326i32.to_le_bytes());
1765            let header = read_wkb_dialect_header(&bytes);
1766            assert!(header.is_ewkb, "flags {flags:#010x} must sniff as EWKB");
1767            assert_eq!(header.srid, (flags & 0x2000_0000 != 0).then_some(4326));
1768            assert_eq!(header.base_type, 1, "POINT base type for {flags:#010x}");
1769            assert_eq!(header.has_z, has_z, "Z flag for {flags:#010x}");
1770            assert_eq!(header.has_m, has_m, "M flag for {flags:#010x}");
1771        }
1772        // A numeric-dimension type word (POINT Z = 1001) classifies as OGC
1773        // WKB with no SRID, and the OGC numeric dimension maps to has_z.
1774        let mut bytes = vec![0u8]; // big-endian
1775        bytes.extend_from_slice(&1001u32.to_be_bytes());
1776        let header = read_wkb_dialect_header(&bytes);
1777        assert!(!header.is_ewkb);
1778        assert_eq!(header.srid, None);
1779        assert_eq!(header.base_type, 1, "OGC POINT = 1001 % 1000");
1780        assert!(header.has_z, "OGC numeric dim 1 = Z");
1781        assert!(!header.has_m);
1782        // OGC POINT M (2001) maps to has_m only; ZM (3001) to both.
1783        let mut bytes = vec![0u8];
1784        bytes.extend_from_slice(&2001u32.to_be_bytes());
1785        let header = read_wkb_dialect_header(&bytes);
1786        assert!(!header.has_z && header.has_m);
1787        let mut bytes = vec![0u8];
1788        bytes.extend_from_slice(&3001u32.to_be_bytes());
1789        let header = read_wkb_dialect_header(&bytes);
1790        assert!(header.has_z && header.has_m);
1791        // Lenient failure shape: bad byte-order byte → CRS84/OGC defaults.
1792        let header = read_wkb_dialect_header(&[0xFF, 0, 0, 0, 1]);
1793        assert!(!header.is_ewkb);
1794        assert_eq!(header.srid, None);
1795        assert!(!header.has_z && !header.has_m);
1796        let header = read_wkb_dialect_header(&[0x01, 0x00]);
1797        assert!(!header.is_ewkb);
1798        assert_eq!(header.srid, None);
1799    }
1800
1801    #[test]
1802    fn crs_prefix_with_leading_whitespace_detaches() {
1803        // Behavior improvement over the old byte-0 `strip_prefix('<')`:
1804        // whitespace (spaces, tabs, newlines) before the `<crs>` prefix no
1805        // longer hides it, so the literal no longer falls back to a typed
1806        // literal.
1807        for lexical in [
1808            "  <http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.47 153.025)",
1809            "\t\n <http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.47 153.025)",
1810        ] {
1811            let prepared = prepare_geometry_literal(&wkt_literal(lexical)).unwrap();
1812            let EncodedTerm::LiteralPoint { crs, .. } = prepared.term else {
1813                panic!("expected LiteralPoint for {lexical:?}");
1814            };
1815            assert_eq!(crs, CrsId::Epsg4326, "{lexical:?}");
1816        }
1817    }
1818
1819    #[test]
1820    fn crs_prefix_search_window_is_256_bytes() {
1821        // Pin the `<` search window edge: `<` at byte 255 (the last byte of
1822        // the 256-byte window) still detaches; `<` at byte 256 (one past it)
1823        // is a no-prefix body, so the geozero parse fails and ingest falls
1824        // back.
1825        let inside = format!(
1826            "{}<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(1 2)",
1827            " ".repeat(255)
1828        );
1829        let prepared = prepare_geometry_literal(&wkt_literal(&inside)).unwrap();
1830        let EncodedTerm::LiteralPoint { crs, .. } = prepared.term else {
1831            panic!("expected LiteralPoint");
1832        };
1833        assert_eq!(crs, CrsId::Epsg4326);
1834
1835        let outside = format!(
1836            "{}<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(1 2)",
1837            " ".repeat(256)
1838        );
1839        assert!(matches!(
1840            prepare_geometry_literal(&wkt_literal(&outside)),
1841            Err(GeoError::Parse(_))
1842        ));
1843    }
1844
1845    #[test]
1846    fn unterminated_crs_prefix_errors_within_the_window() {
1847        // A hostile literal that starts with `<` and never contains `>`:
1848        // the error is bounded to the 256-byte window (the old
1849        // `split_once('>')` scanned the entire value before erroring). The
1850        // body is > 256 bytes to pin the bound while staying modest.
1851        let body = format!("<POINT(1 2) {}", "x".repeat(300));
1852        assert!(matches!(
1853            prepare_geometry_literal(&wkt_literal(&body)),
1854            Err(GeoError::Parse(error)) if error.contains("unterminated CRS URI prefix")
1855        ));
1856    }
1857
1858    #[test]
1859    fn non_whitespace_before_crs_prefix_is_body_junk() {
1860        // A `<` preceded by non-whitespace is not a prefix marker: the whole
1861        // value stays the body, so the geozero parse fails and ingest falls
1862        // back to the hashed typed literal.
1863        let lexical = "junk <http://www.opengis.net/def/crs/EPSG/0/4326> POINT(1 2)";
1864        assert!(matches!(
1865            prepare_geometry_literal(&wkt_literal(lexical)),
1866            Err(GeoError::Parse(_))
1867        ));
1868        assert!(matches!(
1869            encode_literal(&wkt_literal(lexical)).0,
1870            EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
1871        ));
1872    }
1873
1874    #[test]
1875    fn empty_crs_uri_prefix_is_crs84() {
1876        // `<> ` empty prefix means CRS84 (GeoSPARQL default).
1877        let prepared = prepare_geometry_literal(&wkt_literal("<> POINT(153.025 -27.47)")).unwrap();
1878        let EncodedTerm::LiteralPoint { x, y, crs, .. } = prepared.term else {
1879            panic!("expected LiteralPoint");
1880        };
1881        assert_eq!(crs, CrsId::Crs84);
1882        assert_eq!((x, y), (153.025, -27.47));
1883    }
1884
1885    #[test]
1886    fn shape_traits_survive_whitespace_runs_before_the_paren() {
1887        // Normalized detection: any whitespace run between the axis letter
1888        // and the paren collapses to one space, so legal-but-odd WKT like
1889        // `POINT Z  (1 2 3)` (two spaces, a tab, a newline) no longer
1890        // silently routes to the 2D point arm.
1891        for lexical in ["POINT Z  (1 2 3)", "POINT Z\t(1 2 3)", "POINT Z\n(1 2 3)"] {
1892            let traits = detect_wkt_shape_traits(lexical);
1893            assert!(traits.traits.has_z, "{lexical:?} must detect z");
1894            assert!(!traits.traits.has_m, "{lexical:?}");
1895            assert!(!traits.is_empty, "{lexical:?}");
1896        }
1897        for lexical in [
1898            "POLYGON ZM((0 0, 1 1, 0 1, 0 0))",
1899            "POLYGON ZM ((0 0, 1 1, 0 1, 0 0))",
1900        ] {
1901            let traits = detect_wkt_shape_traits(lexical);
1902            assert!(
1903                traits.traits.has_z && traits.traits.has_m,
1904                "{lexical:?} must detect both z and m"
1905            );
1906        }
1907    }
1908
1909    #[test]
1910    fn two_space_z_point_ingests_natively() {
1911        // End-to-end for the whitespace-run normalization: the point takes
1912        // the native Z blob route instead of the 2D inline arm (the exact
1913        // data-loss class this eliminated).
1914        let prepared = prepare_geometry_literal(&wkt_literal("POINT Z  (1 2 3)")).unwrap();
1915        let EncodedTerm::LiteralGeometry { .. } = prepared.term else {
1916            panic!("expected LiteralGeometry, got {:?}", prepared.term);
1917        };
1918        assert!(read_wkb_dialect_header(&prepared.blobs[0].1).has_z);
1919    }
1920
1921    #[test]
1922    fn nested_dimension_markers_are_not_detected() {
1923        // Top-level-only semantics by construction: the marker region ends
1924        // at the first `(`, so a nested member's `LINESTRING Z(...)` inside
1925        // a GEOMETRYCOLLECTION is never seen (matches the WKB side, which
1926        // reads top-level dims only).
1927        let traits = detect_wkt_shape_traits("GEOMETRYCOLLECTION(POINT(1 2), LINESTRING Z(3 4 5))");
1928        assert!(!traits.traits.has_z);
1929        assert!(!traits.traits.has_m);
1930        assert!(!traits.is_empty);
1931    }
1932
1933    #[test]
1934    fn marker_beyond_the_detect_window_is_an_accepted_miss() {
1935        // Accepted residual miss (documented in the module docs): a shape
1936        // marker outside the 1000-byte paren-bounded region — here hidden
1937        // behind 2000 bytes of leading whitespace — is NOT detected; such a
1938        // literal ingests as 2D or falls back via the parse.
1939        let lexical = format!("{}POINT Z(1 2 3)", " ".repeat(2000));
1940        let traits = detect_wkt_shape_traits(&lexical);
1941        assert!(!traits.traits.has_z);
1942        assert!(!traits.traits.has_m);
1943    }
1944
1945    #[test]
1946    fn empty_marker_detection_tolerates_whitespace_runs() {
1947        assert!(detect_wkt_shape_traits("POLYGON EMPTY").is_empty);
1948        assert!(detect_wkt_shape_traits("POLYGON  EMPTY").is_empty);
1949        assert!(detect_wkt_shape_traits("POLYGON\n\t EMPTY").is_empty);
1950        assert!(!detect_wkt_shape_traits("POLYGON((0 0, 1 1, 0 1, 0 0))").is_empty);
1951    }
1952
1953    #[test]
1954    fn geometry_collection_under_limit_ingests_natively_with_union_covering() {
1955        // Mixed collection (two polygons + a point + a linestring), far
1956        // below the 1024-cell limit: native term, and the covering is the
1957        // union of the members' coverings — every member's known interior
1958        // point / vertex is covered.
1959        let prepared = prepare_geometry_literal(&wkt_literal(
1960            "GEOMETRYCOLLECTION(POLYGON((152.0 -28.0, 153.0 -28.0, 153.0 -27.0, 152.0 -27.0, 152.0 -28.0)), POLYGON((154.0 -28.0, 155.0 -28.0, 155.0 -27.0, 154.0 -27.0, 154.0 -28.0)), POINT(150.0 -30.0), LINESTRING(148.0 -31.0, 149.0 -31.0))",
1961        ))
1962        .unwrap();
1963        assert!(prepared.is_native());
1964        assert!(!prepared.postings.is_empty());
1965        let covering = geometry_covering(&prepared.geometry);
1966        for leaf in [
1967            point_leaf_cell(152.5, -27.5), // first polygon interior
1968            point_leaf_cell(154.5, -27.5), // second polygon interior
1969            point_leaf_cell(150.0, -30.0), // the point member itself
1970            point_leaf_cell(148.5, -31.0), // linestring midpoint
1971        ] {
1972            assert!(
1973                covering.iter().any(|id| {
1974                    let (min, max) = (id.range_min().id(), id.range_max().id());
1975                    leaf.id() >= min.min(max) && leaf.id() <= min.max(max)
1976                }),
1977                "member point {leaf:?} is not covered by the collection covering"
1978            );
1979        }
1980    }
1981
1982    #[test]
1983    fn geometry_collection_over_limit_query_constant_falls_back_to_typed_literal() {
1984        // A collection whose combined distinct covering exceeds the 1024
1985        // cell limit: 40 far-apart 30°×15° polygons (each several distinct
1986        // cells) PLUS 800 spread point members. The points are the
1987        // deterministic margin — their exact level-30 leaves do not depend on
1988        // the process-global coverer config, so the union crosses the limit
1989        // even if a concurrent test has `max_cells` lowered (the point
1990        // postings alone would need 800 < 1024; combined with any polygon
1991        // cells the union clears the limit under any config).
1992        let mut members = Vec::new();
1993        for c in 0..5 {
1994            for r in 0..8 {
1995                let lon = -150.0 + c as f64 * 70.0;
1996                let lat = -60.0 + r as f64 * 16.0;
1997                members.push(format!(
1998                    "POLYGON(({lon} {lat}, {lon2} {lat}, {lon2} {lat2}, {lon} {lat2}, {lon} {lat}))",
1999                    lon2 = lon + 30.0,
2000                    lat2 = lat + 15.0
2001                ));
2002            }
2003        }
2004        for i in 0..800 {
2005            let lon = -179.0 + (i % 40) as f64 * 9.0;
2006            let lat = -80.0 + (i / 40) as f64 * 2.0;
2007            members.push(format!("POINT({lon} {lat})"));
2008        }
2009        let literal = wkt_literal(&format!("GEOMETRYCOLLECTION({})", members.join(", ")));
2010        // `prepare_geometry_literal` errors with `UnsupportedShape` naming
2011        // the count and limit. A stored put treats that as a hard error,
2012        // while `encode_literal` keeps the query-constant fallback because a
2013        // query constant creates no index entry.
2014        let error = prepare_geometry_literal(&literal).unwrap_err();
2015        let GeoError::UnsupportedShape(message) = &error else {
2016            panic!("expected UnsupportedShape, got {error:?}");
2017        };
2018        assert!(
2019            message.contains("1024"),
2020            "error must name the limit, got: {message}"
2021        );
2022        assert!(
2023            matches!(
2024                encode_literal(&literal).0,
2025                EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
2026            ),
2027            "over-limit collection query constant falls back to a hashed typed literal"
2028        );
2029    }
2030
2031    fn point_wkb(x: f64, y: f64) -> Vec<u8> {
2032        let mut out = vec![1u8]; // little-endian
2033        out.extend_from_slice(&1u32.to_le_bytes()); // POINT
2034        out.extend_from_slice(&x.to_le_bytes());
2035        out.extend_from_slice(&y.to_le_bytes());
2036        out
2037    }
2038}