Skip to main content

waratah_geo/
rebuild.rs

1//! The geo index rebuild/upgrade CORE: one implementation, two shells.
2//!
3//! The cluster auto-rebuild (compute startup, streaming over RPC) and the
4//! offline `waratah geo rebuild-index` CLI share everything below their IO
5//! shells through this module: term classification, orphan upgrade
6//! planning (parse → validate → CRS84 transform → native term + blob
7//! payload), and per-term posting derivation (points leaf-post inline,
8//! geometries cover their CRS84 shape). The shells own transport only —
9//! term sources (head-scan streams vs in-process walks), blob sinks
10//! (clients vs `BlobStore`), replace sinks (RPC batches vs direct
11//! multi-axis batches) — so the two paths can never drift. Flagged zero-area
12//! spikes are reduced before covering; legacy unflagged spikes fail closed.
13
14use waratah_storage::{CommitTs, EncodedTerm, GeoIndexPut, StorageOp, StrHash, VisibilityLabel};
15
16use crate::validation::{reduce_tolerated_spikes, validate_geometry};
17
18/// The outcome of planning one orphaned typed literal's upgrade.
19#[derive(Debug, Clone, PartialEq)]
20pub enum UpgradeOutcome {
21    /// The literal parsed, validated, and transformed to CRS84: replace the
22    /// stored typed term with this native term (blob puts first when
23    /// non-empty).
24    ToNative {
25        /// The minted native term (`LiteralPoint` or `LiteralGeometry`).
26        new_term: EncodedTerm,
27        /// Content-addressed blob puts (empty for inline points).
28        blobs: Vec<(StrHash, Vec<u8>)>,
29    },
30    /// The literal is a geo datatype but NOT upgradeable (ill-formed WKT /
31    /// WKB, unsupported CRS, validation failure). A stored-geometry rebuild
32    /// must treat this as a hard error and leave the index untrusted rather
33    /// than stamp a complete-looking index that omits the literal.
34    Invalid {
35        /// Why the literal could not upgrade (parse / CRS / validation).
36        reason: String,
37    },
38}
39
40/// Plan the upgrade of one orphaned typed literal.
41///
42/// `lexical` is the typed term's raw value (inline `SmallString` or a
43/// registry resolve); `datatype_iri` is the geo datatype IRI the caller
44/// KNOWS from the discovery prefix (`geo:wktLiteral` / `geo:wkbLiteral`).
45/// The parse/validate/transform path is the same
46/// [`crate::encode::prepare_geometry_literal`] the write plugin uses at
47/// ingest — the upgrade mints exactly the term that ingest would have.
48pub fn upgrade_outcome(
49    old_typed: &EncodedTerm,
50    datatype_iri: &str,
51    lexical: &str,
52) -> UpgradeOutcome {
53    debug_assert!(
54        matches!(
55            old_typed,
56            EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
57        ),
58        "upgrade_outcome plans typed-literal orphans only"
59    );
60    let literal =
61        oxrdf::Literal::new_typed_literal(lexical, oxrdf::NamedNode::new_unchecked(datatype_iri));
62    match crate::encode::prepare_geometry_literal(&literal) {
63        Ok(prepared) if prepared.is_native() => UpgradeOutcome::ToNative {
64            new_term: prepared.term,
65            blobs: prepared.blobs,
66        },
67        Ok(_) => UpgradeOutcome::Invalid {
68            reason: "not a native-encodeable geometry (unsupported CRS or empty geometry)"
69                .to_owned(),
70        },
71        Err(error) => UpgradeOutcome::Invalid {
72            reason: error.to_string(),
73        },
74    }
75}
76
77/// Derive the index postings for one NATIVE geo term at `commit_ts`.
78///
79/// Points leaf-post from their inline CRS84 coordinates; geometries fetch
80/// nothing here — the caller supplies the canonical CRS84 EWKB payload
81/// (batched blob fetch on the cluster shell, direct `BlobStore` reads
82/// offline). Typed-literal terms are NOT posted by this core: orphans are
83/// upgraded to native terms first and the native term is posted (a typed
84/// term reaching here is a shell bug).
85pub fn postings_for_geo_term(
86    term: &EncodedTerm,
87    blob_payload: Option<&[u8]>,
88    commit_ts: CommitTs,
89) -> Result<Vec<GeoIndexPut>, String> {
90    let term_bytes = waratah_storage::encode_term_bytes(term);
91    let postings: Vec<GeoIndexPut> = match term {
92        EncodedTerm::LiteralPoint { x, y, .. } => {
93            vec![GeoIndexPut {
94                cell_id: crate::point_leaf_cell(*x, *y).id(),
95                term: term_bytes,
96                commit_ts,
97                op: StorageOp::Put,
98                visibility: VisibilityLabel::default(),
99                envelope: None,
100            }]
101        }
102        EncodedTerm::LiteralGeometry { .. } => {
103            let Some(payload) = blob_payload else {
104                return Err(format!(
105                    "geometry term {term:?} requires its CRS84 EWKB payload"
106                ));
107            };
108            let original = crate::geometry_from_crs84_ewkb(payload).map_err(|e| e.to_string())?;
109            let reduction = if validate_geometry(&original).is_ok() {
110                None
111            } else {
112                Some(reduce_tolerated_spikes(&original).map_err(|error| {
113                    format!("geometry term {term:?} cannot be rebuilt: {error}")
114                })?)
115            };
116            let removed_vertices = reduction
117                .as_ref()
118                .map_or(0, |reduction| reduction.removed_vertices);
119            match (term.requires_spike_reduction(), removed_vertices) {
120                (false, 0) => {}
121                (false, _) => {
122                    return Err(format!(
123                        "legacy geometry term {term:?} contains a tolerated zero-area spike but lacks the spike-reduction flag; re-ingest the geometry before rebuilding"
124                    ));
125                }
126                (true, 0) => {
127                    return Err(format!(
128                        "geometry term {term:?} carries the spike-reduction flag but its blob contains no reducible spike"
129                    ));
130                }
131                (true, _) => {}
132            }
133            let geometry = reduction
134                .as_ref()
135                .map_or(&original, |reduction| &reduction.geometry);
136            let covering = crate::geometry_covering(geometry);
137            let envelope = crate::geometry_envelope(geometry);
138            covering
139                .into_iter()
140                .map(|cell| {
141                    let cell_id = cell.id();
142                    GeoIndexPut {
143                        cell_id,
144                        term: term_bytes.clone(),
145                        commit_ts,
146                        op: StorageOp::Put,
147                        visibility: VisibilityLabel::default(),
148                        envelope: envelope.filter(|env| crate::should_store_envelope(cell_id, env)),
149                    }
150                })
151                .collect()
152        }
153        other => {
154            return Err(format!("unexpected geo term shape: {other:?}"));
155        }
156    };
157    Ok(postings)
158}
159
160/// Report totals one shell accumulates over a rebuild/upgrade run.
161#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
162pub struct RebuildReport {
163    /// Native terms (`LiteralPoint` / `LiteralGeometry`) re-covered.
164    pub native_recovered: u64,
165    /// Orphaned typed literals upgraded to native terms (replaced across
166    /// all axes).
167    pub orphans_upgraded: u64,
168    /// Postings written.
169    pub postings: u64,
170}
171
172impl RebuildReport {
173    /// The operator-facing summary line.
174    pub fn summary(&self) -> String {
175        format!(
176            "{} native term(s) re-covered, {} orphan(s) upgraded, {} posting(s) written",
177            self.native_recovered, self.orphans_upgraded, self.postings
178        )
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use oxrdf::{Literal, NamedNode};
186    use waratah_storage::EncodedTerm;
187
188    fn outcome(wkt: &str) -> UpgradeOutcome {
189        let literal =
190            Literal::new_typed_literal(wkt, NamedNode::new_unchecked(crate::GEO_WKT_LITERAL));
191        upgrade_outcome(&EncodedTerm::from(&literal), crate::GEO_WKT_LITERAL, wkt)
192    }
193
194    fn spike_prepared() -> crate::encode::PreparedGeometryLiteral {
195        let literal = oxrdf::Literal::new_typed_literal(
196            "POLYGON((154.000000 -28.797429, 154.000000 -27.760501, \
197             153.834707 -27.678942, 153.018589 -27.558772, \
198             152.746796 -28.041757, 152.170156 -29.032803, \
199             153.097669 -29.526447, 154.000000 -29.270522, \
200             154.000000 -29.550790, 154.000000 -28.797429))",
201            NamedNode::new_unchecked(crate::GEO_WKT_LITERAL),
202        );
203        crate::encode::prepare_geometry_literal(&literal).unwrap()
204    }
205
206    #[test]
207    fn flagged_spike_rebuild_matches_ingest_postings() {
208        let prepared = spike_prepared();
209        let rebuilt =
210            postings_for_geo_term(&prepared.term, Some(&prepared.blobs[0].1), CommitTs(7)).unwrap();
211        let expected: Vec<_> = prepared.postings.iter().map(|put| put.cell_id).collect();
212        let actual: Vec<_> = rebuilt.iter().map(|put| put.cell_id).collect();
213        assert_eq!(actual, expected);
214    }
215
216    #[test]
217    fn legacy_unflagged_spike_is_rejected_by_rebuild() {
218        let prepared = spike_prepared();
219        let waratah_storage::EncodedTerm::LiteralGeometry {
220            geom_kind,
221            crs,
222            geo_datatype,
223            blob_id,
224            ..
225        } = prepared.term
226        else {
227            panic!("expected LiteralGeometry");
228        };
229        let legacy = waratah_storage::EncodedTerm::LiteralGeometry {
230            geom_kind,
231            crs,
232            geo_datatype,
233            blob_id,
234            requires_spike_reduction: false,
235        };
236        let error =
237            postings_for_geo_term(&legacy, Some(&prepared.blobs[0].1), CommitTs(7)).unwrap_err();
238        assert!(error.contains("legacy geometry term"), "{error}");
239        assert!(error.contains("re-ingest the geometry"), "{error}");
240    }
241
242    #[test]
243    fn tolerated_member_overlap_upgrades_to_a_native_term() {
244        assert!(matches!(
245            outcome(
246                "MULTIPOLYGON(((0 0, 1 0, 1 1, 0 1, 0 0)), \
247                 ((0.999999999 0, 1.999999999 0, 1.999999999 1, 0.999999999 1, 0.999999999 0)))"
248            ),
249            UpgradeOutcome::ToNative { .. }
250        ));
251    }
252
253    #[test]
254    fn untolerable_validation_error_is_reported() {
255        let UpgradeOutcome::Invalid { reason } = outcome("POLYGON((0 0, 2 2, 2 0, 0 2, 0 0))")
256        else {
257            panic!("expected an invalid orphan");
258        };
259        assert!(reason.contains("self-intersection"), "{reason}");
260    }
261}