Skip to main content

waratah/
geo_upgrade.rs

1//! The cluster geo index upgrade/rebuild driver (the RPC shell of
2//! `waratah_geo::rebuild`'s core): takes the partition lease, streams geo
3//! terms via prefix-filtered head scans, upgrades orphaned typed literals
4//! (`ReplaceQuads` across all three axes at a swap ts derived from the
5//! walked data — 1 + the max ts under the discovery prefixes), covers the
6//! now-homogeneously-native store, and finishes — refreshing the lease per
7//! batch so a slow walk is never taken over. Startup blocks on this; a
8//! failure leaves the epoch unstamped (the untrusted gate keeps queries
9//! correct via the residual path), and a crashed driver's stale lease is
10//! force-takeable by the next attempt.
11
12use 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
27/// Head-scan page size (terms per RPC; the walk resumes per term).
28const HEAD_PAGE: u64 = 5_000;
29/// Orphan triples fetched per filtered-scan drain.
30const TRIPLE_CHUNK: usize = 5_000;
31/// Replace pairs per `ReplaceQuads` call (the client byte-frames anyway;
32/// this keeps one call's pair count bounded for log readability).
33const REPLACE_CHUNK: usize = 8_000;
34
35// Encoded-term type bytes (declared in waratah_storage::encode::binary; the
36// values are part of the on-disk format contract).
37const 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
42/// The six discovery prefixes: native geo term type bytes plus the orphaned
43/// typed-literal forms (type byte + the geo datatype-IRI hash, which sits at
44/// a fixed offset in both typed-literal encodings). The typed-literal type
45/// bytes are NEVER listed bare: the scan's prefix normalization
46/// (`prepare_head_prefixes`) drops a longer prefix subsumed by a kept
47/// shorter one, so a bare `[24]` / `[25]` would swallow the four
48/// datatype-named prefixes below and widen the head walk to every typed
49/// literal in the store.
50pub 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    // Native geo terms live at their own type bytes: one bare byte each.
55    for type_byte in [TYPE_LITERAL_POINT, TYPE_LITERAL_GEOMETRY] {
56        out.push(vec![type_byte]);
57    }
58    // Orphaned typed literals are narrowed by datatype hash; a bare
59    // typed-literal type byte here would subsume these four entries.
60    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
71/// Drive one geo index rebuild/upgrade against a running cluster.
72///
73/// Returns `Ok(None)` when another compute held a fresh lease (the caller
74/// polls `Describe` instead), `Ok(Some(report))` when this call completed
75/// the rebuild (epoch stamped).
76pub 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    // TODO(rebuild): writes are not locked during the upgrade. Current
85    //    correctness relies on plugin-on writers never minting typed forms
86    //    (orphan chains are frozen during the walk; see ARCH.md §7
87    //    "Two-stage swap preconditions"). A mixed deployment with a
88    //    plugin-off writer voids that guarantee and can invalidate the
89    //    derived swap ts. Implement a cluster write lock held for the
90    //    duration of the rebuild: partition-enforced (compute is stateless),
91    //    exempting the lease-holder's own ReplaceQuads / blob puts, and
92    //    expiring with the rebuild lease so a crashed driver cannot wedge
93    //    ingestion.
94    // 0. Take the lease (wipes the CF). The lease ts — the partition's
95    //    max-commit_ts counter — is NOT the swap ts: a freshly opened process
96    //    holds 0 regardless of what earlier processes wrote, and a swap at 0
97    //    sorts below the old rows' Puts so the duplicates survive MVCC.
98    //    Stage 1 below derives the swap ts from the walked data instead.
99    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    // 1. Discover terms AND the swap bound: prefix-filtered head scans over
115    //    both O permutations (visible-row emission = per-quad OR-liveness),
116    //    plus the max ts on disk under the same prefixes. The swap must
117    //    dominate the newest version of every upgradeable row it deletes,
118    //    and the walked data is the only authority for that bound — rows on
119    //    S/P carry the same ts as their O twins, so the O-walked max bounds
120    //    the whole swap.
121    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    // The swap ts: one past the newest walked version (0 when the store holds
170    // no upgradeable literals — nothing to swap, and `finish` floors the
171    // epoch at the previously stamped one).
172    let upgrade_ts = waratah_storage::CommitTs(max_seen.map_or(0, |m| m + 1));
173    // Dedup by encoded bytes (EncodedTerm is Hash+Eq; sort by bytes for a
174    // deterministic cover order).
175    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    // Every native term discovered is re-covered in step 4's cover pass.
190    report.native_recovered = native.len() as u64;
191
192    // 2. Upgrade orphaned typed literals: discover their referencing
193    //    triples (object allow-list filtered scans on the O axis), resolve
194    //    the lexical (string registry; ONE plan per distinct orphan term),
195    //    blob puts first, then `ReplaceQuads` batches at the upgrade ts.
196    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    /// One planned orphan upgrade: the minted native term plus its blob puts.
204    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                // Batch upgrade walk: no cursor and no consumer for omitted
224                // slots, so ask for the full payload.
225                waratah_proto::OMIT_NONE,
226                // Drain-to-EOF at limit 0: the flag's look-ahead never
227                // runs on a drain.
228                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                    // Blob puts precede the replaces (payload exists before
246                    // rows referencing it become visible).
247                    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 totals: one entry per DISTINCT orphan term (rows sharing an
268    // orphan collapse into the `planned` cache above).
269    report.orphans_upgraded = planned.len() as u64;
270
271    // 3. Cover pass over the now-homogeneously-native store: the original
272    //    natives plus every upgraded term's new encoding (their blobs were
273    //    put in step 3; geometries' payloads are fetched here, batched).
274    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        // Byte-framed by the client; renew per frame-batch.
312        hexastore
313            .put_geo_index(&postings)
314            .await
315            .map_err(status_to_compute)?;
316        renew().await?;
317    }
318
319    // 4. Finish: stamp the epoch — the partition floors it at the previously
320    //    stamped number and at the counter (raised to the swap ts by the
321    //    replaces and to the coverage ts by the posting writes) — and
322    //    release the lease.
323    let _epoch = hexastore
324        .finish_geo_index_rebuild()
325        .await
326        .map_err(status_to_compute)?;
327    Ok(Some(report))
328}
329
330/// Flush replace pairs in bounded batches at the upgrade ts.
331async 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
347/// Plan one orphan's upgrade: resolve its lexical (inline for
348/// `SmallTypedLiteral`, the string registry for `BigTypedLiteral`), then
349/// parse/validate/transform through the shared ingest path. Any failure is a
350/// hard rebuild error: stamping an epoch after skipping the orphan would make
351/// the trusted candidate index incomplete.
352async 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
433/// Fetch blob payloads through the registry client (batched), returning
434/// `(id, payload)` pairs for the hits.
435async 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    /// The discovery prefixes must be subsumption-free: no prefix may be a
509    /// strict extension of another, or the scan's normalization
510    /// (`prepare_head_prefixes`) silently drops the longer one and its rows
511    /// are served by the shorter — a bare typed-literal type byte
512    /// (`[24]` / `[25]`) used to subsume all four datatype-named prefixes,
513    /// widening the head walk to every typed literal in the store.
514    #[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        // The bare bytes are exactly the native geo terms' type bytes.
533        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}