1use std::collections::HashMap;
13use std::sync::Arc;
14
15use waratah_compute::ComputeError;
16use waratah_compute::{
17 BlobStoreClient, BroadcastFilter, HexastoreAxisHeadStats, HexastoreGeo, HexastoreInsert,
18 HexastoreScan, StringResolve,
19};
20use waratah_proto::PatternSlot;
21use waratah_storage::{
22 EncodedQuad, EncodedTerm, IndexPermutation, PartitionAxis, SnapshotId, StrHash,
23};
24
25use crate::geo::format_orphan_error;
26
27const HEAD_PAGE: u64 = 5_000;
29const TRIPLE_CHUNK: usize = 5_000;
31const REPLACE_CHUNK: usize = 8_000;
34
35const TYPE_LITERAL_POINT: u8 = 26;
38const TYPE_LITERAL_GEOMETRY: u8 = 27;
39const TYPE_SMALL_TYPED_LITERAL: u8 = 24;
40const TYPE_BIG_TYPED_LITERAL: u8 = 25;
41
42pub fn geo_head_prefixes() -> Vec<Vec<u8>> {
51 let wkt = StrHash::new(waratah_geo::GEO_WKT_LITERAL).to_be_bytes();
52 let wkb = StrHash::new(waratah_geo::GEO_WKB_LITERAL).to_be_bytes();
53 let mut out = Vec::new();
54 for type_byte in [TYPE_LITERAL_POINT, TYPE_LITERAL_GEOMETRY] {
56 out.push(vec![type_byte]);
57 }
58 for hash in [wkt, wkb] {
61 let mut small = vec![TYPE_SMALL_TYPED_LITERAL];
62 small.extend_from_slice(&hash);
63 let mut big = vec![TYPE_BIG_TYPED_LITERAL];
64 big.extend_from_slice(&hash);
65 out.push(small);
66 out.push(big);
67 }
68 out
69}
70
71pub async fn drive_geo_upgrade<H, R>(
77 hexastore: &H,
78 registry: &R,
79) -> Result<Option<waratah_geo::RebuildReport>, ComputeError>
80where
81 H: HexastoreScan + HexastoreGeo + HexastoreInsert + HexastoreAxisHeadStats + Sync,
82 R: StringResolve + BlobStoreClient + Sync,
83{
84 let (started, _already, _lease_ts) = hexastore
100 .rebuild_geo_index()
101 .await
102 .map_err(status_to_compute)?;
103 if !started {
104 return Ok(None);
105 }
106 let mut report = waratah_geo::RebuildReport::default();
107 let renew = || async {
108 hexastore
109 .renew_geo_rebuild_lease()
110 .await
111 .map_err(status_to_compute)
112 };
113
114 let prefixes = geo_head_prefixes();
122 let mut max_seen: Option<u64> = None;
123 let mut native: Vec<EncodedTerm> = Vec::new();
124 let mut orphans: Vec<EncodedTerm> = Vec::new();
125 let geo_wkt = StrHash::new(waratah_geo::GEO_WKT_LITERAL);
126 let geo_wkb = StrHash::new(waratah_geo::GEO_WKB_LITERAL);
127 for permutation in [IndexPermutation::Opsg, IndexPermutation::Tsg] {
128 let walked_max = hexastore
129 .axis_head_max_commit_ts(permutation, &prefixes)
130 .await
131 .map_err(status_to_compute)?;
132 max_seen = max_seen.max(Some(walked_max));
133 let mut cursor: Option<EncodedTerm> = None;
134 loop {
135 let terms = hexastore
136 .scan_axis_head(
137 permutation,
138 SnapshotId::latest(),
139 HEAD_PAGE,
140 cursor.as_ref(),
141 None,
142 None,
143 false,
144 &prefixes,
145 )
146 .await
147 .map_err(status_to_compute)?;
148 if terms.is_empty() {
149 break;
150 }
151 for term in &terms {
152 match term {
153 EncodedTerm::LiteralPoint { .. } | EncodedTerm::LiteralGeometry { .. } => {
154 native.push(term.clone())
155 }
156 EncodedTerm::SmallTypedLiteral { datatype_id, .. }
157 | EncodedTerm::BigTypedLiteral { datatype_id, .. }
158 if *datatype_id == geo_wkt || *datatype_id == geo_wkb =>
159 {
160 orphans.push(term.clone())
161 }
162 _ => {}
163 }
164 }
165 cursor = terms.last().cloned();
166 renew().await?;
167 }
168 }
169 let upgrade_ts = waratah_storage::CommitTs(max_seen.map_or(0, |m| m + 1));
173 let dedup_terms = |mut terms: Vec<EncodedTerm>| {
176 let mut seen: std::collections::HashSet<
177 StrHash,
178 waratah_storage::StrHashIdentityBuildHasher,
179 > = std::collections::HashSet::with_hasher(waratah_storage::StrHashIdentityBuildHasher);
180 terms.retain(|term| {
181 seen.insert(waratah_storage::StrHash::from_bytes(
182 &waratah_storage::encode_term_bytes(term),
183 ))
184 });
185 terms
186 };
187 native = dedup_terms(native);
188 orphans = dedup_terms(orphans);
189 report.native_recovered = native.len() as u64;
191
192 let unbound = waratah_storage::EncodedTriplePattern {
197 subject: None,
198 predicate: None,
199 object: None,
200 graph_name: None,
201 };
202 let mut replace_pairs: Vec<waratah_storage::ReplacePair> = Vec::new();
203 type OrphanPlan = (EncodedTerm, Vec<(StrHash, Vec<u8>)>);
205 let mut planned: HashMap<EncodedTerm, OrphanPlan> = HashMap::new();
206 for chunk in orphans.chunks(TRIPLE_CHUNK) {
207 let filter = BroadcastFilter {
208 slot: PatternSlot::Object,
209 terms: Arc::from(chunk.to_vec().into_boxed_slice()),
210 };
211 let mut pages = hexastore
212 .scan_pattern_stream(
213 PartitionAxis::O,
214 &unbound,
215 SnapshotId::latest(),
216 0,
217 Some(IndexPermutation::Opsg),
218 Some(&filter),
219 None,
220 None,
221 false,
222 waratah_storage::IriOnlyMask::default(),
223 waratah_proto::OMIT_NONE,
226 false,
229 )
230 .await
231 .map_err(status_to_compute)?;
232 while let Some(page) = tokio_stream::StreamExt::next(&mut pages).await {
233 for row in page.map_err(status_to_compute)?.rows {
234 let orphan = row.object.clone();
235 let plan = match planned.get(&orphan) {
236 Some(plan) => plan.clone(),
237 None => {
238 let plan = plan_orphan(registry, &row, geo_wkt, geo_wkb).await?;
239 planned.insert(orphan.clone(), plan.clone());
240 plan
241 }
242 };
243 let (new_term, blobs) = plan;
244 for (blob_id, payload) in blobs {
245 let payload = Arc::from(payload);
248 registry
249 .put_blobs(std::slice::from_ref(&(blob_id, Arc::clone(&payload))))
250 .await
251 .map_err(status_to_compute)?;
252 }
253 replace_pairs.push(waratah_storage::ReplacePair {
254 subject: row.subject.clone(),
255 predicate: row.predicate.clone(),
256 graph_name: row.graph_name.clone(),
257 old_object: orphan,
258 new_object: new_term,
259 });
260 }
261 }
262 flush_replaces(hexastore, &mut replace_pairs, upgrade_ts).await?;
263 renew().await?;
264 }
265 flush_replaces(hexastore, &mut replace_pairs, upgrade_ts).await?;
266
267 report.orphans_upgraded = planned.len() as u64;
270
271 let mut cover: Vec<EncodedTerm> = native;
275 for plan in planned.values() {
276 cover.push(plan.0.clone());
277 }
278 cover = dedup_terms(cover);
279 let geometry_blob_ids: Vec<StrHash> = cover
280 .iter()
281 .filter_map(|term| match term {
282 EncodedTerm::LiteralGeometry { blob_id, .. } => Some(*blob_id),
283 _ => None,
284 })
285 .collect();
286 let mut payloads: HashMap<StrHash, Vec<u8>> = HashMap::new();
287 for chunk in geometry_blob_ids.chunks(512) {
288 let fetched = fetch_blobs(registry, chunk).await?;
289 for (id, payload) in fetched {
290 payloads.insert(id, payload);
291 }
292 renew().await?;
293 }
294 for term in &cover {
295 let blob_payload = match term {
296 EncodedTerm::LiteralGeometry { blob_id, .. } => Some(
297 payloads
298 .get(blob_id)
299 .ok_or_else(|| {
300 ComputeError::UnsupportedSparql(format!(
301 "geo upgrade: blob {blob_id:?} missing during cover pass"
302 ))
303 })?
304 .as_slice(),
305 ),
306 _ => None,
307 };
308 let postings = waratah_geo::postings_for_geo_term(term, blob_payload, upgrade_ts)
309 .map_err(ComputeError::UnsupportedSparql)?;
310 report.postings += postings.len() as u64;
311 hexastore
313 .put_geo_index(&postings)
314 .await
315 .map_err(status_to_compute)?;
316 renew().await?;
317 }
318
319 let _epoch = hexastore
324 .finish_geo_index_rebuild()
325 .await
326 .map_err(status_to_compute)?;
327 Ok(Some(report))
328}
329
330async fn flush_replaces<H: HexastoreInsert + ?Sized>(
332 hexastore: &H,
333 pairs: &mut Vec<waratah_storage::ReplacePair>,
334 upgrade_ts: waratah_storage::CommitTs,
335) -> Result<(), ComputeError> {
336 while !pairs.is_empty() {
337 let take = pairs.len().min(REPLACE_CHUNK);
338 let batch: Vec<_> = pairs.drain(..take).collect();
339 hexastore
340 .replace_quads(&batch, upgrade_ts)
341 .await
342 .map_err(status_to_compute)?;
343 }
344 Ok(())
345}
346
347async fn plan_orphan<R: StringResolve + ?Sized>(
353 registry: &R,
354 row: &EncodedQuad,
355 geo_wkt: StrHash,
356 _geo_wkb: StrHash,
357) -> Result<(EncodedTerm, Vec<(StrHash, Vec<u8>)>), ComputeError> {
358 let orphan = &row.object;
359 let (datatype_iri, inline, value_id) = match orphan {
360 EncodedTerm::SmallTypedLiteral { datatype_id, value } => {
361 let iri = if *datatype_id == geo_wkt {
362 waratah_geo::GEO_WKT_LITERAL
363 } else {
364 waratah_geo::GEO_WKB_LITERAL
365 };
366 (iri, Some(value.as_str().to_owned()), None)
367 }
368 EncodedTerm::BigTypedLiteral {
369 datatype_id,
370 value_id,
371 } => {
372 let iri = if *datatype_id == geo_wkt {
373 waratah_geo::GEO_WKT_LITERAL
374 } else {
375 waratah_geo::GEO_WKB_LITERAL
376 };
377 (iri, None, Some(*value_id))
378 }
379 _ => {
380 return Err(ComputeError::Internal(format!(
381 "geo upgrade: unexpected orphan term shape {orphan:?}"
382 )));
383 }
384 };
385 let lexical = match inline {
386 Some(lexical) => lexical,
387 None => {
388 let resolved = registry
389 .resolve_strings(&[value_id.expect("big literal carries value_id")])
390 .await
391 .map_err(status_to_compute)?;
392 resolved.into_iter().flatten().next().ok_or_else(|| {
393 ComputeError::UnsupportedSparql(format!(
394 "geo upgrade: registry miss for orphan literal value hash {value_id:?}"
395 ))
396 })?
397 }
398 };
399 match waratah_geo::upgrade_outcome(orphan, datatype_iri, &lexical) {
400 waratah_geo::UpgradeOutcome::ToNative { new_term, blobs } => Ok((new_term, blobs)),
401 waratah_geo::UpgradeOutcome::Invalid { reason } => {
402 let hashes: Vec<StrHash> = [&row.subject, &row.predicate, &row.graph_name]
403 .into_iter()
404 .filter_map(|term| match term {
405 EncodedTerm::NamedNode { iri_id } => Some(*iri_id),
406 EncodedTerm::BigBlankNode { id_id } => Some(*id_id),
407 _ => None,
408 })
409 .collect();
410 let resolved = if hashes.is_empty() {
411 HashMap::new()
412 } else {
413 let values = registry
414 .resolve_strings(&hashes)
415 .await
416 .map_err(status_to_compute)?;
417 hashes
418 .into_iter()
419 .zip(values)
420 .filter_map(|(hash, value)| value.map(|value| (hash, value)))
421 .collect()
422 };
423 Err(ComputeError::InvalidLiteral(format!(
424 "geo upgrade: orphan cannot be indexed: {}",
425 format_orphan_error(row, &lexical, &reason, |hash| {
426 resolved.get(hash).cloned()
427 })
428 )))
429 }
430 }
431}
432
433async fn fetch_blobs<R: BlobStoreClient + ?Sized>(
436 registry: &R,
437 ids: &[StrHash],
438) -> Result<Vec<(StrHash, Vec<u8>)>, ComputeError> {
439 let fetched = registry.get_blobs(ids).await.map_err(status_to_compute)?;
440 Ok(ids
441 .iter()
442 .cloned()
443 .zip(fetched)
444 .filter_map(|(id, payload)| payload.map(|payload| (id, payload)))
445 .collect())
446}
447
448fn status_to_compute(status: tonic::Status) -> ComputeError {
449 ComputeError::UnsupportedSparql(format!("geo upgrade RPC failed: {status}"))
450}
451
452#[cfg(test)]
453mod tests {
454 use super::*;
455
456 struct MockRegistry;
457
458 impl StringResolve for MockRegistry {
459 async fn resolve_strings(
460 &self,
461 hashes: &[StrHash],
462 ) -> Result<Vec<Option<String>>, tonic::Status> {
463 Ok(hashes
464 .iter()
465 .map(|hash| {
466 if *hash == StrHash::new("http://ex/s") {
467 Some("http://ex/s".to_owned())
468 } else if *hash == StrHash::new("http://ex/p") {
469 Some("http://ex/p".to_owned())
470 } else {
471 None
472 }
473 })
474 .collect())
475 }
476 }
477
478 #[tokio::test]
479 async fn orphan_error_identifies_the_online_referencing_row() {
480 let subject = waratah_storage::NamedNode::new_unchecked("http://ex/s");
481 let predicate = waratah_storage::NamedNode::new_unchecked("http://ex/p");
482 let literal = oxrdf::Literal::new_typed_literal(
483 "POINT EMPTY",
484 oxrdf::NamedNode::new_unchecked(waratah_geo::GEO_WKT_LITERAL),
485 );
486 let row = EncodedQuad::new(
487 EncodedTerm::from(&subject),
488 EncodedTerm::from(&predicate),
489 EncodedTerm::from(&literal),
490 EncodedTerm::DefaultGraph,
491 );
492 let error = plan_orphan(
493 &MockRegistry,
494 &row,
495 StrHash::new(waratah_geo::GEO_WKT_LITERAL),
496 StrHash::new(waratah_geo::GEO_WKB_LITERAL),
497 )
498 .await
499 .unwrap_err();
500 assert!(matches!(&error, ComputeError::InvalidLiteral(_)));
501 let message = error.to_string();
502 assert!(message.contains("subject=<http://ex/s>"), "{message}");
503 assert!(message.contains("predicate=<http://ex/p>"), "{message}");
504 assert!(message.contains("graph=DefaultGraph"), "{message}");
505 assert!(message.contains("POINT EMPTY"), "{message}");
506 }
507
508 #[test]
515 fn discovery_prefixes_survive_normalization() {
516 let prefixes = geo_head_prefixes();
517 assert_eq!(
518 prefixes.len(),
519 6,
520 "two native type bytes + four datatype-named forms"
521 );
522 for a in &prefixes {
523 for b in &prefixes {
524 if a.len() < b.len() {
525 assert!(
526 !b.starts_with(a),
527 "prefix {b:?} is subsumed by {a:?} and would never reach the scan"
528 );
529 }
530 }
531 }
532 let mut bare: Vec<u8> = prefixes
534 .iter()
535 .filter_map(|p| (p.len() == 1).then_some(p[0]))
536 .collect();
537 bare.sort_unstable();
538 assert_eq!(bare, vec![TYPE_LITERAL_POINT, TYPE_LITERAL_GEOMETRY]);
539 }
540}