Skip to main content

waratah_geo/
covering.rs

1//! S2 coverings, merged cell-id intervals, and CRS84 envelopes.
2//!
3//! Compute owns **all** S2 math (plan §3): points index at their level-30
4//! leaf cell; polygons cover with [`s2rst::s2::RegionCoverer`] on the actual
5//! CRS84 rings (never the convex hull). Coverer params (`min_level` /
6//! `max_level` / `max_cells`) are process configuration with the v1 defaults
7//! `0` / `24` / `32`; ingest covering and query covering both read this
8//! process's live config, and changing them requires
9//! `waratah geo rebuild-index` (no fingerprint / fail-closed in v1).
10//!
11//! Covering budget (owner contract): `max_cells` is a **per geometry**
12//! budget. Multi* shapes are ONE geometry: a `MultiPolygon` becomes one
13//! `RegionUnion` of the members' individual `s2::Polygon`s (shell/hole
14//! classification per member) and a `MultiLineString` / large `MultiPoint`
15//! becomes one `RegionUnion`, each covered by a SINGLE `RegionCoverer`
16//! call — the
17//! query-time trade-off is coarser cells for disperse multi-geometries,
18//! i.e. more Relate candidates downstream (Relate stays exact on the geo
19//! geometry, so results are unaffected, only candidate volume grows). A
20//! `GeometryCollection` is MULTIPLE geometries: its covering is the
21//! normalized union of the members' (recursive) coverings with NO
22//! per-member budget reduction, bounded by
23//! [`MAX_COLLECTION_COVERING_CELLS`] distinct cells — a stored top-level
24//! collection above the limit fails as an unsupported shape, while a
25//! query-authored constant may use the typed-literal fallback. A
26//! `MultiPoint` tiers at [`MAX_MULTIPOINT_EXACT_POINTS`] points: at or
27//! below it the per-point exact leaf postings are never budgeted away;
28//! above it the set takes one budgeted covering.
29
30use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering};
31
32use geo::BoundingRect;
33use geo::Coord;
34use geo::Geometry;
35use geo::LineString;
36use s2rst::s2::region_coverer::RegionCoverer;
37use s2rst::s2::region_union::RegionUnion;
38use s2rst::s2::{Cell, CellId, CellUnion, LatLng, Level, LevelMod, Polygon as S2Polygon, Region};
39use waratah_storage::{GeoCellInterval, GeoEnvelope};
40
41/// MultiPoint size at or below which every point keeps its exact level-30
42/// leaf posting (owner decision). Leaf-exact postings are the precise
43/// reverse lookup for modest point sets — a few hundred or a few thousand
44/// rows is cheap and never loses precision. Above the threshold the set is
45/// treated as degenerate (e.g. machine-generated point clouds): it takes
46/// ONE budgeted region covering (`max_cells` cells) instead of one exact
47/// posting per point, accepting the precision loss for lower row multiplicity.
48pub(crate) const MAX_MULTIPOINT_EXACT_POINTS: usize = 1024;
49
50/// Distinct-cell limit on a top-level `GeometryCollection` covering (owner
51/// decision). A collection's covering is the normalized union of its
52/// members' coverings — per-key row multiplicity is multiplicative (members
53/// × per-member cells) and unbounded by construction, so the limit bounds it:
54/// a stored collection above the limit fails as an unsupported shape, while
55/// a query-authored constant may use the typed-literal fallback. MultiPoint
56/// is deliberately NOT subject to this limit: its row multiplicity is linear
57/// (one exact row per point within the [`MAX_MULTIPOINT_EXACT_POINTS`] tier)
58/// and the over-tier case takes a single budgeted covering instead. Enforced
59/// in `prepare_geometry_literal` rather than in [`geometry_covering`], which
60/// stays infallible for the rebuild path and tests. A rebuild can still see a
61/// legacy over-limit typed literal; it aborts rather than stamping an index
62/// that omits the term.
63pub(crate) const MAX_COLLECTION_COVERING_CELLS: usize = 1024;
64
65/// Minimum covered-cell level (default 0).
66static MIN_LEVEL: AtomicU8 = AtomicU8::new(0);
67/// Maximum covered-cell level (default 24). Points never snap to this.
68static MAX_LEVEL: AtomicU8 = AtomicU8::new(24);
69/// Maximum cells in one covering (default 40). S2's own library default
70/// (8) minimizes index terms per shape for term-index use; Waratah's
71/// covering backs every posting with envelope + exact relate refinement,
72/// so the budget trades index rows against false-candidate work — a
73/// higher budget buys tighter coverings. 32 saturated on essentially
74/// every non-point geometry of the bellendena corpora (31.6 cells/geometry
75/// average, `waratah geo census` 2026-10); 40 leaves that headroom and
76/// keeps the coarse-cell population (levels 8–12) from growing.
77static MAX_CELLS: AtomicUsize = AtomicUsize::new(40);
78
79/// Live coverer configuration of this process.
80#[derive(Debug, Clone, Copy, PartialEq)]
81pub struct CovererConfig {
82    /// Minimum covered-cell level.
83    pub min_level: u8,
84    /// Maximum covered-cell level (points stay at the level-30 leaf).
85    pub max_level: u8,
86    /// Maximum cells per covering.
87    pub max_cells: usize,
88    /// Planar edge densification step in degrees: polygon/line-string edges
89    /// longer than this are subdivided before the S2 region is built, so the
90    /// geodesic covering is a superset of the planar (WKT/JTS) region.
91    /// `0.0` disables densification (raw rings — geodesic interpretation
92    /// only); values in `(0.0, MIN_DENSIFY_STEP_DEG)` are rejected at config
93    /// time. The contract lives on [`geometry_covering`].
94    pub densify_step_deg: f64,
95}
96
97/// Planar-edge densification step (degrees), stored as f64 bits so the config
98/// stays a plain atomic read (coverer_config() runs per ingest geometry and
99/// per query constant). Initialized to the default step — densification is ON
100/// unless explicitly disabled (`0.0` bits).
101static DENSIFY_STEP: AtomicU64 = AtomicU64::new(DEFAULT_DENSIFY_STEP_DEG.to_bits());
102
103/// The default densification step (0.1°): ~11 km segments, worst-case
104/// geodesic-vs-planar chord deviation ~5 m (measured; the deviation scales
105/// with the square of the step) — three orders of magnitude inside the
106/// near-edge depths that motivated the contract.
107pub const DEFAULT_DENSIFY_STEP_DEG: f64 = 0.1;
108
109/// The smallest configurable densification step (0.0001° ≈ 11 m segments).
110/// Steps below the covering's own cell resolution buy no accuracy — the cell
111/// budget is what bounds the output — they only inflate the intermediate
112/// vertex list toward an unbounded loop. `0.0` remains the documented
113/// disable sentinel.
114pub const MIN_DENSIFY_STEP_DEG: f64 = 1e-4;
115
116/// Hard piece-count per segment for pathological inputs. With the enforced
117/// step floor this never binds for legitimate configuration; it exists so a
118/// direct caller bypassing `set_coverer_config` cannot drive
119/// [`segment_pieces`] to `usize::MAX` and hang the loop.
120const MAX_SEGMENT_PIECES: usize = 65_536;
121
122/// The densification-contract fixture hexagon as WKT: a continental-scale
123/// hexagon ~24° wide, centered near 132°W 58°N, whose SE/SW edges bow up to
124/// ~0.67° into the interior under geodesic interpretation. The canonical
125/// spelling shared by the covering unit tests and the end-to-end contract
126/// tests, so the suites cannot drift onto different shapes.
127pub const DENSIFICATION_FIXTURE_HEXAGON_WKT: &str = "POLYGON((-120.05194 58.28306, -126.05194 68.67536, -138.05194 68.67536, -144.05194 58.28306, -138.05194 47.89075, -126.05194 47.89075, -120.05194 58.28306))";
128/// Current process configuration (ingest and query covering both use it).
129pub fn coverer_config() -> CovererConfig {
130    CovererConfig {
131        min_level: MIN_LEVEL.load(Ordering::Relaxed),
132        max_level: MAX_LEVEL.load(Ordering::Relaxed),
133        max_cells: MAX_CELLS.load(Ordering::Relaxed).max(1),
134        densify_step_deg: f64::from_bits(DENSIFY_STEP.load(Ordering::Relaxed)),
135    }
136}
137
138/// Override the process coverer config (CLI / compute config / tests).
139///
140/// NOT cluster-wide (v1): two computes with different flags silently mix
141/// covering generations on the same CF; an operator must run
142/// `waratah geo rebuild-index` after changing these.
143///
144/// # Panics
145///
146/// Panics when `densify_step_deg` is not `0.0` (the documented disable
147/// sentinel), negative, NaN, or below [`MIN_DENSIFY_STEP_DEG`] — a
148/// misconfigured step must not silently disable or corrupt the
149/// candidate-superset contract, and a sub-floor step spends unbounded CPU and
150/// memory buying accuracy the covering's cell resolution cannot represent.
151pub fn set_coverer_config(config: CovererConfig) {
152    assert!(
153        config.densify_step_deg == 0.0
154            || (config.densify_step_deg.is_finite()
155                && config.densify_step_deg >= MIN_DENSIFY_STEP_DEG),
156        "densify_step_deg must be 0.0 (disabled) or a finite value >= \
157         MIN_DENSIFY_STEP_DEG ({MIN_DENSIFY_STEP_DEG}), got {}",
158        config.densify_step_deg
159    );
160    MIN_LEVEL.store(config.min_level, Ordering::Relaxed);
161    MAX_LEVEL.store(config.max_level, Ordering::Relaxed);
162    MAX_CELLS.store(config.max_cells.max(1), Ordering::Relaxed);
163    DENSIFY_STEP.store(config.densify_step_deg.to_bits(), Ordering::Relaxed);
164}
165
166/// Covering of a 2D point: exactly the level-30 leaf cell.
167///
168/// Points do **not** snap to `max_level` — a polygon covering at level 24
169/// skip-seeks `[C.range_min, C.range_max]`, which already includes every
170/// finer descendant, so the leaf posting is found without any parent math.
171pub fn point_leaf_cell(lon: f64, lat: f64) -> CellId {
172    CellId::from_lat_lng(&LatLng::from_degrees(lat, lon))
173}
174
175/// Normalize the shape aliases (`Rect`/`Triangle`/`Line`) into the canonical
176/// `Polygon`/`LineString` forms the covering arms handle, so normalization and
177/// densification run exactly once — at the top of [`geometry_covering`] — and
178/// ingest and query coverings cannot diverge.
179fn normalize_geometry(geometry: &Geometry<f64>) -> Geometry<f64> {
180    match geometry {
181        Geometry::Rect(rect) => Geometry::Polygon(rect.to_polygon()),
182        Geometry::Triangle(triangle) => Geometry::Polygon(triangle.to_polygon()),
183        Geometry::Line(line) => Geometry::LineString((*line).into()),
184        other => other.clone(),
185    }
186}
187
188/// Number of subdivision pieces for one segment: no piece exceeds `step`
189/// degrees in either coordinate; a zero-length (degenerate) segment emits its
190/// single vertex unchanged, so no vertex is ever lost.
191///
192/// The ceiling tolerates spans a rounding hair over `step` (the f64 noise of
193/// prior interpolation, ~1e-14 degrees): without the epsilon, re-densifying
194/// an already-densified ring re-splits those segments and the ring grows on
195/// every pass. The tolerance is relative — 1e-9 of the ratio, i.e. ~1e-10
196/// degrees at the default step — far below any meaningful step and far above
197/// the noise floor, which restores exact idempotence.
198///
199/// [`MAX_SEGMENT_PIECES`] bounds the result so a sub-floor step (possible
200/// only through a direct call that bypassed `set_coverer_config`) degrades
201/// the subdivision instead of hanging the emit loop.
202fn segment_pieces(a: &Coord<f64>, b: &Coord<f64>, step: f64) -> usize {
203    let span = (a.x - b.x).abs().max((a.y - b.y).abs());
204    let unbounded = ((span / step) - 1e-9).ceil().max(0.0) as usize;
205    unbounded.clamp(1, MAX_SEGMENT_PIECES)
206}
207
208/// Densify one coordinate sequence. A polygon ring (`closed = true`) is
209/// treated as a cyclic vertex sequence regardless of whether the closing
210/// vertex is carried explicitly; the output keeps the input's closure
211/// convention (explicitly closed in → explicitly closed out) with no
212/// duplicated vertex at the seam.
213fn densify_coords(pts: &[Coord<f64>], step: f64, closed: bool) -> Vec<Coord<f64>> {
214    if pts.len() < 2 {
215        return pts.to_vec();
216    }
217    let explicitly_closed = closed && pts.first() == pts.last();
218    let vertices: &[Coord<f64>] = if explicitly_closed {
219        &pts[..pts.len() - 1]
220    } else {
221        pts
222    };
223    let m = vertices.len();
224    if m < 2 {
225        return pts.to_vec();
226    }
227    let segments = if closed { m } else { m - 1 };
228    let mut out = Vec::new();
229    for i in 0..segments {
230        let a = &vertices[i];
231        let b = &vertices[(i + 1) % m];
232        let pieces = segment_pieces(a, b, step);
233        for k in 0..pieces {
234            let t = k as f64 / pieces as f64;
235            out.push(Coord {
236                x: a.x + t * (b.x - a.x),
237                y: a.y + t * (b.y - a.y),
238            });
239        }
240    }
241    // Re-establish the tail: the cyclic walk emits every vertex exactly once
242    // as a segment start, so only the closing/last vertex needs re-appending.
243    if closed {
244        out.push(vertices[0]);
245    } else {
246        out.push(vertices[m - 1]);
247    }
248    out
249}
250
251fn densify_linestring(line: &LineString<f64>, step: f64) -> LineString<f64> {
252    LineString::from(densify_coords(&line.0, step, false))
253}
254
255fn densify_polygon(polygon: &geo::Polygon<f64>, step: f64) -> geo::Polygon<f64> {
256    geo::Polygon::new(
257        LineString::from(densify_coords(&polygon.exterior().0, step, true)),
258        polygon
259            .interiors()
260            .iter()
261            .map(|ring| LineString::from(densify_coords(&ring.0, step, true)))
262            .collect(),
263    )
264}
265
266/// Densify the planar edges of every edge-carrying geometry family. Points
267/// have no edges (a point's geodesic position IS its planar position);
268/// `GeometryCollection` members densify on the recursive `geometry_covering`
269/// call. Idempotent: every segment of an already-densified geometry is at or
270/// under `step`, so re-densification reproduces the identical vertex sequence.
271fn densify_geometry(geometry: &Geometry<f64>, step: f64) -> Geometry<f64> {
272    if step <= 0.0 || step.is_nan() {
273        // Disabled (0.0), negative, or NaN (rejected at config time, this is
274        // defense-in-depth for direct callers): the division in
275        // `segment_pieces` would saturate to usize::MAX and hang.
276        return geometry.clone();
277    }
278    match geometry {
279        // Shape aliases convert to their canonical forms and re-enter here
280        // (depth-1 recursion: canonical shapes hit the real arms below), so
281        // a direct caller that skipped normalization cannot silently bypass
282        // densification by passing an alias variant.
283        Geometry::Rect(rect) => densify_geometry(&rect.to_polygon().into(), step),
284        Geometry::Triangle(triangle) => densify_geometry(&triangle.to_polygon().into(), step),
285        Geometry::Line(line) => densify_geometry(&Geometry::LineString((*line).into()), step),
286        Geometry::LineString(line) => Geometry::LineString(densify_linestring(line, step)),
287        Geometry::MultiLineString(lines) => Geometry::MultiLineString(geo::MultiLineString(
288            lines
289                .0
290                .iter()
291                .map(|line| densify_linestring(line, step))
292                .collect(),
293        )),
294        Geometry::Polygon(polygon) => Geometry::Polygon(densify_polygon(polygon, step)),
295        Geometry::MultiPolygon(multi) => Geometry::MultiPolygon(geo::MultiPolygon(
296            multi
297                .0
298                .iter()
299                .map(|polygon| densify_polygon(polygon, step))
300                .collect(),
301        )),
302        // Points carry no edges (a point's geodesic position IS its planar
303        // position); after the alias arms above, only the point families
304        // remain, and they pass through unchanged.
305        other => other.clone(),
306    }
307}
308
309/// Covering of a CRS84 polygon (or any area geometry) under the live config.
310///
311/// The coverer spends the `max_cells` budget on fewer, coarser cells that
312/// stick OUTSIDE the surface when the shape is awkward — a valid superset,
313/// which is exactly what a candidate probe needs.
314///
315/// **Densification contract:** S2 region edges are geodesic arcs, while WKT
316/// edges are straight lines in lon/lat space; on continental-scale edges the
317/// two interpretations of the same coordinates diverge by up to ~1° — far
318/// more than the covering's cell overshoot — so an undensified covering is
319/// NOT a superset of the planar (WKT/JTS/GeoSPARQL) region and the candidate
320/// index silently drops planar-inside geometries near such edges. Before the
321/// coverer runs, every polygon/line-string edge longer than
322/// `CovererConfig::densify_step_deg` is subdivided so the geodesic chain hugs
323/// the planar edge within that step's chord-deviation bound; ingest and query
324/// constants densify identically here, which is what makes the candidate set
325/// a superset of the exact planar answer. `0.0` disables (raw rings).
326///
327/// Edges whose endpoints straddle the antimeridian (e.g. `179.9` → `-179.9`
328/// longitude) densify the long planar way — straight through lon 0, the same
329/// 359.8° reading WKT/JTS give such an edge — so the contract holds against
330/// planar engines, but data with genuine antimeridian-crossing edges pays
331/// the full traverse in vertices and covering cost. If that cost bites,
332/// disable the step (`0.0`) or pre-split such rings at ±180.
333pub fn geometry_covering(geometry: &Geometry<f64>) -> CellUnion {
334    covering_with_config(geometry, &coverer_config())
335}
336
337/// [`geometry_covering`] under an explicit config — the testable inner half
338/// (the wrapper's global-config read would race parallel tests that mutate
339/// process configuration).
340fn covering_with_config(geometry: &Geometry<f64>, config: &CovererConfig) -> CellUnion {
341    let coverer = RegionCoverer::new()
342        .min_level(Level::new(config.min_level))
343        .max_level(Level::new(config.max_level))
344        .level_mod(LevelMod::new(1))
345        .max_cells(config.max_cells);
346    // Shape aliases first (Rect/Triangle/Line), then planar-edge
347    // densification — both once, at this choke point. Normalized aliases
348    // cannot reappear below; the alias arms remain as a safety net.
349    let normalized = normalize_geometry(geometry);
350    let geometry = if config.densify_step_deg > 0.0 {
351        densify_geometry(&normalized, config.densify_step_deg)
352    } else {
353        normalized
354    };
355    match &geometry {
356        Geometry::Polygon(polygon) => coverer.covering(&S2Polygon::from(polygon.clone())),
357        Geometry::MultiPolygon(multi) => {
358            // One budget for the whole MultiPolygon (owner contract): the
359            // members' individual `S2Polygon`s go into a single `RegionUnion`
360            // and ONE `covering` call splits `max_cells` across the whole
361            // set. Per-member construction is identical to the
362            // single-polygon arm (ring → loop, closing vertex stripped,
363            // shell/hole classification per member), so no cross-member loop
364            // reinterpretation is possible — a member can never be
365            // reinterpreted as another member's hole. The union region's
366            // covering is a superset of every member's region, so the worst
367            // failure mode on invalid input (overlapping member shells) is
368            // over-coverage, never under-coverage: a multi-loop polygon
369            // built from crossing/overlapping member loops could misassign
370            // nesting depth and exclude a member's area from the covering —
371            // a false-negative candidate, which the index must never
372            // produce. Uniform with the `MultiLineString` arm's treatment.
373            //
374            // Overlapping member shells are technically invalid S2Polygon
375            // input; we only use the polygons for covering (superset) —
376            // Relate happens on the geo crate geometry.
377            let polys_region = RegionUnion::from_regions(
378                multi
379                    .0
380                    .iter()
381                    .map(|polygon| Box::new(S2Polygon::from(polygon.clone())) as Box<dyn Region>)
382                    .collect::<Vec<_>>(),
383            );
384            coverer.covering(&polys_region)
385        }
386        Geometry::Point(point) => CellUnion::from_iter([point_leaf_cell(point.x(), point.y())]),
387        Geometry::LineString(line) => {
388            coverer.covering(&s2rst::s2::polyline::Polyline::from(line.clone()))
389        }
390        Geometry::MultiPoint(points) => {
391            // Tiered (owner decision): at or below
392            // `MAX_MULTIPOINT_EXACT_POINTS` every point keeps its exact
393            // level-30 leaf; above it the set is degenerate and takes ONE
394            // budgeted covering over the leaf cells instead (superset,
395            // ≤ max_cells).
396            if points.0.len() <= MAX_MULTIPOINT_EXACT_POINTS {
397                points
398                    .0
399                    .iter()
400                    .map(|point| point_leaf_cell(point.x(), point.y()))
401                    .collect::<CellUnion>()
402            } else {
403                let leaves = RegionUnion::from_regions(
404                    points
405                        .0
406                        .iter()
407                        .map(|point| {
408                            Box::new(s2rst::s2::Cell::from_cell_id(point_leaf_cell(
409                                point.x(),
410                                point.y(),
411                            ))) as Box<dyn Region>
412                        })
413                        .collect::<Vec<_>>(),
414                );
415                coverer.covering(&leaves)
416            }
417        }
418        Geometry::MultiLineString(lines) => {
419            // One budget for the whole MultiLineString (owner contract): the
420            // members' `Polyline`s go into a single `RegionUnion` and ONE
421            // `covering` call splits `max_cells` across them (the former
422            // per-member coverings minted up to `max_cells` EACH).
423            let members = RegionUnion::from_regions(
424                lines
425                    .0
426                    .iter()
427                    .map(|line| {
428                        Box::new(s2rst::s2::polyline::Polyline::from(line.clone()))
429                            as Box<dyn Region>
430                    })
431                    .collect::<Vec<_>>(),
432            );
433            coverer.covering(&members)
434        }
435        // Collections are MULTIPLE geometries: accumulate the members'
436        // (recursive) coverings; `CellUnion` collection normalizes (sorts,
437        // dedups, collapses nested cells), so this stays a valid union. The
438        // unbounded row multiplicity is bounded by the stored-geometry check
439        // in `prepare_geometry_literal`.
440        Geometry::GeometryCollection(collection) => collection
441            .0
442            .iter()
443            .flat_map(|member| {
444                // Recurse with THIS call's config, not the process-global
445                // step: an explicit-config call (the test seam, or any future
446                // config-carrying caller) must treat collections like every
447                // other family, or a step-0 request densifies members at the
448                // live global step.
449                let covering = covering_with_config(member, config);
450                covering.into_iter().collect::<Vec<_>>()
451            })
452            .collect::<CellUnion>(),
453        Geometry::Rect(rect) => {
454            let polygon: geo::Polygon<f64> = rect.to_polygon();
455            coverer.covering(&S2Polygon::from(polygon))
456        }
457        Geometry::Triangle(triangle) => {
458            let polygon: geo::Polygon<f64> = triangle.to_polygon();
459            coverer.covering(&S2Polygon::from(polygon))
460        }
461        Geometry::Line(line) => {
462            let line: geo::LineString<f64> = line.into();
463            coverer.covering(&s2rst::s2::polyline::Polyline::from(line))
464        }
465    }
466}
467
468/// Merge a covering into the GeoCandidateScan interval list: each covering
469/// cell contributes its `[range_min, range_max]` descendant range **plus**
470/// the exact ids of every proper ancestor (which catch indexed POINTS whose
471/// leaf cell is an ancestor of the query polygon's cells). Deduped and
472/// sorted by cell id.
473pub fn intervals_for_covering(covering: &CellUnion) -> Vec<GeoCellInterval> {
474    let mut intervals: Vec<GeoCellInterval> = Vec::with_capacity(covering.len() * 2);
475    for &id in covering.iter() {
476        let min = id.range_min().id();
477        let max = id.range_max().id();
478        intervals.push(GeoCellInterval {
479            min_cell_id: min.min(max),
480            max_cell_id: min.max(max),
481        });
482        // Proper ancestors as exact single-cell postings.
483        let mut parent = id;
484        while parent.level() > 0 {
485            parent = parent.parent();
486            intervals.push(GeoCellInterval::exact(parent.id()));
487        }
488    }
489    intervals.sort_unstable_by_key(|interval| interval.min_cell_id);
490    intervals.dedup();
491    intervals
492}
493
494/// Placeholder row density for the area-based geo scan estimate: rows per
495/// square degree of covered area. The FALLBACK when the rolled-up profile
496/// carries no geo cell-count histogram (fresh compute, stats not yet
497/// refreshed, or a store with no geo data) — replaces the former flat
498/// `GEO_SCAN_ESTIMATED_ROWS = 1000`.
499const ASSUMED_ROWS_PER_SQ_DEG: u64 = 1200;
500
501/// Square degrees per steradian on the unit sphere: the full globe is
502/// `4π ≈ 12.566` steradians ≈ `41252.97` square degrees, so 1 sr =
503/// `(180/π)² ≈ 3282.80635` sq deg. [`Cell::exact_area`] returns steradians.
504const SQ_DEG_PER_STERADIAN: f64 = 3282.80635;
505
506/// Area-based cardinality estimate for a geo scan covering: sum the exact
507/// cell areas (steradians), convert to square degrees, and multiply by the
508/// [`ASSUMED_ROWS_PER_SQ_DEG`] placeholder density. Clamped to ≥ 1 so any
509/// covering (including a single point leaf) estimates at least one row.
510///
511/// Deliberately crude: cell areas are the true sphere area, not the indexed
512/// term count under them — the per-bucket counts of the geo cell-count
513/// histogram are the real signal this fallback stands in for.
514pub fn covering_estimate_rows(covering: &[CellId]) -> u64 {
515    let steradians: f64 = covering
516        .iter()
517        .map(|&id| Cell::from_cell_id(id).exact_area())
518        .sum();
519    let square_degrees = steradians * SQ_DEG_PER_STERADIAN;
520    ((square_degrees * ASSUMED_ROWS_PER_SQ_DEG as f64) as u64).max(1)
521}
522
523/// The query covering as **disjoint** inclusive level-11 dense-index ranges
524/// (the bucket grid of `waratah_stats::GeoCellHistogram`).
525///
526/// Each covering cell at level ≥ 11 maps to its single L11 ancestor bucket;
527/// a coarser cell maps to the contiguous run of its L11 descendants (one S2
528/// cell never spans a face, and the dense index is Hilbert-ordered within a
529/// face, so the run needs no enumeration). Covering cells can nest (a coarse
530/// cell's descendants may also appear as their own covering entries), so the
531/// ranges are merged — summing unmerged ranges would multiply-count nested
532/// candidates.
533pub fn covering_l11_ranges(covering: &[CellId]) -> Vec<(u32, u32)> {
534    let mut ranges: Vec<(u32, u32)> = covering
535        .iter()
536        .filter_map(|&id| waratah_storage::geo_l11_bucket_range(id.id()))
537        .collect();
538    ranges.sort_unstable();
539    let mut merged: Vec<(u32, u32)> = Vec::with_capacity(ranges.len());
540    for (lo, hi) in ranges {
541        match merged.last_mut() {
542            Some(last) if lo <= last.1.saturating_add(1) => last.1 = last.1.max(hi),
543            _ => merged.push((lo, hi)),
544        }
545    }
546    merged
547}
548
549/// Covering row estimate from the rolled-up geo cell-count histogram: the
550/// exact / parent-average / clamp-1 ladder over the covering's L11 ranges
551/// (`GeoCellHistogram::estimate_ranges`). Posting multiplicity and the
552/// remainder summary both bias UP — the safe side for broadcast-vs-shuffle
553/// and build-arm placement; the one under-biased shape (a parent dropped by
554/// the remainder's own wire budget) reads empty, mirroring the area
555/// fallback's floor. Like the fallback, the result is clamped ≥ 1 so even
556/// an empty covering estimates one row (§10: never zero).
557pub fn covering_estimate_rows_from_histogram(
558    histogram: &waratah_stats::GeoCellHistogram,
559    covering: &[CellId],
560) -> u64 {
561    histogram
562        .estimate_ranges(&covering_l11_ranges(covering))
563        .max(1)
564}
565
566/// The query-side window derivation the geo planner performs for one
567/// constant-argument `geof:*` conjunct, exposed for diagnostics
568/// (`waratah geo census --window`): the WKT parses through the SAME ingest
569/// encode path as a query literal (CRS84-normalized, validity-checked,
570/// native forms only), the covering computes under the process coverer
571/// config, and both consumer views derive from it — the drain's cell-id
572/// intervals and the estimator's merged L11 ranges.
573pub struct WindowQueryShape {
574    /// Query covering under the process coverer config.
575    pub covering: CellUnion,
576    /// Drain view: the sorted cell-id intervals the storage scan walks
577    /// ([`intervals_for_covering`] — descendant ranges plus exact
578    /// ancestor cells).
579    pub intervals: Vec<GeoCellInterval>,
580    /// Estimator view: merged L11 dense-index ranges
581    /// ([`covering_l11_ranges`]).
582    pub l11_ranges: Vec<(u32, u32)>,
583}
584
585/// Derive a window's query shape from WKT text. Fails the same way the
586/// planner's conjunct match fails (parse / CRS / validity / non-native
587/// form), so the census window report prices exactly what a query over
588/// this WKT would price.
589pub fn window_query_shape(wkt: &str) -> Result<WindowQueryShape, crate::encode::GeoError> {
590    let literal = oxrdf::Literal::new_typed_literal(
591        wkt,
592        oxrdf::NamedNode::new_unchecked(crate::GEO_WKT_LITERAL),
593    );
594    let prepared = crate::encode::prepare_geometry_literal(&literal)?;
595    if !prepared.is_native() {
596        return Err(crate::encode::GeoError::InvalidGeometry(
597            "window geometry has no native indexable form".into(),
598        ));
599    }
600    let covering = geometry_covering(&prepared.geometry);
601    Ok(WindowQueryShape {
602        intervals: intervals_for_covering(&covering),
603        l11_ranges: covering_l11_ranges(&covering),
604        covering,
605    })
606}
607
608/// CRS84 envelope of a geometry (min/max over every coordinate). TODO(v1):
609/// no lon wrap — WKT lons past ±180 produce a raw min/max box that may
610/// compare disjoint from an overlapping antimeridian query (see
611/// `aabb_skip_for_lon_wrap`, which covers the span ≥ 180° case only).
612pub fn geometry_envelope(geometry: &Geometry<f64>) -> Option<GeoEnvelope> {
613    let rect = match geometry {
614        Geometry::Point(_) | Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {
615            geometry.bounding_rect()?
616        }
617        other => other.bounding_rect()?,
618    };
619    Some(GeoEnvelope {
620        min_lon: rect.min().x as f32,
621        min_lat: rect.min().y as f32,
622        max_lon: rect.max().x as f32,
623        max_lat: rect.max().y as f32,
624    })
625}
626
627/// Area ratio above which a covering cell is a "loose bucket" for the
628/// geometry and its posting value carries the envelope (plan §3: order of
629/// magnitude 4–10).
630const ENVELOPE_AREA_RATIO: f64 = 6.0;
631
632/// Cell level at or below which the posting always carries the envelope
633/// (a coarse parent is shared by many geometries).
634const ENVELOPE_LEVEL_FLOOR: u8 = 12;
635
636/// Whether the posting `(cell, geometry)` stores the envelope value.
637///
638/// Tight leaf-ish covering cells omit it (S2 already did the work);
639/// coarse cells carry it so the scan can AABB-reject candidates that S2's
640/// over-return pulled in. Axis-aligned rectangles benefit the most — and are
641/// exactly the shapes where Relate is cheapest to defer.
642pub fn should_store_envelope(cell_id: u64, envelope: &GeoEnvelope) -> bool {
643    let id = CellId(cell_id);
644    if id.level() <= ENVELOPE_LEVEL_FLOOR {
645        return true;
646    }
647    let cell_area = s2rst::s2::Cell::from_cell_id(id).exact_area();
648    let dlon = (envelope.max_lon as f64 - envelope.min_lon as f64).to_radians();
649    let dlat = (envelope.max_lat as f64 - envelope.min_lat as f64).to_radians();
650    let lat_mid = ((envelope.max_lat as f64 + envelope.min_lat as f64) / 2.0).to_radians();
651    let envelope_area = (dlon * dlat * lat_mid.cos()).abs();
652    if envelope_area <= 0.0 {
653        // Degenerate box (a point-like bbox): the envelope carries no extra
654        // information.
655        return false;
656    }
657    cell_area / envelope_area > ENVELOPE_AREA_RATIO
658}
659
660#[cfg(test)]
661mod tests {
662    /// A valid level-30 leaf cell id on `face` at Hilbert position `pos`.
663    fn histogram_leaf(face: u64, pos: u64) -> CellId {
664        CellId::from((face << 61) | (pos << 1) | 1)
665    }
666
667    #[test]
668    fn covering_l11_ranges_merge_nested_cells() {
669        // A coarse face-0 cell (level 8, digits 0) plus two leaves inside it
670        // (positions below 2^38): all three collapse to ONE range, and no
671        // bucket is counted twice.
672        let level8 = CellId::from(1u64 << (60 - 2 * 8));
673        let leaf_a = histogram_leaf(0, 5);
674        let leaf_b = histogram_leaf(0, 9);
675        let ranges = covering_l11_ranges(&[level8, leaf_a, leaf_b]);
676        assert_eq!(
677            ranges,
678            vec![(0, 63)],
679            "leaves nest inside the L8 cell's run"
680        );
681        // Face-1 leaves form a disjoint range.
682        let other = histogram_leaf(1, 5);
683        let ranges = covering_l11_ranges(&[level8, other]);
684        assert_eq!(
685            ranges,
686            vec![(0, 63), (1 << 22, 1 << 22)],
687            "faces never merge: the dense index is face-salted"
688        );
689    }
690
691    #[test]
692    fn histogram_estimate_beats_the_area_fallback_on_skew() {
693        // Two face-0 L11 buckets with wildly different densities: bucket 0
694        // holds 2000 postings, bucket 1 holds 2. The area fallback prices
695        // both the same (same cell area); the histogram ladder reads the
696        // counts.
697        let mut hist = waratah_stats::GeoCellHistogram::default();
698        for i in 0..2000u64 {
699            hist.observe_posting(histogram_leaf(0, i).id());
700        }
701        for i in 0..2u64 {
702            hist.observe_posting(histogram_leaf(0, (1 << 38) + i).id());
703        }
704        let covering = vec![histogram_leaf(0, 0), histogram_leaf(0, 1 << 38)];
705        assert_eq!(
706            covering_estimate_rows_from_histogram(&hist, &covering),
707            2002,
708        );
709        // The empty-space win: a covering over face-3 (no data) prices at
710        // the clamp, where the area fallback prices the level-2 cell's
711        // ~400 sq deg at placeholder density (S2 cell areas vary by
712        // position within a level).
713        let empty = vec![CellId::from(3 << 61 | 1 << 56)];
714        assert_eq!(covering_estimate_rows_from_histogram(&hist, &empty), 1);
715        assert!(covering_estimate_rows(&empty) > 100_000);
716    }
717
718    use super::*;
719    use geo::wkt;
720    use pretty_assertions::assert_eq;
721
722    #[test]
723    fn point_covers_exactly_its_leaf() {
724        let leaf = point_leaf_cell(153.025, -27.47);
725        assert_eq!(u8::from(leaf.level()), 30);
726        let covering = geometry_covering(&Geometry::Point(geo::Point::new(153.025, -27.47)));
727        assert_eq!(covering.to_vec(), vec![leaf]);
728    }
729
730    #[test]
731    fn polygon_covering_is_bounded_and_contains_an_interior_leaf() {
732        let polygon = wkt!(POLYGON((
733            152.0 - 28.0,
734            153.0 - 28.0,
735            153.0 - 27.0,
736            152.0 - 27.0,
737            152.0 - 28.0
738        )));
739        let covering = geometry_covering(&Geometry::Polygon(polygon));
740        assert!(!covering.is_empty());
741        assert!(covering.len() <= coverer_config().max_cells + 6);
742        for id in &covering {
743            assert!(
744                u8::from(id.level()) <= coverer_config().max_level,
745                "no cell finer than max_level"
746            );
747        }
748        // The union of cell ranges contains a known interior point's leaf.
749        let interior = point_leaf_cell(152.5, -27.5);
750        assert!(covering.iter().any(|id| {
751            let (min, max) = (id.range_min().id(), id.range_max().id());
752            interior.id() >= min.min(max) && interior.id() <= min.max(max)
753        }));
754    }
755
756    #[test]
757    fn intervals_include_descendant_ranges_and_ancestors() {
758        let point = point_leaf_cell(153.025, -27.47);
759        let intervals = intervals_for_covering(&CellUnion::from_iter([point]));
760        // The leaf itself contributes its own [range_min, range_max] (a
761        // single id) and 30 ancestors.
762        assert!(intervals.len() >= 30);
763        let exact = intervals
764            .iter()
765            .find(|i| i.min_cell_id == point.id() && i.max_cell_id == point.id());
766        assert!(exact.is_some());
767        // Sorted, deduped.
768        for pair in intervals.windows(2) {
769            assert!(pair[0].min_cell_id <= pair[1].min_cell_id);
770        }
771    }
772
773    #[test]
774    fn envelope_stores_on_loose_cells_only() {
775        let envelope = GeoEnvelope {
776            min_lon: 152.0,
777            min_lat: -28.0,
778            max_lon: 153.0,
779            max_lat: -27.0,
780        };
781        // A level-4 cell is a very loose bucket for this box.
782        let face_cell = CellId::from_lat_lng(&LatLng::from_degrees(-27.5, 152.5))
783            .parent_at_level(Level::new(4));
784        assert!(should_store_envelope(face_cell.id(), &envelope));
785        // A tight leaf-level cell covering the whole box is not loose.
786        let covering = geometry_covering(&Geometry::Polygon(wkt!(POLYGON((
787            152.0 - 28.0,
788            153.0 - 28.0,
789            153.0 - 27.0,
790            152.0 - 27.0,
791            152.0 - 28.0
792        )))));
793        let finest = covering
794            .iter()
795            .map(|c| c.level())
796            .max()
797            .unwrap_or(s2rst::s2::Level::MIN);
798        let tight = covering
799            .iter()
800            .copied()
801            .find(|c| c.level() == finest)
802            .unwrap();
803        // A cell whose area is small relative to the box must NOT store it.
804        let cell_area = s2rst::s2::Cell::from_cell_id(tight).exact_area();
805        let box_area =
806            (1.0_f64.to_radians() * 1.0_f64.to_radians() * (-27.5_f64.to_radians().cos())).abs();
807        if cell_area / box_area <= 6.0 && tight.level() > 12 {
808            assert!(!should_store_envelope(tight.id(), &envelope));
809        }
810    }
811
812    #[test]
813    fn estimate_is_clamped_dense_and_monotonic_in_area() {
814        // Empty covering: clamped to at least one row (a scan is never free).
815        assert_eq!(covering_estimate_rows(&[]), 1);
816        // A single point leaf: tiny real area, still ≥ 1.
817        let leaf = point_leaf_cell(153.025, -27.47);
818        assert!(covering_estimate_rows(std::slice::from_ref(&leaf)) >= 1);
819        // Monotonic in covered area: a 1° box estimates strictly less than a
820        // 10° box around the same center (coarse covering cells shrink as the
821        // shape grows, so their summed exact area grows too).
822        let small = geometry_covering(&Geometry::Polygon(wkt!(POLYGON((
823            152.0 - 28.0,
824            153.0 - 28.0,
825            153.0 - 27.0,
826            152.0 - 27.0,
827            152.0 - 28.0
828        )))));
829        let big = geometry_covering(&Geometry::Polygon(wkt!(POLYGON((
830            147.5 - 32.5,
831            157.5 - 32.5,
832            157.5 - 22.5,
833            147.5 - 22.5,
834            147.5 - 32.5
835        )))));
836        let small_rows = covering_estimate_rows(&small);
837        let big_rows = covering_estimate_rows(&big);
838        assert!(small_rows >= 1);
839        assert!(
840            big_rows > small_rows,
841            "bigger polygon must estimate more rows: {big_rows} <= {small_rows}"
842        );
843        // Density: the 10°×10° box sits near 100 sq deg × cos(lat) ≈ 91 sq
844        // deg; at the placeholder density that is ~110k rows. Assert the
845        // order of magnitude rather than an exact cell sum.
846        assert!(
847            big_rows > 10_000 && big_rows < 1_000_000,
848            "10° box estimate out of the expected order of magnitude: {big_rows}"
849        );
850    }
851
852    #[test]
853    fn config_round_trip() {
854        let before = coverer_config();
855        set_coverer_config(CovererConfig {
856            min_level: 2,
857            max_level: 20,
858            max_cells: 8,
859            densify_step_deg: 0.25,
860        });
861        assert_eq!(
862            coverer_config(),
863            CovererConfig {
864                min_level: 2,
865                max_level: 20,
866                max_cells: 8,
867                densify_step_deg: 0.25,
868            }
869        );
870        set_coverer_config(before);
871    }
872
873    #[test]
874    #[should_panic(expected = "densify_step_deg must be 0.0 (disabled) or a finite value")]
875    fn negative_densify_step_is_rejected() {
876        set_coverer_config(CovererConfig {
877            min_level: 0,
878            max_level: 24,
879            max_cells: 40,
880            densify_step_deg: -1.0,
881        });
882    }
883
884    #[test]
885    #[should_panic(expected = "MIN_DENSIFY_STEP_DEG (0.0001)")]
886    fn sub_floor_densify_step_is_rejected() {
887        // A positive-but-tiny step drives the piece count to usize::MAX (the
888        // emit loop would hang or OOM) while buying accuracy the covering's
889        // cell resolution cannot represent — rejected at config time.
890        set_coverer_config(CovererConfig {
891            min_level: 0,
892            max_level: 24,
893            max_cells: 40,
894            densify_step_deg: 1e-6,
895        });
896    }
897
898    #[test]
899    fn segment_pieces_is_bounded_for_pathological_steps() {
900        // Defense-in-depth: a direct densify call with a sub-floor step
901        // degrades to the piece bound instead of hanging the emit loop.
902        let a = Coord { x: 0.0, y: 0.0 };
903        let b = Coord { x: 100.0, y: 100.0 };
904        assert_eq!(segment_pieces(&a, &b, 1e-15), MAX_SEGMENT_PIECES);
905        // Legitimate steps are unaffected by the bound.
906        assert_eq!(segment_pieces(&a, &b, 0.1), 1000);
907        assert_eq!(segment_pieces(&a, &b, 1.0), 100);
908    }
909
910    /// True when `leaf` sits inside some covering cell's `[range_min,
911    /// range_max]` descendant range — the same containment probe the
912    /// polygon test uses.
913    fn leaf_is_covered(covering: &CellUnion, leaf: CellId) -> bool {
914        covering.iter().any(|id| {
915            let (min, max) = (id.range_min().id(), id.range_max().id());
916            leaf.id() >= min.min(max) && leaf.id() <= min.max(max)
917        })
918    }
919
920    #[test]
921    fn multipolygon_covering_is_one_budget_and_covers_each_member() {
922        // Two disjoint members; the second carries a hole. The hole is NOT
923        // asserted against — the covering is a superset by design — only
924        // the per-geometry budget and per-member coverage are.
925        let multi = wkt!(MULTIPOLYGON(
926            ((
927                152.0 - 28.0,
928                153.0 - 28.0,
929                153.0 - 27.0,
930                152.0 - 27.0,
931                152.0 - 28.0
932            )),
933            (
934                (
935                    150.0 - 30.0,
936                    151.0 - 30.0,
937                    151.0 - 29.0,
938                    150.0 - 29.0,
939                    150.0 - 30.0
940                ),
941                (
942                    150.3 - 29.7,
943                    150.8 - 29.7,
944                    150.8 - 29.3,
945                    150.3 - 29.3,
946                    150.3 - 29.7
947                )
948            )
949        ));
950        let covering = geometry_covering(&Geometry::MultiPolygon(multi));
951        assert!(!covering.is_empty());
952        // ONE `max_cells` budget for the WHOLE multipolygon (owner
953        // contract), not one per member.
954        assert!(
955            covering.len() <= coverer_config().max_cells + 6,
956            "multi-multipolygon covering of {} cells exceeds the per-geometry budget",
957            covering.len()
958        );
959        // Each member's known interior point's leaf is covered — the second
960        // point is in the second member's shell but OUTSIDE its hole.
961        for leaf in [point_leaf_cell(152.5, -27.5), point_leaf_cell(150.1, -29.9)] {
962            assert!(leaf_is_covered(&covering, leaf));
963        }
964    }
965
966    #[test]
967    fn multilinestring_covering_is_one_budget_and_covers_each_member() {
968        let lines = wkt!(MULTILINESTRING(
969            (152.0 - 28.0, 153.0 - 28.0),
970            (150.0 - 30.0, 150.0 - 29.0)
971        ));
972        let covering = geometry_covering(&Geometry::MultiLineString(lines));
973        assert!(!covering.is_empty());
974        // ONE budget for the whole MultiLineString (owner contract).
975        assert!(
976            covering.len() <= coverer_config().max_cells + 6,
977            "multilinestring covering of {} cells exceeds the per-geometry budget",
978            covering.len()
979        );
980        // Each member's midpoint leaf is covered.
981        for leaf in [point_leaf_cell(152.5, -28.0), point_leaf_cell(150.0, -29.5)] {
982            assert!(leaf_is_covered(&covering, leaf));
983        }
984    }
985
986    #[test]
987    fn multipoint_tiers_between_exact_leaves_and_budgeted_covering() {
988        // Tier 1 (<= 1024 points): pairwise-distinct points keep their exact
989        // level-30 leaves — exactly one distinct cell per point.
990        let small: Vec<geo::Point<f64>> = (0..50)
991            .map(|i| geo::Point::new(140.0 + i as f64 * 0.01, -30.0 + i as f64 * 0.02))
992            .collect();
993        let covering = geometry_covering(&Geometry::MultiPoint(geo::MultiPoint::new(small)));
994        assert_eq!(covering.len(), 50, "exact leaf per point, no budget");
995        // Tier 2 (> 1024 points): a degenerate point set takes ONE budgeted
996        // covering over the leaves instead.
997        let big: Vec<geo::Point<f64>> = (0..2000)
998            .map(|i| {
999                geo::Point::new(
1000                    140.0 + (i % 50) as f64 * 0.5,
1001                    -40.0 + (i / 50) as f64 * 0.05,
1002                )
1003            })
1004            .collect();
1005        let covering = geometry_covering(&Geometry::MultiPoint(geo::MultiPoint::new(big)));
1006        assert!(!covering.is_empty());
1007        assert!(
1008            covering.len() <= coverer_config().max_cells,
1009            "2000-point multipoint covering of {} cells exceeds the budget",
1010            covering.len()
1011        );
1012    }
1013
1014    // ---- planar-edge densification ----
1015
1016    fn cfg(step: f64) -> CovererConfig {
1017        CovererConfig {
1018            min_level: 0,
1019            max_level: 24,
1020            max_cells: 40,
1021            densify_step_deg: step,
1022        }
1023    }
1024
1025    /// The densification-contract fixture: the shared hexagon const parsed
1026    /// through the production literal parser, so the unit suite and the
1027    /// end-to-end tests exercise one canonical shape. Its SE/SW edges bow up
1028    /// to ~0.67° INTO the polygon interior under geodesic interpretation,
1029    /// which is what made the raw covering miss planar-inside points near
1030    /// them.
1031    fn hexagon() -> Geometry<f64> {
1032        let literal = oxrdf::Literal::new_typed_literal(
1033            DENSIFICATION_FIXTURE_HEXAGON_WKT,
1034            oxrdf::NamedNode::new_unchecked(crate::encode::GEO_WKT_LITERAL),
1035        );
1036        let (geometry, _) = crate::encode::parse_geometry_literal(&literal)
1037            .expect("densification fixture hexagon must parse");
1038        geometry
1039    }
1040
1041    #[test]
1042    fn densify_ring_preserves_closure_and_vertex_order() {
1043        // Explicitly closed square, 1.0-degree edges, step 0.4: each edge
1044        // subdivides into ceil(1.0/0.4) = 3 pieces.
1045        let square = LineString::from(vec![
1046            Coord { x: 0.0, y: 0.0 },
1047            Coord { x: 1.0, y: 0.0 },
1048            Coord { x: 1.0, y: 1.0 },
1049            Coord { x: 0.0, y: 1.0 },
1050            Coord { x: 0.0, y: 0.0 },
1051        ]);
1052        let out = densify_coords(&square.0, 0.4, true);
1053        // 4 edges x 3 pieces + re-closed seam vertex = 13.
1054        assert_eq!(out.len(), 13);
1055        assert_eq!(out.first(), out.last(), "re-closed ring");
1056        assert_eq!(out[0], Coord { x: 0.0, y: 0.0 });
1057        // Every output vertex lies on the original ring boundary.
1058        for coord in &out {
1059            let on_edge = (coord.y.abs() <= f64::EPSILON && coord.x <= 1.0)
1060                || (coord.x.abs() <= f64::EPSILON && coord.y <= 1.0)
1061                || ((coord.x - 1.0).abs() <= f64::EPSILON && coord.y <= 1.0)
1062                || ((coord.y - 1.0).abs() <= f64::EPSILON && coord.x <= 1.0);
1063            assert!(on_edge, "densified vertex drifted off the ring: {coord:?}");
1064        }
1065    }
1066
1067    #[test]
1068    fn densify_open_ring_gains_explicit_closure() {
1069        // Same square WITHOUT the closing vertex: the cyclic walk densifies
1070        // the closing segment too and re-closes explicitly.
1071        let open = vec![
1072            Coord { x: 0.0, y: 0.0 },
1073            Coord { x: 1.0, y: 0.0 },
1074            Coord { x: 1.0, y: 1.0 },
1075            Coord { x: 0.0, y: 1.0 },
1076        ];
1077        let out = densify_coords(&open, 0.5, true);
1078        assert_eq!(out.first(), out.last(), "explicitly re-closed");
1079        // 4 edges x 2 pieces (ceil(1.0/0.5)) + closure = 9.
1080        assert_eq!(out.len(), 9);
1081    }
1082
1083    #[test]
1084    fn densify_open_path_stays_open() {
1085        let path = vec![Coord { x: 0.0, y: 0.0 }, Coord { x: 2.0, y: 0.0 }];
1086        let out = densify_coords(&path, 0.5, false);
1087        assert_eq!(out.len(), 5, "ceil(2.0/0.5) = 4 pieces + final vertex");
1088        assert_eq!(out.last(), Some(&Coord { x: 2.0, y: 0.0 }));
1089    }
1090
1091    #[test]
1092    fn densify_degenerate_segment_keeps_vertex() {
1093        // A repeated coordinate must survive densification (no vertex loss on
1094        // zero-length segments).
1095        let pts = vec![
1096            Coord { x: 0.0, y: 0.0 },
1097            Coord { x: 0.0, y: 0.0 },
1098            Coord { x: 1.0, y: 0.0 },
1099        ];
1100        let out = densify_coords(&pts, 0.1, false);
1101        assert_eq!(out[0], Coord { x: 0.0, y: 0.0 });
1102        assert_eq!(out[1], Coord { x: 0.0, y: 0.0 });
1103        assert_eq!(out.last(), Some(&Coord { x: 1.0, y: 0.0 }));
1104    }
1105
1106    #[test]
1107    fn densify_is_idempotent() {
1108        let raw = hex_ring_coords();
1109        let once = densify_coords(&raw, 0.1, true);
1110        let twice = densify_coords(&once, 0.1, true);
1111        assert_eq!(once.len(), twice.len(), "vertex counts must match");
1112        for (i, (a, b)) in once.iter().zip(twice.iter()).enumerate() {
1113            assert_eq!(a, b, "vertex {i} differs on re-densification");
1114        }
1115        assert_eq!(
1116            once, twice,
1117            "re-densifying an already-densified ring is a no-op"
1118        );
1119    }
1120
1121    /// The hexagon as an explicitly closed coordinate sequence, for the direct
1122    /// helper tests.
1123    fn hex_ring_coords() -> Vec<Coord<f64>> {
1124        HEX_DENSIFY_FIXTURE
1125            .iter()
1126            .map(|(x, y)| Coord { x: *x, y: *y })
1127            .collect()
1128    }
1129
1130    /// The hexagon as an open vertex list, for the direct-helper tests.
1131    const HEX_DENSIFY_FIXTURE: [(f64, f64); 7] = [
1132        (-120.05194, 58.28306),
1133        (-126.05194, 68.67536),
1134        (-138.05194, 68.67536),
1135        (-144.05194, 58.28306),
1136        (-138.05194, 47.89075),
1137        (-126.05194, 47.89075),
1138        (-120.05194, 58.28306),
1139    ];
1140
1141    #[test]
1142    fn densify_point_and_multipoint_pass_through() {
1143        let point = Geometry::Point(wkt!(POINT(1.0 2.0)));
1144        let out = densify_geometry(&point, 0.1);
1145        assert_eq!(out, point);
1146        let multi = Geometry::MultiPoint(wkt!(MULTIPOINT(1.0 2.0, 3.0 4.0)));
1147        let out = densify_geometry(&multi, 0.1);
1148        assert_eq!(out, multi);
1149    }
1150
1151    /// True when `leaf` is inside some covering cell's descendant range — the
1152    /// same probe the partition's interval walk performs.
1153    fn leaf_is_in_intervals(covering: &CellUnion, leaf: CellId) -> bool {
1154        let leaf_id = leaf.id();
1155        intervals_for_covering(covering)
1156            .iter()
1157            .any(|interval| interval.min_cell_id <= leaf_id && leaf_id <= interval.max_cell_id)
1158    }
1159
1160    #[test]
1161    fn densified_covering_is_a_superset_of_the_planar_region() {
1162        // The densification contract: a planar-inside point near a long edge
1163        // must survive the candidate lookup. With densification ON every
1164        // probe point below is a candidate; with it OFF the deep SE-edge
1165        // points are not (the raw geodesic covering excludes them).
1166        let hexagon = hexagon();
1167        let (a, b) = (HEX_DENSIFY_FIXTURE[5], HEX_DENSIFY_FIXTURE[0]);
1168        let (dx, dy) = (b.0 - a.0, b.1 - a.1);
1169        let len = (dx * dx + dy * dy).sqrt();
1170        let (nx, ny) = (-dy / len, dx / len); // interior side (CCW left)
1171
1172        let densified = covering_with_config(&hexagon, &cfg(0.1));
1173        let raw = covering_with_config(&hexagon, &cfg(0.0));
1174
1175        // r1: planar-inside at ~0.16° perpendicular depth from the SE edge —
1176        // the geodesic reading of that edge passes at lat 53.845 here, north
1177        // of the point, so the raw covering excludes it while the densified
1178        // one must capture it.
1179        let r1 = (-123.0, 53.5);
1180        assert!(
1181            leaf_is_in_intervals(&densified, point_leaf_cell(r1.0, r1.1)),
1182            "densified covering must capture r1"
1183        );
1184        assert!(
1185            !leaf_is_in_intervals(&raw, point_leaf_cell(r1.0, r1.1)),
1186            "raw (undensified) covering misses r1 — the pre-fix behavior"
1187        );
1188
1189        // Perpendicular-depth ladder along the SE edge, in degrees (0.001° ≈
1190        // 111 m, 0.0001° ≈ 11 m): the finest rung still sits ~6 m beyond the
1191        // ~5 m chord-deviation bound of a 0.1° step, so every rung must be
1192        // captured — the 0.0001° rung pins the capture band far below the
1193        // 111 m granularity the coarser rungs test.
1194        for depth in [0.0001f64, 0.001, 0.005, 0.01, 0.05, 0.1, 0.3] {
1195            for f in [0.1f64, 0.3, 0.5, 0.7, 0.9] {
1196                let probe = (a.0 + f * dx + depth * nx, a.1 + f * dy + depth * ny);
1197                assert!(
1198                    leaf_is_in_intervals(&densified, point_leaf_cell(probe.0, probe.1)),
1199                    "densified covering missed SE-edge probe at depth {depth} f={f}: {probe:?}"
1200                );
1201            }
1202        }
1203    }
1204
1205    #[test]
1206    fn densify_step_zero_disables_raw_rings() {
1207        // The disable sentinel passes the geometry through unchanged and
1208        // reproduces the raw (pre-densification) covering — the A/B escape
1209        // hatch for benchmarking and the pre-fix behavior reference.
1210        let hexagon = hexagon();
1211        let direct = densify_geometry(&hexagon, 0.0);
1212        assert_eq!(direct, hexagon, "step 0 passthrough");
1213        let disabled = covering_with_config(&hexagon, &cfg(0.0));
1214        let raw_cell_count = disabled.iter().count();
1215        assert!(
1216            raw_cell_count > 0 && raw_cell_count <= 40,
1217            "raw covering must respect the cell budget, got {raw_cell_count}"
1218        );
1219        // And the disabled output differs from the densified output on the
1220        // hexagon (the densified covering strictly adds capture band).
1221        let densified = covering_with_config(&hexagon, &cfg(0.1));
1222        let densified_cells = densified.iter().map(|c| c.id()).collect::<Vec<_>>();
1223        let disabled_cells = disabled.iter().map(|c| c.id()).collect::<Vec<_>>();
1224        assert_ne!(
1225            densified_cells, disabled_cells,
1226            "densification must change the hexagon's covering cells"
1227        );
1228    }
1229
1230    #[test]
1231    fn alias_shapes_densify_through_their_canonical_forms() {
1232        // Rect/Triangle/Line reach densify_geometry as alias variants: they
1233        // must convert to their canonical Polygon/LineString forms and
1234        // densify, never pass through, so a caller that skips normalization
1235        // cannot silently post raw rings under a non-zero step.
1236        let rect: Geometry<f64> =
1237            geo::Rect::new(Coord { x: 0.0, y: 0.0 }, Coord { x: 10.0, y: 5.0 }).into();
1238        let Geometry::Polygon(rect_ring) = densify_geometry(&rect, 0.5) else {
1239            panic!("rect must densify as a polygon");
1240        };
1241        assert!(
1242            rect_ring.exterior().0.len() > 10,
1243            "rect edges must be subdivided, got {} ring vertices",
1244            rect_ring.exterior().0.len()
1245        );
1246
1247        let triangle: Geometry<f64> = geo::Triangle::new(
1248            Coord { x: 0.0, y: 0.0 },
1249            Coord { x: 10.0, y: 0.0 },
1250            Coord { x: 0.0, y: 10.0 },
1251        )
1252        .into();
1253        let Geometry::Polygon(triangle_ring) = densify_geometry(&triangle, 0.5) else {
1254            panic!("triangle must densify as a polygon");
1255        };
1256        assert!(
1257            triangle_ring.exterior().0.len() > 10,
1258            "triangle edges must be subdivided, got {} ring vertices",
1259            triangle_ring.exterior().0.len()
1260        );
1261
1262        let line: Geometry<f64> =
1263            geo::Line::new(Coord { x: 0.0, y: 0.0 }, Coord { x: 10.0, y: 0.0 }).into();
1264        let Geometry::LineString(densified_line) = densify_geometry(&line, 0.5) else {
1265            panic!("line must densify as a line string");
1266        };
1267        assert!(
1268            densified_line.0.len() > 2,
1269            "the line's edge must be subdivided, got {} vertices",
1270            densified_line.0.len()
1271        );
1272    }
1273
1274    #[test]
1275    fn antimeridian_edges_densify_the_long_planar_way() {
1276        // An edge 179.9°E → 179.9°W is a 359.8° traverse in lon/lat space —
1277        // the reading WKT/JTS give it — not a 0.2° hop across ±180. The
1278        // densified chain must follow that planar reading (vertices march
1279        // through lon 0, never wrap at the antimeridian) so the covering
1280        // stays a superset of the planar region; the piece count reflects
1281        // the full traverse, which is the documented cost for such data.
1282        let line: Geometry<f64> = wkt!(LINESTRING(179.9 10.0, -179.9 10.0)).into();
1283        let densified = densify_geometry(&line, 1.0);
1284        let Geometry::LineString(densified) = densified else {
1285            panic!("line in, line out");
1286        };
1287        // ~360 pieces at a 1.0° step, not one segment.
1288        assert!(
1289            densified.0.len() >= 300,
1290            "long-way traverse must be subdivided, got {} vertices",
1291            densified.0.len()
1292        );
1293        // The chain passes through lon 0 — a short-hop reading would keep
1294        // every vertex inside the [179.9, 180] ∪ [-180, -179.9] band, so no
1295        // vertex may sit beyond the endpoints' longitudes either.
1296        assert!(
1297            densified.0.iter().any(|c| c.x.abs() < 90.0),
1298            "traverse must pass through lon 0 (the long planar way)"
1299        );
1300        assert!(
1301            densified.0.iter().all(|c| c.x.abs() <= 179.9 + 1e-9),
1302            "no vertex may wrap past ±180 (the short-hop reading)"
1303        );
1304    }
1305
1306    #[test]
1307    fn collection_members_cover_under_the_callers_config() {
1308        // Regression: the GeometryCollection arm used to re-enter the public
1309        // wrapper and re-read the process-global step, so an explicit step-0
1310        // call densified members at the live default — making
1311        // `covering_with_config` family-dependent (and the test seam racy).
1312        // A single-member collection must cover exactly like its bare member
1313        // under whatever config the caller passed.
1314        let hexagon = hexagon();
1315        let collection =
1316            Geometry::GeometryCollection(geo::GeometryCollection(vec![hexagon.clone()]));
1317        let member_only = covering_with_config(&hexagon, &cfg(0.0));
1318        let via_collection = covering_with_config(&collection, &cfg(0.0));
1319        assert_eq!(
1320            via_collection.iter().map(|c| c.id()).collect::<Vec<_>>(),
1321            member_only.iter().map(|c| c.id()).collect::<Vec<_>>(),
1322            "single-member collection covers exactly like its member under the caller's config"
1323        );
1324        // Sensitivity check: the assertion above must be able to fail. Under
1325        // the default step the same member covers differently from step 0.
1326        let densified_member = covering_with_config(&hexagon, &cfg(0.1));
1327        assert_ne!(
1328            member_only.iter().map(|c| c.id()).collect::<Vec<_>>(),
1329            densified_member.iter().map(|c| c.id()).collect::<Vec<_>>(),
1330            "sanity: step 0 and step 0.1 coverings differ on this fixture"
1331        );
1332    }
1333}