Skip to main content

waratah_storage/encode/
geo_index.rs

1//! O-axis geometry index (`geo_index` CF): compute-derived S2 postings.
2//!
3//! ```text
4//! key   = s2_cell_id_u64_be(8) ‖ encode_term_bytes(geo_term) ‖ commit_ts_desc(8)
5//! value = op u8 ‖ visibility u32 ‖ [ CRS84 envelope: min_lon, min_lat,
6//!                                      max_lon, max_lat as 4 × f32 BE ]
7//! ```
8//!
9//! Compute owns **all** S2 math: the partition applies postings verbatim — it
10//! never derives cell ids, never runs a region coverer, and never touches the
11//! blob store. This module is only the byte layout, the MVCC walk, and the
12//! optional-envelope AABB reject.
13//!
14//! Invariant for later O hash-subsharding: this CF is **range-partitioned by
15//! cell id**, never by term hash.
16//!
17//! TODO(v1 limitation, lon wrap): WKT may carry longitudes past ±180 (e.g.
18//! 190). A raw min/max envelope of such a ring compares disjoint from a
19//! −170..−160 query envelope while the rings overlap. The conservative fix —
20//! wrapping stored/query lons to [−180, 180) at ingest so every
21//! dateline-crossing envelope has span ≥ 180° (already the skip-reject case)
22//! — is deliberately NOT implemented in v1; AU/NZ regional data is the
23//! intended operating region.
24
25use rustc_hash::FxHashSet;
26
27use super::binary::TermReader;
28use super::versioned::{COMMIT_TS_LEN, STORAGE_VALUE_LEN, encode_storage_value};
29use crate::StorageError;
30use crate::types::{CommitTs, SnapshotId, StorageOp, VisibilityLabel};
31
32/// RocksDB column-family name. Opened only on [`crate::PartitionAxis::O`].
33pub const GEO_INDEX_CF: &str = "geo_index";
34
35/// RocksDB column-family name for geo-index metadata. Opened only on
36/// [`crate::PartitionAxis::O`]. Two reserved keys (the rebuild epoch and its
37/// liveness marker) — no walker ever touches it, so reserved keys are
38/// unambiguous.
39pub const GEO_INDEX_META_CF: &str = "geo_index_meta";
40
41/// The one reserved key in [`GEO_INDEX_META_CF`]: the rebuild epoch as
42/// 8-byte big-endian (`u64` commit_ts).
43pub const GEO_INDEX_EPOCH_KEY: &[u8] = b"geo_index_epoch";
44
45/// The other reserved key in [`GEO_INDEX_META_CF`]: the rebuild LIVENESS
46/// marker, holding the epoch it was stamped with (8-byte big-endian).
47///
48/// Why a second key: the epoch must be able to OUTLIVE the index. An operator
49/// wiping the `geo_index` CF, or a rebuild that took the lease and died
50/// mid-walk, leaves the postings empty while `geo_index_epoch` still reads as
51/// stamped — and a trusted-but-empty index answers every `geof:*` rewrite with
52/// zero rows. That is the §10 forbidden class, and the missing-epoch-untrusted
53/// gate does not cover it because the epoch is still there.
54///
55/// So the marker lives beside the epoch, and `wipe_geo_index` clears the
56/// MARKER (not the epoch). The two are written together by
57/// `set_geo_index_epoch` and read together by `geo_index_epoch`, which
58/// reports `None` — untrusted, exactly like a missing epoch — unless both are
59/// present and agree. This also keeps the ESTIMATES flowing: the marker gates
60/// only the rewrite's trust decision, never anything a sketch or a placeholder
61/// density needs.
62pub const GEO_INDEX_LIVENESS_KEY: &[u8] = b"geo_index_live";
63
64/// Byte length of a persisted epoch value (big-endian `u64`).
65pub const GEO_EPOCH_VALUE_LEN: usize = 8;
66
67/// Byte length of a persisted liveness marker (big-endian `u64` epoch).
68pub const GEO_LIVENESS_VALUE_LEN: usize = 8;
69
70/// Encode a persisted geo-index epoch as 8-byte big-endian.
71pub fn encode_geo_epoch(epoch: u64) -> Vec<u8> {
72    epoch.to_be_bytes().to_vec()
73}
74
75/// Encode the liveness marker for `epoch`.
76pub fn encode_geo_liveness(epoch: u64) -> Vec<u8> {
77    epoch.to_be_bytes().to_vec()
78}
79
80/// Decode a persisted geo-index epoch.
81///
82/// An absent or malformed value decodes to `None`. Note that this is the RAW
83/// epoch read: callers wanting the TRUST decision must go through
84/// [`crate::Storage::geo_index_epoch`], which additionally requires the
85/// liveness marker.
86pub fn decode_geo_epoch(bytes: Option<&[u8]>) -> Option<u64> {
87    let bytes = bytes?;
88    if bytes.len() != GEO_EPOCH_VALUE_LEN {
89        return None;
90    }
91    Some(u64::from_be_bytes(bytes.try_into().expect("len checked")))
92}
93
94/// Decode a persisted liveness marker (the epoch it was stamped with).
95pub fn decode_geo_liveness(bytes: Option<&[u8]>) -> Option<u64> {
96    let bytes = bytes?;
97    if bytes.len() != GEO_LIVENESS_VALUE_LEN {
98        return None;
99    }
100    Some(u64::from_be_bytes(bytes.try_into().expect("len checked")))
101}
102
103/// Fixed prefix length of the S2 cell id in every geo-index key.
104pub const GEO_CELL_ID_LEN: usize = 8;
105
106/// Value length without the optional envelope (`op` + `visibility`).
107pub const GEO_VALUE_MIN_LEN: usize = STORAGE_VALUE_LEN;
108
109/// Value length with a CRS84 envelope (5 + 16 bytes).
110pub const GEO_VALUE_ENVELOPE_LEN: usize = STORAGE_VALUE_LEN + 16;
111
112/// Ingest-time envelope reject padding, in degrees (see the plan: a
113/// conservative reject must never drop a true candidate because `f64` →
114/// `f32` rounded the box inward; 4-byte lon/lat truncates near 1e-5°, so the
115/// compare-time epsilon is an order of magnitude larger).
116pub const GEO_AABB_PAD_DEGREES: f32 = 1e-4;
117
118/// CRS84 AABB of one geometry, as packed on a posting value.
119#[derive(Debug, Clone, Copy, PartialEq)]
120pub struct GeoEnvelope {
121    /// Minimum longitude (degrees, CRS84).
122    pub min_lon: f32,
123    /// Minimum latitude (degrees, CRS84).
124    pub min_lat: f32,
125    /// Maximum longitude (degrees, CRS84).
126    pub max_lon: f32,
127    /// Maximum latitude (degrees, CRS84).
128    pub max_lat: f32,
129}
130
131impl GeoEnvelope {
132    /// Encode as 16 big-endian f32 bytes (min_lon, min_lat, max_lon, max_lat).
133    pub fn encode(self) -> [u8; 16] {
134        let mut out = [0u8; 16];
135        out[0..4].copy_from_slice(&self.min_lon.to_be_bytes());
136        out[4..8].copy_from_slice(&self.min_lat.to_be_bytes());
137        out[8..12].copy_from_slice(&self.max_lon.to_be_bytes());
138        out[12..16].copy_from_slice(&self.max_lat.to_be_bytes());
139        out
140    }
141
142    /// Decode 16 envelope bytes.
143    pub fn decode(bytes: &[u8]) -> Result<Self, StorageError> {
144        if bytes.len() != 16 {
145            return Err(StorageError::Corrupt(format!(
146                "geo envelope must be 16 bytes, got {}",
147                bytes.len()
148            )));
149        }
150        Ok(Self {
151            min_lon: f32::from_be_bytes(bytes[0..4].try_into().expect("4-byte slice")),
152            min_lat: f32::from_be_bytes(bytes[4..8].try_into().expect("4-byte slice")),
153            max_lon: f32::from_be_bytes(bytes[8..12].try_into().expect("4-byte slice")),
154            max_lat: f32::from_be_bytes(bytes[12..16].try_into().expect("4-byte slice")),
155        })
156    }
157
158    /// Longitude span of the box.
159    pub fn lon_span(&self) -> f32 {
160        self.max_lon - self.min_lon
161    }
162}
163
164/// True when either side spans at least half the globe in longitude: raw
165/// min/max comparison is meaningless for antimeridian-crossing boxes, so the
166/// AABB reject must be skipped (conservative — the candidate survives to
167/// Relate).
168pub fn aabb_skip_for_lon_wrap(query: &GeoEnvelope, stored: &GeoEnvelope) -> bool {
169    query.lon_span() >= 180.0 || stored.lon_span() >= 180.0
170}
171
172/// Conservative AABB disjointness: `true` = this row can be skipped.
173///
174/// Both envelopes are expanded by [`GEO_AABB_PAD_DEGREES`] before the test —
175/// the stored side was truncated to f32 at write time and the query side may
176/// have been, so a raw compare could drop a candidate that truly overlaps by
177/// less than one f32 ULP of a box edge.
178pub fn aabb_disjoint_padded(query: &GeoEnvelope, stored: &GeoEnvelope) -> bool {
179    if aabb_skip_for_lon_wrap(query, stored) {
180        return false;
181    }
182    let eps = GEO_AABB_PAD_DEGREES;
183    query.min_lon - eps > stored.max_lon + eps
184        || stored.min_lon - eps > query.max_lon + eps
185        || query.min_lat - eps > stored.max_lat + eps
186        || stored.min_lat - eps > query.max_lat + eps
187}
188
189/// One staged geometry-index posting (compute-built; O applies verbatim).
190#[derive(Debug, Clone, PartialEq)]
191pub struct GeoIndexPut {
192    /// S2 cell id this posting files the term under (leaf for points).
193    pub cell_id: u64,
194    /// Encoded geo term bytes (`LiteralPoint` / `LiteralGeometry`).
195    pub term: Vec<u8>,
196    /// Cluster commit timestamp (same domain as the hexastore version).
197    pub commit_ts: CommitTs,
198    /// `Put` or `Delete`.
199    pub op: StorageOp,
200    /// Cell-level visibility label.
201    pub visibility: VisibilityLabel,
202    /// Optional CRS84 envelope. `None` = no AABB reject for this row.
203    pub envelope: Option<GeoEnvelope>,
204}
205
206impl GeoIndexPut {
207    /// Encode the versioned key: `cell ‖ term ‖ descending commit_ts`.
208    pub fn encode_key(&self) -> Vec<u8> {
209        let mut key = Vec::with_capacity(GEO_CELL_ID_LEN + self.term.len() + COMMIT_TS_LEN);
210        key.extend_from_slice(&self.cell_id.to_be_bytes());
211        key.extend_from_slice(&self.term);
212        key.extend_from_slice(&self.commit_ts.to_descending_be_bytes());
213        key
214    }
215
216    /// Encode the value: `op ‖ visibility [‖ envelope]`.
217    pub fn encode_value(&self) -> Vec<u8> {
218        let mut value = Vec::with_capacity(GEO_VALUE_ENVELOPE_LEN);
219        value.extend_from_slice(&encode_storage_value(self.op, self.visibility));
220        if let Some(envelope) = self.envelope {
221            value.extend_from_slice(&envelope.encode());
222        }
223        value
224    }
225
226    /// Build a posting from raw key/value bytes.
227    pub fn decode(key: &[u8], value: &[u8]) -> Result<Self, StorageError> {
228        if key.len() < GEO_CELL_ID_LEN + COMMIT_TS_LEN {
229            return Err(StorageError::Corrupt(format!(
230                "geo index key too short: {} bytes",
231                key.len()
232            )));
233        }
234        let cell_id = u64::from_be_bytes(key[0..GEO_CELL_ID_LEN].try_into().expect("8-byte slice"));
235        let (term_bytes, ts_bytes) =
236            key[GEO_CELL_ID_LEN..].split_at(key.len() - GEO_CELL_ID_LEN - COMMIT_TS_LEN);
237        let commit_ts =
238            CommitTs::from_descending_be_bytes(ts_bytes.try_into().expect("8-byte slice"));
239        let mut cursor = term_bytes;
240        let _ = cursor.read_term()?;
241        if !cursor.is_empty() {
242            return Err(StorageError::Corrupt(format!(
243                "{} trailing byte(s) after geo term",
244                cursor.len()
245            )));
246        }
247        if value.len() != GEO_VALUE_MIN_LEN && value.len() != GEO_VALUE_ENVELOPE_LEN {
248            return Err(StorageError::Corrupt(format!(
249                "geo index value must be {} or {} bytes, got {}",
250                GEO_VALUE_MIN_LEN,
251                GEO_VALUE_ENVELOPE_LEN,
252                value.len()
253            )));
254        }
255        let (op, visibility) = super::versioned::decode_storage_value(&value[..STORAGE_VALUE_LEN])?;
256        let envelope = if value.len() == GEO_VALUE_ENVELOPE_LEN {
257            Some(GeoEnvelope::decode(&value[STORAGE_VALUE_LEN..])?)
258        } else {
259            None
260        };
261        Ok(Self {
262            cell_id,
263            term: term_bytes.to_vec(),
264            commit_ts,
265            op,
266            visibility,
267            envelope,
268        })
269    }
270}
271
272/// Bucket-grid level of the geo cell-count histogram: every posting counts
273/// into its level-11 ancestor bucket (or, for postings coarser than 11, into
274/// the histogram's coarse side — see `GEO_HISTOGRAM_COARSE_FLOOR_LEVEL`).
275///
276/// Level 11 is 6 × 4^11 ≈ 25.2M cells (~20 km² average), small enough that
277/// per-bucket densities track real-world spatial skew, and its dense index
278/// (`face ‖ 22 Hilbert bits` = 25 bits) fits a `u32` key with room for
279/// levels up to 14. This is a FIXED grid, decoupled from the ingest
280/// coverer's `min_level` / `max_level`: postings map onto it by pure
281/// bit-twiddling on the u64 cell id — no S2 library, so the O partition's
282/// stats collector can run it (the partition stays S2-blind by contract).
283pub const GEO_HISTOGRAM_BUCKET_LEVEL: u8 = 11;
284
285/// Postings at a level below this floor go to the histogram's coarse side
286/// (keyed by their native cell id) instead of expanding into
287/// `4^(11 − level)` level-11 buckets. Level 9 bounds the fine expansion at
288/// 4^2 = 16 buckets per posting; coarser postings (level 8 and below) stay
289/// individual count-once entries. Level 8 was moved onto the coarse side
290/// (2026-10) because its 64-bucket expansion multiplied a small posting
291/// population into half the fine map's wire mass on real corpora (18.6k
292/// L8 postings = 1.19M of 2.37M incidences on bellendena-geo-10m), while
293/// the count-once rung prices such a posting as ONE candidate — the
294/// estimate's actual unit. One continent-scale polygon still cannot make a
295/// flush collector emit millions of increments: levels 0–7 were always
296/// coarse-side.
297pub const GEO_HISTOGRAM_COARSE_FLOOR_LEVEL: u8 = 9;
298
299/// S2 level of a u64 cell id: the trailing 1-bit sentinel sits at bit
300/// `60 − 2·level`. Returns `None` for a malformed id (sentinel at an odd bit
301/// position, above bit 60, or a face value ≥ 6 — S2 defines six faces, so
302/// bits 63–61 holding 6 or 7 is not a cell).
303pub fn geo_cell_level(cell_id: u64) -> Option<u8> {
304    if cell_id >> 61 > 5 {
305        return None;
306    }
307    let lsb = cell_id & cell_id.wrapping_neg();
308    let tz = lsb.trailing_zeros();
309    if tz > 60 || !tz.is_multiple_of(2) {
310        return None;
311    }
312    Some(((60 - tz) / 2) as u8)
313}
314
315/// Dense level-11 bucket index of `cell_id`'s L11 ancestor:
316/// `face ‖ 22 Hilbert bits` (25 bits). Defined for any cell at level ≥ 11.
317///
318/// Pure shifts/masks on the u64 layout (face in bits 63–61, two Hilbert bits
319/// per level, trailing 1-bit sentinel) — no S2 types, safe for the
320/// storage-partition process.
321#[must_use]
322pub fn geo_l11_bucket_index(cell_id: u64) -> u32 {
323    let face = (cell_id >> 61) as u32;
324    let digits = ((cell_id >> (60 - 2 * GEO_HISTOGRAM_BUCKET_LEVEL as u32 + 1)) & 0x3F_FFFF) as u32;
325    (face << 22) | digits
326}
327
328/// Level-8 parent bucket index of a level-11 dense index: dropping the low 6
329/// Hilbert bits (`22 − 16`) yields `face ‖ 16 Hilbert bits` (19 bits). The
330/// histogram's coarse remainder summary groups dropped L11 buckets by this
331/// parent so a wire-trimmed map still carries each region's total mass.
332#[must_use]
333pub fn geo_l8_parent_index(l11_index: u32) -> u32 {
334    l11_index >> 6
335}
336
337/// Inclusive level-11 dense-index range covered by `cell_id`.
338///
339/// Level ≥ 11: the single L11 ancestor bucket. Level < 11: the contiguous
340/// run of `4^(11 − level)` L11 descendants (contiguous because one S2 cell
341/// never spans a face and the dense index is Hilbert-ordered within a face).
342/// Returns `None` for a malformed cell id.
343#[must_use]
344pub fn geo_l11_bucket_range(cell_id: u64) -> Option<(u32, u32)> {
345    let level = geo_cell_level(cell_id)?;
346    let face = (cell_id >> 61) as u32;
347    if level >= GEO_HISTOGRAM_BUCKET_LEVEL {
348        let idx = geo_l11_bucket_index(cell_id);
349        return Some((idx, idx));
350    }
351    let digits = (cell_id >> (61 - 2 * level as u32)) & ((1u64 << (2 * level as u32)) - 1);
352    let base = (face << 22) | ((digits as u32) << (22 - 2 * level as u32));
353    let width = 1u32 << (2 * (GEO_HISTOGRAM_BUCKET_LEVEL - level) as u32);
354    Some((base, base + width - 1))
355}
356
357/// One merged, sorted cell-id interval to probe (compute-built from a
358/// covering: descendant `[range_min, range_max]` ranges ∪ exact ancestor ids).
359#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360pub struct GeoCellInterval {
361    /// Inclusive lower bound of the cell-id range.
362    pub min_cell_id: u64,
363    /// Inclusive upper bound of the cell-id range.
364    pub max_cell_id: u64,
365}
366
367impl GeoCellInterval {
368    /// Single-cell interval (an exact ancestor posting).
369    pub const fn exact(cell_id: u64) -> Self {
370        Self {
371            min_cell_id: cell_id,
372            max_cell_id: cell_id,
373        }
374    }
375}
376
377/// Outcome of one geo-index candidate decision.
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub enum GeoCandidateDecision {
380    /// Emit this term as a candidate (first visible Put under the snapshot).
381    Emit,
382    /// Skip (older version, Delete at the snapshot, or AABB-rejectable).
383    Skip,
384}
385
386/// State machine for one `GeoCandidateScan` stream: MVCC collapse per logical
387/// `(cell, term)` key **and** a DISTINCT seen-set over full term bytes.
388///
389/// The seen-set exists because one polygon files postings under up to
390/// `max_cells` cell ids that are NOT adjacent in cell-major order; DomainScan
391/// run-collapse does not apply, and duplicate `?g` rows would multiply the
392/// SPARQL bag on the join build side. The set keys on the **full term bytes**
393/// (wire encoding) — hashing only picks buckets, equality compares the whole
394/// term, so a hash collision can never drop a geometry. Never replace this
395/// with a `hash(term) as u64` identity or a Bloom filter.
396#[derive(Debug, Default)]
397pub struct GeoCandidateState {
398    /// Logical-key prefix of the last handled posting (`cell ‖ term`).
399    last_handled_logical: Vec<u8>,
400    /// Full term bytes already emitted on this stream.
401    seen: FxHashSet<Box<[u8]>>,
402}
403
404impl GeoCandidateState {
405    /// Decide one visible posting row for a stream at `snapshot`.
406    ///
407    /// `envelope` is the decoded optional value envelope (None = absent) and
408    /// `query_envelope` the constant geometry's CRS84 box — when both are
409    /// present and neither spans the antimeridian, a padded-disjoint row is
410    /// skipped before it can reach compute's Relate.
411    #[allow(clippy::too_many_arguments)]
412    pub fn consider_posting(
413        &mut self,
414        key: &[u8],
415        commit_ts: CommitTs,
416        op: StorageOp,
417        snapshot: SnapshotId,
418        envelope: Option<&GeoEnvelope>,
419        query_envelope: Option<&GeoEnvelope>,
420    ) -> Result<GeoCandidateDecision, StorageError> {
421        // MVCC: like hexastore versions, the first version of each logical
422        // key with commit_ts <= snapshot wins; anything after it is older.
423        let logical_len = key.len().saturating_sub(COMMIT_TS_LEN);
424        let logical = &key[..logical_len];
425        if self.last_handled_logical.as_slice() == logical {
426            return Ok(GeoCandidateDecision::Skip);
427        }
428        if commit_ts.0 > snapshot.0 {
429            return Ok(GeoCandidateDecision::Skip);
430        }
431        self.last_handled_logical.clear();
432        self.last_handled_logical.extend_from_slice(logical);
433        if op != StorageOp::Put {
434            return Ok(GeoCandidateDecision::Skip);
435        }
436        if let (Some(stored), Some(query)) = (envelope, query_envelope)
437            && aabb_disjoint_padded(query, stored)
438        {
439            return Ok(GeoCandidateDecision::Skip);
440        }
441        if self.seen.contains(logical[GEO_CELL_ID_LEN..].as_ref()) {
442            return Ok(GeoCandidateDecision::Skip);
443        }
444        self.seen
445            .insert(logical[GEO_CELL_ID_LEN..].to_vec().into_boxed_slice());
446        Ok(GeoCandidateDecision::Emit)
447    }
448}
449
450/// Raw (key, value) rows of one geo-index scan, in CF order.
451pub struct GeoIndexRow<'a> {
452    /// Key bytes (`cell ‖ term ‖ commit_ts_desc`).
453    pub key: &'a [u8],
454    /// Value bytes (`op ‖ visibility [‖ envelope]`).
455    pub value: &'a [u8],
456}
457
458impl GeoIndexRow<'_> {
459    /// Term bytes of this posting (between the cell id and the commit ts).
460    pub fn term_bytes(&self) -> Result<&[u8], StorageError> {
461        versioned_key_term_prefix_lossy(self.key).map(|logical| &logical[GEO_CELL_ID_LEN..])
462    }
463}
464
465/// Logical prefix of a geo key (drop the commit_ts suffix).
466fn versioned_key_term_prefix_lossy(key: &[u8]) -> Result<&[u8], StorageError> {
467    if key.len() < COMMIT_TS_LEN {
468        return Err(StorageError::Corrupt(format!(
469            "geo index key too short: {} bytes",
470            key.len()
471        )));
472    }
473    Ok(&key[..key.len() - COMMIT_TS_LEN])
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479    use pretty_assertions::assert_eq;
480
481    fn point_term(x: f64, y: f64) -> Vec<u8> {
482        super::super::binary::encode_term_bytes(&EncodedTerm::LiteralPoint {
483            x,
484            y,
485            crs: CrsId::Crs84,
486            geo_datatype: GeoDatatype::WktLiteral,
487        })
488    }
489
490    use super::super::encoded_term::{CrsId, EncodedTerm, GeoDatatype};
491
492    #[test]
493    fn envelope_round_trip() {
494        let env = GeoEnvelope {
495            min_lon: 152.9,
496            min_lat: -27.5,
497            max_lon: 153.1,
498            max_lat: -27.4,
499        };
500        assert_eq!(GeoEnvelope::decode(&env.encode()).unwrap(), env);
501        assert!(GeoEnvelope::decode(&[0u8; 15]).is_err());
502    }
503
504    #[test]
505    fn posting_round_trip_with_and_without_envelope() {
506        let term = point_term(153.02, -27.47);
507        let mut put = GeoIndexPut {
508            cell_id: 0x0102_0304_0506_0708,
509            term: term.clone(),
510            commit_ts: CommitTs(42),
511            op: StorageOp::Put,
512            visibility: VisibilityLabel::default(),
513            envelope: None,
514        };
515        let bare = GeoIndexPut::decode(&put.encode_key(), &put.encode_value()).unwrap();
516        assert_eq!(bare, put);
517        put.envelope = Some(GeoEnvelope {
518            min_lon: 153.0,
519            min_lat: -27.5,
520            max_lon: 153.05,
521            max_lat: -27.4,
522        });
523        let with_env = GeoIndexPut::decode(&put.encode_key(), &put.encode_value()).unwrap();
524        assert_eq!(with_env, put);
525    }
526
527    #[test]
528    fn aabb_padding_keeps_one_ulp_overlap() {
529        // A stored box whose true extent reaches 153.0000001 but whose f32
530        // truncation rounds to 153.0000000 vs a query starting exactly there:
531        // the raw compare would call this disjoint; the 1e-4° pad keeps the
532        // candidate alive for Relate.
533        let query = GeoEnvelope {
534            min_lon: 153.000_000_1,
535            min_lat: -27.5,
536            max_lon: 153.2,
537            max_lat: -27.4,
538        };
539        let stored = GeoEnvelope {
540            min_lon: 152.9,
541            min_lat: -27.5,
542            max_lon: 153.0,
543            max_lat: -27.4,
544        };
545        assert!(!aabb_disjoint_padded(&query, &stored));
546    }
547
548    #[test]
549    fn aabb_lon_wrap_skips_the_reject() {
550        let wide = GeoEnvelope {
551            min_lon: -170.0,
552            min_lat: -40.0,
553            max_lon: 170.0,
554            max_lat: -30.0,
555        };
556        let narrow = GeoEnvelope {
557            min_lon: -175.0,
558            min_lat: -35.0,
559            max_lon: -174.0,
560            max_lat: -34.0,
561        };
562        assert!(aabb_skip_for_lon_wrap(&wide, &narrow));
563        // 170 < 174 raw → would be disjoint without the span check.
564        assert!(!aabb_disjoint_padded(&wide, &narrow));
565    }
566
567    #[test]
568    fn candidate_state_mvcc_distinct_and_aabb() {
569        let term_a = point_term(153.0, -27.5);
570        let term_b = point_term(151.0, -33.8);
571        let cell = 0x0000_0000_0000_00ff_u64;
572        let put = |term: &[u8], ts: u64, op: StorageOp, envelope: Option<GeoEnvelope>| {
573            let posting = GeoIndexPut {
574                cell_id: cell,
575                term: term.to_vec(),
576                commit_ts: CommitTs(ts),
577                op,
578                visibility: VisibilityLabel::default(),
579                envelope,
580            };
581            let key = posting.encode_key();
582            let value = posting.encode_value();
583            (key, value)
584        };
585
586        let query_env = GeoEnvelope {
587            min_lon: 150.0,
588            min_lat: -35.0,
589            max_lon: 155.0,
590            max_lat: -25.0,
591        };
592        let disjoint_env = GeoEnvelope {
593            min_lon: 0.0,
594            min_lat: 0.0,
595            max_lon: 1.0,
596            max_lat: 1.0,
597        };
598
599        let mut state = GeoCandidateState::default();
600        let snapshot = SnapshotId(10);
601
602        // Future version: invisible.
603        let (k, v) = put(&term_a, 20, StorageOp::Put, None);
604        let posting = GeoIndexPut::decode(&k, &v).unwrap();
605        assert_eq!(
606            state
607                .consider_posting(
608                    &k,
609                    posting.commit_ts,
610                    posting.op,
611                    snapshot,
612                    posting.envelope.as_ref(),
613                    Some(&query_env),
614                )
615                .unwrap(),
616            GeoCandidateDecision::Skip
617        );
618        // Visible version: emit.
619        let (k, v) = put(&term_a, 5, StorageOp::Put, None);
620        let posting = GeoIndexPut::decode(&k, &v).unwrap();
621        assert_eq!(
622            state
623                .consider_posting(
624                    &k,
625                    posting.commit_ts,
626                    posting.op,
627                    snapshot,
628                    posting.envelope.as_ref(),
629                    Some(&query_env),
630                )
631                .unwrap(),
632            GeoCandidateDecision::Emit
633        );
634        // Older version of the same logical key: skipped by MVCC state.
635        let (k2, v2) = put(&term_a, 1, StorageOp::Put, None);
636        let posting2 = GeoIndexPut::decode(&k2, &v2).unwrap();
637        assert_eq!(
638            state
639                .consider_posting(
640                    &k2,
641                    posting2.commit_ts,
642                    posting2.op,
643                    snapshot,
644                    posting2.envelope.as_ref(),
645                    Some(&query_env),
646                )
647                .unwrap(),
648            GeoCandidateDecision::Skip
649        );
650        // A delete at the snapshot hides the logical key entirely.
651        let (kd, vd) = put(&term_b, 8, StorageOp::Delete, None);
652        let postingd = GeoIndexPut::decode(&kd, &vd).unwrap();
653        assert_eq!(
654            state
655                .consider_posting(
656                    &kd,
657                    postingd.commit_ts,
658                    postingd.op,
659                    snapshot,
660                    postingd.envelope.as_ref(),
661                    Some(&query_env),
662                )
663                .unwrap(),
664            GeoCandidateDecision::Skip
665        );
666        // AABB-disjoint visible row: skipped by the envelope reject.
667        let (k3, v3) = put(&term_b, 3, StorageOp::Put, Some(disjoint_env));
668        let posting3 = GeoIndexPut::decode(&k3, &v3).unwrap();
669        assert_eq!(
670            state
671                .consider_posting(
672                    &k3,
673                    posting3.commit_ts,
674                    posting3.op,
675                    snapshot,
676                    posting3.envelope.as_ref(),
677                    Some(&query_env),
678                )
679                .unwrap(),
680            GeoCandidateDecision::Skip
681        );
682        // Same term under a DIFFERENT cell: the seen-set (not MVCC) skips it.
683        let posting_dup = GeoIndexPut {
684            cell_id: cell + 1,
685            term: term_a.clone(),
686            commit_ts: CommitTs(4),
687            op: StorageOp::Put,
688            visibility: VisibilityLabel::default(),
689            envelope: None,
690        };
691        let kdup = posting_dup.encode_key();
692        assert_eq!(
693            state
694                .consider_posting(
695                    &kdup,
696                    posting_dup.commit_ts,
697                    posting_dup.op,
698                    snapshot,
699                    None,
700                    Some(&query_env),
701                )
702                .unwrap(),
703            GeoCandidateDecision::Skip,
704            "one geometry must stream once even under two covering cells"
705        );
706    }
707}