Skip to main content

waratah/
standalone.rs

1//! In-process S/P/O + registry adapters for the `waratah standalone` command.
2//!
3//! `waratah start` spawns partition/registry binaries and lets
4//! [`ComputeNode::connect`](waratah_compute::ComputeNode::connect) dial them.
5//! `waratah standalone` opens the same [`PartitionService`] /
6//! [`RegistryService`] types in this process and implements compute's client
7//! traits with direct method calls — no child processes, no gRPC, no proto
8//! round-trip.
9//!
10//! Every call runs on `spawn_blocking`: the storage methods are synchronous
11//! RocksDB walks with no await points, so running them inline would block an
12//! async runtime worker and make concurrent scans degenerate to sequential.
13//! On the blocking pool they overlap exactly like the gRPC deployment.
14//!
15//! Data-dir layout matches spawn and `import --offline`: `{data_dir}/{repository}/s|p|o`
16//! and `{data_dir}/{repository}/registry` (repository is `main`).
17
18use std::collections::BTreeMap;
19use std::path::Path;
20use std::sync::Arc;
21
22use tokio_stream::wrappers::ReceiverStream;
23use tonic::Status;
24use waratah_compute::{
25    BroadcastFilter, ComputeNode, GraphFilter, HexastoreAdmin, HexastoreAxisHeadStats,
26    HexastoreCatalog, HexastoreCompact, HexastoreDescribe, HexastoreFlush, HexastoreInsert,
27    HexastoreScan, HexastoreStats, LsmMetricsView, QuadPageStream, RegistryAdmin, RegistryDescribe,
28    RetryPolicy, StringRegister, StringRegistryCompact, StringRegistryFlush, StringResolve,
29    TermPageStream,
30};
31use waratah_partition::{
32    PartitionError, PartitionService, RocksDbOpenOptions, SCAN_STREAM_FRAME_ROWS,
33};
34use waratah_proto::{
35    PatternSlot, QuadVersion, axis_from_proto, blocking_join_error, pb, quad_from_proto_omitting,
36};
37use waratah_registry::{DEFAULT_SHARD_COUNT, RegistryService};
38use waratah_stats::to_bytes;
39use waratah_storage::{
40    AxisHeadCountHit, CommitTs, DomainCountMode, DomainScanCountHit, DomainScanHit, EncodedQuad,
41    EncodedTerm, EncodedTriplePattern, IndexPermutation, IriOnlyMask, MAIN_REPOSITORY_ID,
42    PartitionAxis, ReplacePair, RocksDbTuning, SlotComparison, SnapshotId, StrHash,
43    hexastore_data_dir, registry_data_dir,
44};
45
46use crate::dev::{Backend, DevOptions};
47use crate::error::DevError;
48
49/// Virtual nodes per axis — same ring density as [`ComputeNode::connect`].
50const ROUTER_VNODES: u32 = 16;
51
52/// Open S/P/O + registry in this process and wrap them as a [`ComputeNode`].
53/// Also returns the startup cache-warm tracker: `/health` gates on it until
54/// every walk finishes (or the max wait), so clients that wait on `/health`
55/// do not race a still-running warm. SPARQL routes themselves are not gated.
56pub fn open_compute(
57    options: &DevOptions,
58) -> Result<
59    (
60        ComputeNode<LocalHexastoreClients, LocalRegistryClients>,
61        std::sync::Arc<waratah_storage::WarmState>,
62    ),
63    DevError,
64> {
65    let warm = waratah_storage::WarmState::empty();
66    let hexastore = LocalHexastoreClients::open(&options.backend, options.debug, &warm)?;
67    let registry = LocalRegistryClients::open(&options.backend, options.debug, &warm)?;
68    let router = options.config.router(ROUTER_VNODES)?;
69    let compute =
70        ComputeNode::from_clients(hexastore, registry, router, RetryPolicy::default_dev())
71            .with_cluster_config(options.config.clone())
72            .with_standalone(true);
73    Ok((compute, warm))
74}
75
76/// In-process hexastore clients keyed by partition axis.
77#[derive(Debug, Clone)]
78pub struct LocalHexastoreClients {
79    partitions: BTreeMap<PartitionAxis, PartitionService>,
80}
81
82impl LocalHexastoreClients {
83    fn open(
84        backend: &Backend,
85        trace: bool,
86        warm: &std::sync::Arc<waratah_storage::WarmState>,
87    ) -> Result<Self, DevError> {
88        let mut partitions = BTreeMap::new();
89        for axis in PartitionAxis::ALL {
90            let service = match backend {
91                Backend::Memory => PartitionService::memory(axis),
92                Backend::RocksDb(path) => PartitionService::open_rocksdb(
93                    axis_data_dir(path, axis),
94                    axis,
95                    RocksDbOpenOptions::default(),
96                )?,
97            }
98            .with_trace(trace)
99            .with_identity(waratah_partition::NodeIdentity {
100                node_id: format!("{axis}-0"),
101                listen: String::new(),
102                data_dir: match backend {
103                    Backend::Memory => String::new(),
104                    Backend::RocksDb(path) => axis_data_dir(path, axis).display().to_string(),
105                },
106                repository_id: MAIN_REPOSITORY_ID.to_owned(),
107            });
108            partitions.insert(axis, service);
109        }
110        // Gate B (`WARATAH_WARM_CACHE`, on by default): warm each axis in the background,
111        // matching what the spawned `waratah-partition` processes do. Walks are
112        // tracked on `warm` so `/health` gates until they finish. No-op for
113        // the memory backend (no block cache), so skip the spawn there.
114        if waratah_storage::warm_cache_env_enabled() && matches!(backend, Backend::RocksDb(_)) {
115            for (axis, service) in &partitions {
116                let axis_name = format!("axis-{}", axis.as_str());
117                warm.track(axis_name.clone());
118                let service = service.clone();
119                // `Arc::clone`, not `warm.clone()` — the latter would clone
120                // the `&Arc` reference and capture its borrow in the thread.
121                let warm_thread = std::sync::Arc::clone(warm);
122                let axis = *axis;
123                std::thread::spawn(move || {
124                    let result =
125                        service.warm_block_cache(waratah_storage::WARM_CACHE_FILL_FRACTION);
126                    match &result {
127                        Ok(stats) => eprintln!(
128                            "partition-trace warm axis={axis}: entries={} usage {:.1} MiB -> {:.1} MiB of {:.1} MiB capacity",
129                            stats.entries_touched,
130                            stats.usage_before as f64 / 1024.0 / 1024.0,
131                            stats.usage_after as f64 / 1024.0 / 1024.0,
132                            stats.capacity as f64 / 1024.0 / 1024.0,
133                        ),
134                        Err(error) => eprintln!("partition-trace warm axis={axis} failed: {error}"),
135                    }
136                    warm_thread.complete(&axis_name);
137                });
138            }
139        }
140        Ok(Self { partitions })
141    }
142
143    fn partition(&self, axis: PartitionAxis) -> Result<&PartitionService, Status> {
144        self.partitions.get(&axis).ok_or_else(|| {
145            Status::failed_precondition(format!("no in-process partition for axis {axis}"))
146        })
147    }
148}
149
150/// In-process string-registry client (one dictionary, matching the MVP).
151#[derive(Debug, Clone)]
152pub struct LocalRegistryClients {
153    service: RegistryService,
154}
155
156impl LocalRegistryClients {
157    fn open(
158        backend: &Backend,
159        trace: bool,
160        warm: &std::sync::Arc<waratah_storage::WarmState>,
161    ) -> Result<Self, DevError> {
162        let service = match backend {
163            Backend::Memory => RegistryService::new(DEFAULT_SHARD_COUNT)
164                // In-memory mode still carries a RAM-backed blob store so geo
165                // writes work; payloads live until process shutdown.
166                .with_blobs_memory()?,
167            Backend::RocksDb(path) => RegistryService::open_rocksdb(
168                registry_data_dir(path, MAIN_REPOSITORY_ID),
169                RocksDbTuning::registry_node(),
170            )?
171            // Blob store beside the dictionary ({data_dir}/{repository}/blobs):
172            // the geo plugin's PutBlobs / GetBlobs land here in standalone mode.
173            .with_blobs(&waratah_storage::blob_store_dir(path, MAIN_REPOSITORY_ID))?,
174        }
175        .with_trace(trace)
176        .with_identity(waratah_registry::RegistryIdentity {
177            node_id: "registry-0".to_owned(),
178            listen: String::new(),
179            data_dir: match backend {
180                Backend::Memory => String::new(),
181                Backend::RocksDb(path) => registry_data_dir(path, MAIN_REPOSITORY_ID)
182                    .display()
183                    .to_string(),
184            },
185            repository_id: MAIN_REPOSITORY_ID.to_owned(),
186        });
187        // Gate B (`WARATAH_WARM_CACHE`, on by default): warm the dictionary in the
188        // background, matching what the spawned `waratah-registry` does.
189        // Tracked on `warm` so `/health` gates until it finishes. No-op for
190        // the memory backend (no block cache), so skip the spawn.
191        if waratah_storage::warm_cache_env_enabled() && matches!(backend, Backend::RocksDb(_)) {
192            warm.track("registry");
193            let service = service.clone();
194            // `Arc::clone`, not `warm.clone()` — same reference-clone gotcha.
195            let warm_thread = std::sync::Arc::clone(warm);
196            std::thread::spawn(move || {
197                let result = service.warm_block_cache(waratah_storage::WARM_CACHE_FILL_FRACTION);
198                match &result {
199                    Ok(stats) => eprintln!(
200                        "registry-trace warm: entries={} usage {:.1} MiB -> {:.1} MiB of {:.1} MiB capacity",
201                        stats.entries_touched,
202                        stats.usage_before as f64 / 1024.0 / 1024.0,
203                        stats.usage_after as f64 / 1024.0 / 1024.0,
204                        stats.capacity as f64 / 1024.0 / 1024.0,
205                    ),
206                    Err(error) => eprintln!("registry-trace warm failed: {error}"),
207                }
208                warm_thread.complete("registry");
209            });
210        }
211        Ok(Self { service })
212    }
213}
214
215fn axis_data_dir(data_dir: &Path, axis: PartitionAxis) -> std::path::PathBuf {
216    hexastore_data_dir(data_dir, MAIN_REPOSITORY_ID, axis)
217}
218
219impl waratah_compute::HexastoreGeo for LocalHexastoreClients {
220    async fn put_geo_index(&self, puts: &[waratah_storage::GeoIndexPut]) -> Result<u64, Status> {
221        let partition = self.partition(PartitionAxis::O)?.clone();
222        let puts = puts.to_vec();
223        Ok(
224            tokio::task::spawn_blocking(move || partition.apply_geo(&puts))
225                .await
226                .map_err(|join| blocking_join_error("storage", join))??,
227        )
228    }
229
230    async fn delete_geo_term(&self, term: &[u8]) -> Result<u64, Status> {
231        let partition = self.partition(PartitionAxis::O)?.clone();
232        let term = term.to_vec();
233        Ok(
234            tokio::task::spawn_blocking(move || partition.delete_geo_term(&term))
235                .await
236                .map_err(|join| blocking_join_error("storage", join))??,
237        )
238    }
239
240    async fn geo_candidate_scan(
241        &self,
242        intervals: &[waratah_storage::GeoCellInterval],
243        snapshot: SnapshotId,
244        query_envelope: Option<waratah_storage::GeoEnvelope>,
245        limit: u64,
246    ) -> Result<TermPageStream, Status> {
247        let partition = self.partition(PartitionAxis::O)?.clone();
248        let intervals = intervals.to_vec();
249        let frames = partition.geo_candidate_frames(intervals, snapshot, query_envelope, limit);
250        let pages = tokio_stream::StreamExt::map(frames, |frame| {
251            frame.and_then(|frame| {
252                frame
253                    .terms
254                    .iter()
255                    .map(|bytes| {
256                        waratah_proto::term_from_bytes(bytes)
257                            .map_err(|e| Status::internal(e.to_string()))
258                    })
259                    .collect()
260            })
261        });
262        Ok(Box::pin(pages))
263    }
264
265    /// Begin the geo index rebuild: take the rebuild lease and wipe the
266    /// `geo_index` CF. `already_in_progress` is the complement of `started`,
267    /// exactly how the partition's gRPC handler derives the pair from
268    /// `begin_geo_rebuild`'s `Option`.
269    ///
270    /// The lease needs no extra coordination on this path. `begin_geo_rebuild`
271    /// already keeps it as a plain `Option<Instant>` deadline, and in
272    /// `waratah standalone` the only client that can hold it is the compute node in
273    /// this process — a driver that dies takes the process with it, so the
274    /// deadline's expired-stale takeover can only ever fire against a lease
275    /// this same process abandoned.
276    async fn rebuild_geo_index(&self) -> Result<(bool, bool, u64), tonic::Status> {
277        let partition = self.partition(PartitionAxis::O)?.clone();
278        let upgrade_ts = tokio::task::spawn_blocking(move || partition.begin_geo_rebuild())
279            .await
280            .map_err(|join| blocking_join_error("storage", join))??;
281        let started = upgrade_ts.is_some();
282        Ok((started, !started, upgrade_ts.unwrap_or(0)))
283    }
284
285    /// Refresh the held rebuild lease (the driver calls this per batch so a
286    /// slow walk is not taken over).
287    async fn renew_geo_rebuild_lease(&self) -> Result<(), tonic::Status> {
288        let partition = self.partition(PartitionAxis::O)?.clone();
289        tokio::task::spawn_blocking(move || partition.renew_geo_rebuild_lease())
290            .await
291            .map_err(|join| blocking_join_error("storage", join))??;
292        Ok(())
293    }
294
295    /// Finish the geo index rebuild: stamp `epoch = max commit_ts` observed
296    /// on the partition and release the lease. Fails without a fresh lease,
297    /// same as the gRPC path.
298    async fn finish_geo_index_rebuild(&self) -> Result<u64, tonic::Status> {
299        let partition = self.partition(PartitionAxis::O)?.clone();
300        let epoch = tokio::task::spawn_blocking(move || partition.finish_geo_rebuild())
301            .await
302            .map_err(|join| blocking_join_error("storage", join))??;
303        Ok(epoch)
304    }
305
306    /// Apply temporal-index postings on the O partition.
307    ///
308    /// Without this the trait's default returns `unimplemented`, and every
309    /// temporal write plugin posting is dropped in `waratah standalone`: the index
310    /// stays empty AND its epoch stays unstamped, so the comparison rewrite's
311    /// trust gate refuses to fire and queries fall back to the unindexed
312    /// residual. Right answers, no index, nothing logged. The geo twin above
313    /// is implemented; this is the parity it was missing.
314    async fn put_temporal_index(
315        &self,
316        puts: &[waratah_storage::TemporalIndexPut],
317    ) -> Result<u64, Status> {
318        let partition = self.partition(PartitionAxis::O)?.clone();
319        let puts = puts.to_vec();
320        Ok(
321            tokio::task::spawn_blocking(move || partition.apply_temporal(&puts))
322                .await
323                .map_err(|join| blocking_join_error("storage", join))??,
324        )
325    }
326
327    /// Drain one temporal candidate scan (never cursor-paged; the partition
328    /// owns the DISTINCT seen-set for the drain).
329    async fn temporal_candidate_scan(
330        &self,
331        intervals: &[waratah_storage::TemporalCellInterval],
332        snapshot: SnapshotId,
333        predicate: waratah_storage::TemporalQueryPredicate,
334        limit: u64,
335    ) -> Result<TermPageStream, Status> {
336        let partition = self.partition(PartitionAxis::O)?.clone();
337        let intervals = intervals.to_vec();
338        let frames = partition.temporal_candidate_frames(intervals, snapshot, predicate, limit);
339        let pages = tokio_stream::StreamExt::map(frames, |frame| {
340            frame.and_then(|frame| {
341                frame
342                    .terms
343                    .iter()
344                    .map(|bytes| {
345                        waratah_proto::term_from_bytes(bytes)
346                            .map_err(|e| Status::internal(e.to_string()))
347                    })
348                    .collect()
349            })
350        });
351        Ok(Box::pin(pages))
352    }
353
354    /// Trigger the O-axis temporal rebuild, mirroring the partition's
355    /// gRPC handler: `started` says this call ran the walk,
356    /// `already_in_progress` is its complement (the in-progress flag is
357    /// compare-exchanged, so a loser reports `Ok(false)` rather than
358    /// blocking).
359    async fn rebuild_temporal_index(
360        &self,
361        config: waratah_storage::DyadicCovererConfig,
362    ) -> Result<(bool, bool), Status> {
363        let partition = self.partition(PartitionAxis::O)?.clone();
364        let started = tokio::task::spawn_blocking(move || partition.rebuild_temporal_index(config))
365            .await
366            .map_err(|join| blocking_join_error("storage", join))??;
367        Ok((started, !started))
368    }
369
370    async fn put_text_index(&self, docs: &[waratah_storage::TextIndexDoc]) -> Result<u64, Status> {
371        let partition = self.partition(PartitionAxis::O)?.clone();
372        let docs = docs.to_vec();
373        Ok(
374            tokio::task::spawn_blocking(move || partition.apply_text(&docs))
375                .await
376                .map_err(|join| blocking_join_error("storage", join))??,
377        )
378    }
379
380    async fn text_candidate_scan(
381        &self,
382        request: &waratah_storage::TextSearchRequest,
383        snapshot: SnapshotId,
384    ) -> Result<waratah_compute::TermPageStream, Status> {
385        // The index carries no per-document visibility: the timestamp rides
386        // for diagnostics only (the join with visible rows filters).
387        let _ = snapshot;
388        let partition = self.partition(PartitionAxis::O)?.clone();
389        let request = request.clone();
390        // The drain is one index search; frame it here (the partition's
391        // stream helper targets the gRPC service shape).
392        let (tx, rx) = tokio::sync::mpsc::channel(2);
393        tokio::spawn(async move {
394            let result = tokio::task::spawn_blocking(move || {
395                partition.text_candidates(&request).map(|terms| {
396                    terms
397                        .chunks(waratah_proto::SCAN_STREAM_FRAME_ROWS)
398                        .map(|chunk| {
399                            chunk
400                                .iter()
401                                .map(|bytes| {
402                                    waratah_proto::term_from_bytes(bytes)
403                                        .map_err(|error| Status::internal(error.to_string()))
404                                })
405                                .collect::<Result<Vec<_>, _>>()
406                        })
407                        .collect::<Result<Vec<_>, _>>()
408                })
409            })
410            .await;
411            match result {
412                Ok(Ok(Ok(frames))) => {
413                    for frame in frames {
414                        if tx.send(Ok(frame)).await.is_err() {
415                            return;
416                        }
417                    }
418                }
419                Ok(Ok(Err(status))) => {
420                    let _ = tx.send(Err(status)).await;
421                }
422                Ok(Err(error)) => {
423                    let _ = tx.send(Err(Status::from(error))).await;
424                }
425                Err(join) => {
426                    let _ = tx.send(Err(blocking_join_error("storage", join))).await;
427                }
428            }
429        });
430        Ok(Box::pin(tokio_stream::wrappers::ReceiverStream::new(rx)))
431    }
432
433    async fn text_subject_scan(
434        &self,
435        request: &waratah_storage::TextSubjectRequest,
436        snapshot: SnapshotId,
437    ) -> Result<waratah_compute::SubjectRowStream, Status> {
438        let partition = self.partition(PartitionAxis::O)?.clone();
439        let request = request.clone();
440        let (tx, rx) = tokio::sync::mpsc::channel(2);
441        let tx_errors = tx.clone();
442        tokio::spawn(async move {
443            let result = tokio::task::spawn_blocking(move || -> Result<(), PartitionError> {
444                // Stream each page as the resolve produces it: the local
445                // client must not materialise the whole answer either.
446                partition.resolve_text_subjects(&request, snapshot, &mut |rows| match tx
447                    .blocking_send(Ok(rows.to_vec()))
448                {
449                    Ok(()) => Ok(true),
450                    Err(_) => Ok(false),
451                })
452            })
453            .await;
454            match result {
455                Ok(Ok(())) => {}
456                Ok(Err(error)) => {
457                    let _ = tx_errors.send(Err(Status::from(error))).await;
458                }
459                Err(join) => {
460                    let _ = tx_errors
461                        .send(Err(blocking_join_error("storage", join)))
462                        .await;
463                }
464            }
465        });
466        Ok(Box::pin(tokio_stream::wrappers::ReceiverStream::new(rx)))
467    }
468
469    async fn rebuild_text_index(
470        &self,
471        analyzer: &str,
472        seed_chars: u32,
473        fingerprint: &str,
474        wipe: bool,
475    ) -> Result<(bool, bool, u64), Status> {
476        let partition = self.partition(PartitionAxis::O)?.clone();
477        let options = waratah_text_index::TextIndexOptions::new(
478            analyzer.to_owned(),
479            seed_chars as usize,
480            fingerprint.to_owned(),
481        );
482        let token =
483            tokio::task::spawn_blocking(move || partition.begin_text_rebuild(&options, wipe))
484                .await
485                .map_err(|join| blocking_join_error("storage", join))??;
486        Ok((token.is_some(), token.is_none(), token.unwrap_or(0)))
487    }
488
489    async fn renew_text_rebuild_lease(&self, lease_token: u64) -> Result<(), Status> {
490        let partition = self.partition(PartitionAxis::O)?.clone();
491        tokio::task::spawn_blocking(move || partition.renew_text_rebuild_lease(lease_token))
492            .await
493            .map_err(|join| blocking_join_error("storage", join))??;
494        Ok(())
495    }
496
497    async fn finish_text_index_rebuild(
498        &self,
499        lease_token: u64,
500        stamp: bool,
501    ) -> Result<u64, Status> {
502        let partition = self.partition(PartitionAxis::O)?.clone();
503        let (epoch, describe) = tokio::task::spawn_blocking(move || -> Result<_, Status> {
504            let epoch = partition.finish_text_rebuild(lease_token, stamp)?;
505            // The stamped epoch rides the sidecar; Describe reports it.
506            let describe = partition.describe();
507            Ok((epoch, describe))
508        })
509        .await
510        .map_err(|join| blocking_join_error("storage", join))??;
511        debug_assert!(
512            epoch == 0 || describe.text_index_epoch == Some(epoch),
513            "a stamping finish reports exactly the epoch it stamped; a \
514             non-stamping finish returns 0 over the index's previous epoch"
515        );
516        Ok(epoch)
517    }
518}
519
520impl waratah_compute::BlobStoreClient for LocalRegistryClients {
521    async fn put_blob_chunks(
522        &self,
523        blob_id: waratah_storage::StrHash,
524        payload: Arc<[u8]>,
525    ) -> Result<(), Status> {
526        let service = self.service.clone();
527        tokio::task::spawn_blocking(move || service.put_blob(blob_id, &payload))
528            .await
529            .map_err(|join| blocking_join_error("registry", join))??;
530        Ok(())
531    }
532
533    async fn put_blobs(
534        &self,
535        blobs: &[(waratah_storage::StrHash, Arc<[u8]>)],
536    ) -> Result<(), Status> {
537        // The registry service's inherent `put_blobs` IS the RPC's
538        // semantics — existence probe, skip-existing, hash validation
539        // before any write, segment bytes fdatasynced before one atomic
540        // index commit per batch (the commit fsyncs the WAL) — so the
541        // local path observes exactly what a `PutBlobs` server would do,
542        // with no second implementation to keep in sync.
543        let service = self.service.clone();
544        let blobs = blobs.to_vec();
545        tokio::task::spawn_blocking(move || service.put_blobs(&blobs))
546            .await
547            .map_err(|join| blocking_join_error("registry", join))??;
548        Ok(())
549    }
550
551    async fn get_blobs(
552        &self,
553        ids: &[waratah_storage::StrHash],
554    ) -> Result<Vec<Option<Vec<u8>>>, Status> {
555        let service = self.service.clone();
556        let request = ids.to_vec();
557        let payloads = tokio::task::spawn_blocking(move || service.get_blobs(&request))
558            .await
559            .map_err(|join| blocking_join_error("registry", join))??;
560        // The gRPC client re-hashes each reassembled payload against its id;
561        // the in-process path has no wire boundary, so it performs the same
562        // content-addressing check here. The index lookup is not a
563        // substitute: a corrupt value can be returned under the requested
564        // key.
565        for (id, payload) in ids.iter().zip(&payloads) {
566            if let Some(payload) = payload
567                && waratah_storage::StrHash::from_bytes(payload) != *id
568            {
569                return Err(Status::internal(format!(
570                    "blob {id} failed content-addressing verification"
571                )));
572            }
573        }
574        Ok(payloads)
575    }
576}
577
578impl HexastoreInsert for LocalHexastoreClients {
579    async fn insert_quads(
580        &self,
581        axis: PartitionAxis,
582        versions: &[QuadVersion],
583    ) -> Result<u64, Status> {
584        let partition = self.partition(axis)?.clone();
585        let versions = versions.to_vec();
586        Ok(
587            tokio::task::spawn_blocking(move || partition.apply_versions(Some(axis), &versions))
588                .await
589                .map_err(|join| blocking_join_error("storage", join))??,
590        )
591    }
592
593    async fn replace_quads(
594        &self,
595        pairs: &[ReplacePair],
596        commit_ts: CommitTs,
597    ) -> Result<u64, Status> {
598        // The migration primitive (the geo auto-upgrade): every axis receives
599        // the SAME pairs and translates them into its own permutation rows —
600        // the partition-local half of the gRPC `ReplaceQuads` handler. Left
601        // to the trait default, the answer was `unimplemented`, so a
602        // standalone startup with orphaned geo literals failed the upgrade
603        // and stayed UNINDEXED (warn + residual path) on every start.
604        let mut replaced = 0u64;
605        for axis in [PartitionAxis::S, PartitionAxis::P, PartitionAxis::O] {
606            let partition = self.partition(axis)?.clone();
607            let pairs = pairs.to_vec();
608            replaced +=
609                tokio::task::spawn_blocking(move || partition.apply_replaces(&pairs, commit_ts))
610                    .await
611                    .map_err(|join| blocking_join_error("storage", join))??;
612        }
613        Ok(replaced)
614    }
615}
616
617impl HexastoreAxisHeadStats for LocalHexastoreClients {
618    async fn axis_head_max_commit_ts(
619        &self,
620        permutation: IndexPermutation,
621        head_prefixes: &[Vec<u8>],
622    ) -> Result<u64, Status> {
623        let partition = self.partition(PartitionAxis::from(permutation))?.clone();
624        let head_prefixes = head_prefixes.to_vec();
625        Ok(tokio::task::spawn_blocking(move || {
626            partition.axis_head_max_commit_ts(permutation, &head_prefixes)
627        })
628        .await
629        .map_err(|join| blocking_join_error("storage", join))??)
630    }
631}
632
633impl HexastoreScan for LocalHexastoreClients {
634    #[allow(clippy::too_many_arguments)]
635    async fn scan_pattern(
636        &self,
637        axis: PartitionAxis,
638        pattern: &EncodedTriplePattern,
639        snapshot: SnapshotId,
640        limit: u64,
641        permutation: Option<IndexPermutation>,
642        filter: Option<&BroadcastFilter>,
643        graph_filter: Option<&GraphFilter>,
644        start_after: Option<&EncodedQuad>,
645        merge_default_graph: bool,
646        iri_only: IriOnlyMask,
647        omitted: u8,
648        verdict_wanted: bool,
649    ) -> Result<waratah_storage::ScanPage, Status> {
650        self.scan_pattern_with_comparisons(
651            axis,
652            pattern,
653            snapshot,
654            limit,
655            permutation,
656            filter,
657            graph_filter,
658            start_after,
659            merge_default_graph,
660            iri_only,
661            &[],
662            omitted,
663            verdict_wanted,
664        )
665        .await
666    }
667
668    /// In-process mirror of the partition's `ScanPattern` handler: the
669    /// comparisons go straight into `scan_filtered_packed`'s walk, with no
670    /// proto round-trip for the comparison list itself. The packed page is
671    /// still decoded below, so the comparison semantics are the same ones
672    /// the wire path exercises.
673    #[allow(clippy::too_many_arguments)]
674    async fn scan_pattern_with_comparisons(
675        &self,
676        axis: PartitionAxis,
677        pattern: &EncodedTriplePattern,
678        snapshot: SnapshotId,
679        limit: u64,
680        permutation: Option<IndexPermutation>,
681        filter: Option<&BroadcastFilter>,
682        graph_filter: Option<&GraphFilter>,
683        start_after: Option<&EncodedQuad>,
684        merge_default_graph: bool,
685        iri_only: IriOnlyMask,
686        comparisons: &[SlotComparison],
687        omitted: u8,
688        verdict_wanted: bool,
689    ) -> Result<waratah_storage::ScanPage, Status> {
690        // Own the list: the blocking-pool branch must be `'static`.
691        let comparisons = comparisons.to_vec();
692        let (slot, terms) = broadcast_args(filter);
693        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
694        let graph_terms = graph_terms.to_vec();
695        let pattern = pattern.clone();
696        let start_after = start_after.cloned();
697        let partition = self.partition(axis)?.clone();
698        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): small scans run
699        // directly on this worker — the blocking-pool wake is pure latency
700        // for a µs-scale seek, and its CFS wakeup delay is the measured
701        // ~600 µs small-query stall (see scan_runs_on_caller).
702        let page = if partition.scan_runs_on_caller(
703            permutation,
704            &pattern,
705            slot,
706            terms.as_deref().unwrap_or(&[]),
707        ) {
708            partition.scan_filtered_packed(
709                permutation,
710                &pattern,
711                snapshot,
712                limit,
713                slot,
714                terms.as_deref().unwrap_or(&[]),
715                start_after.as_ref(),
716                &graph_terms,
717                graph_allow,
718                merge_default_graph,
719                iri_only,
720                &comparisons,
721                omitted,
722                verdict_wanted,
723            )?
724        } else {
725            // The task takes its own pattern clone: the walk consumes it,
726            // and the caller keeps decoding against the original below.
727            let task_pattern = pattern.clone();
728            tokio::task::spawn_blocking(move || {
729                partition.scan_filtered_packed(
730                    permutation,
731                    &task_pattern,
732                    snapshot,
733                    limit,
734                    slot,
735                    terms.as_deref().unwrap_or(&[]),
736                    start_after.as_ref(),
737                    &graph_terms,
738                    graph_allow,
739                    merge_default_graph,
740                    iri_only,
741                    &comparisons,
742                    omitted,
743                    verdict_wanted,
744                )
745            })
746            .await
747            .map_err(|join| blocking_join_error("storage", join))??
748        };
749        // One decoder for every transport: the packed page is reassembled
750        // exactly as the gRPC unary client reassembles its response, so the
751        // in-process unary path honours the same mask the wire does. That
752        // uniformity costs one extra copy of every row's term bytes plus a
753        // protobuf message per row versus decoding straight out of the
754        // storage key — accepted so in-process unary exercises the identical
755        // mask/reassembly rule the wire does; it also means the standalone
756        // arm of any scan A/B carries this overhead, keeping recorded
757        // standalone wins conservative.
758        // One decoder for every transport: the packed page is reassembled
759        // exactly as the gRPC unary client reassembles its response, so the
760        // in-process unary path honours the same mask the wire does. That
761        // uniformity costs one extra copy of every row's term bytes plus a
762        // protobuf message per row versus decoding straight out of the
763        // storage key — accepted so in-process unary exercises the identical
764        // mask/reassembly rule the wire does; it also means the standalone
765        // arm of any scan A/B carries this overhead, keeping recorded
766        // standalone wins conservative.
767        let rows = page
768            .quads
769            .iter()
770            .map(|quad| {
771                quad_from_proto_omitting(quad, &pattern, omitted)
772                    .map_err(|e| Status::internal(e.to_string()))
773            })
774            .collect::<Result<Vec<_>, _>>()?;
775        Ok(waratah_storage::ScanPage {
776            rows,
777            exhausted: waratah_proto::scan_exhaustion_from_proto_opt(page.exhausted),
778        })
779    }
780
781    #[allow(clippy::too_many_arguments)]
782    async fn scan_pattern_stream(
783        &self,
784        axis: PartitionAxis,
785        pattern: &EncodedTriplePattern,
786        snapshot: SnapshotId,
787        limit: u64,
788        permutation: Option<IndexPermutation>,
789        filter: Option<&BroadcastFilter>,
790        graph_filter: Option<&GraphFilter>,
791        start_after: Option<&EncodedQuad>,
792        merge_default_graph: bool,
793        iri_only: IriOnlyMask,
794        omitted: u8,
795        verdict_wanted: bool,
796    ) -> Result<QuadPageStream, Status> {
797        self.scan_pattern_stream_with_comparisons(
798            axis,
799            pattern,
800            snapshot,
801            limit,
802            permutation,
803            filter,
804            graph_filter,
805            start_after,
806            merge_default_graph,
807            iri_only,
808            &[],
809            omitted,
810            verdict_wanted,
811        )
812        .await
813    }
814
815    /// Mirror of the partition's `ScanPatternStream` handler: ONE continuous
816    /// `scan_filtered_streaming` walk packed into frames on a bounded
817    /// channel, so the eager path's compute-side drain logic sees the same
818    /// streaming shape it gets over real gRPC (the trait default would
819    /// return one unlimited page).
820    ///
821    /// Both frame branches (caller-thread and dispatched) hand the
822    /// comparison list to the same walk, so the in-process stream applies
823    /// exactly the rows the wire stream would.
824    #[allow(clippy::too_many_arguments)]
825    async fn scan_pattern_stream_with_comparisons(
826        &self,
827        axis: PartitionAxis,
828        pattern: &EncodedTriplePattern,
829        snapshot: SnapshotId,
830        limit: u64,
831        permutation: Option<IndexPermutation>,
832        filter: Option<&BroadcastFilter>,
833        graph_filter: Option<&GraphFilter>,
834        start_after: Option<&EncodedQuad>,
835        merge_default_graph: bool,
836        iri_only: IriOnlyMask,
837        comparisons: &[SlotComparison],
838        omitted: u8,
839        verdict_wanted: bool,
840    ) -> Result<QuadPageStream, Status> {
841        // Own the list: the dispatched frame branch must be `'static`.
842        let comparisons = comparisons.to_vec();
843        let (slot, terms) = broadcast_args(filter);
844        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
845        let graph_terms = graph_terms.to_vec();
846        let pattern = pattern.clone();
847        let start_after = start_after.cloned();
848        let partition = self.partition(axis)?.clone();
849        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): an estimable drain
850        // at or below the threshold runs the whole walk on this worker —
851        // the blocking-pool wake is pure latency for a µs-scale walk, and
852        // its CFS wakeup delay is the measured ~600 µs small-query stall
853        // (see scan_runs_on_caller). Frames, ordering, and error items are
854        // identical to the dispatched drain below; the consumer cannot drop
855        // mid-walk because the estimate bounds the work.
856        if partition.scan_runs_on_caller(
857            permutation,
858            &pattern,
859            slot,
860            terms.as_deref().unwrap_or(&[]),
861        ) {
862            let mut remaining = limit; // 0 = unlimited
863            let mut frame: Vec<EncodedQuad> = Vec::with_capacity(SCAN_STREAM_FRAME_ROWS);
864            let mut items: Vec<Result<waratah_storage::ScanPage, Status>> = Vec::new();
865            let walked = partition.scan_filtered_streaming(
866                permutation,
867                &pattern,
868                snapshot,
869                slot,
870                terms.as_deref().unwrap_or(&[]),
871                start_after.as_ref(),
872                &graph_terms,
873                graph_allow,
874                merge_default_graph,
875                iri_only,
876                &comparisons,
877                |row| {
878                    // Page-limit discipline, selected by the consumer's
879                    // `verdict_wanted` declaration (see the partition's
880                    // `scan_pattern_stream_frames` for the full note):
881                    // EDGE-triggered when wanted, LEVEL-triggered when
882                    // not. Both stops flush the pending partial frame;
883                    // only the EDGE stop's flush carries a verdict
884                    // (LIMITED — the refusing row proved more data), the
885                    // LEVEL stop's none — matching the wire protocol.
886                    if limit > 0 && remaining == 0 {
887                        if !frame.is_empty() {
888                            let ready = std::mem::take(&mut frame);
889                            let ready_rows = ready.len();
890                            items.push(Ok(waratah_storage::ScanPage {
891                                rows: ready,
892                                exhausted: Some(waratah_storage::ScanExhaustion::Limited),
893                            }));
894                            waratah_compute::note_wire_stream_item(ready_rows);
895                        }
896                        return false;
897                    }
898                    match waratah_storage::decode_index_key_omitting(
899                        row.permutation,
900                        row.logical(),
901                        &pattern,
902                        omitted,
903                    ) {
904                        Ok(quad) => frame.push(quad),
905                        Err(error) => {
906                            // Same semantics as the dispatched drain: the
907                            // error item takes the frame's place and the
908                            // walk stops.
909                            let partition_error = waratah_partition::PartitionError::from(error);
910                            items.push(Err(Status::from(partition_error)));
911                            return false;
912                        }
913                    }
914                    remaining = remaining.saturating_sub(1);
915                    if frame.len() >= SCAN_STREAM_FRAME_ROWS {
916                        // Mid-walk frame-size flush: no verdict — the walk
917                        // being live at a frame boundary says nothing
918                        // about what follows the frame.
919                        let ready = std::mem::take(&mut frame);
920                        let ready_rows = ready.len();
921                        items.push(Ok(waratah_storage::ScanPage {
922                            rows: ready,
923                            exhausted: None,
924                        }));
925                        waratah_compute::note_wire_stream_item(ready_rows);
926                    }
927                    if limit > 0 && remaining == 0 && !verdict_wanted {
928                        if !frame.is_empty() {
929                            let ready = std::mem::take(&mut frame);
930                            let ready_rows = ready.len();
931                            items.push(Ok(waratah_storage::ScanPage {
932                                rows: ready,
933                                exhausted: None,
934                            }));
935                            waratah_compute::note_wire_stream_item(ready_rows);
936                        }
937                        return false;
938                    }
939                    true
940                },
941            );
942            match walked {
943                Ok(verdict) => {
944                    if verdict.is_terminal() {
945                        // Flush the trailing partial frame of a COMPLETED
946                        // walk under either flag (rows must not be lost;
947                        // the frame carries no verdict — mid-walk frames
948                        // never do), then the terminal frame — but only
949                        // when the verdict was purchased: without
950                        // `verdict_wanted` no frame carries a verdict and
951                        // none is sent, matching the wire protocol the
952                        // partition emits.
953                        if !frame.is_empty() {
954                            let ready = std::mem::take(&mut frame);
955                            let ready_rows = ready.len();
956                            items.push(Ok(waratah_storage::ScanPage {
957                                rows: ready,
958                                exhausted: None,
959                            }));
960                            waratah_compute::note_wire_stream_item(ready_rows);
961                        }
962                        if verdict_wanted {
963                            items.push(Ok(waratah_storage::ScanPage {
964                                rows: Vec::new(),
965                                exhausted: Some(verdict),
966                            }));
967                        }
968                    }
969                }
970                Err(error) => items.push(Err(Status::from(error))),
971            }
972            return Ok(Box::pin(tokio_stream::iter(items)));
973        }
974        // Two outstanding frames: backpressure without pinning much memory.
975        let (tx, rx) = tokio::sync::mpsc::channel(2);
976        tokio::task::spawn_blocking(move || {
977            let mut remaining = limit; // 0 = unlimited
978            let mut client_dropped = false;
979            let mut frame: Vec<EncodedQuad> = Vec::with_capacity(SCAN_STREAM_FRAME_ROWS);
980            // Compute's in-process contract is decoded quads; rows arrive as
981            // raw key slices and are decoded here (only rows that already
982            // passed the matcher).
983            let walked = partition.scan_filtered_streaming(
984                permutation,
985                &pattern,
986                snapshot,
987                slot,
988                terms.as_deref().unwrap_or(&[]),
989                start_after.as_ref(),
990                &graph_terms,
991                graph_allow,
992                merge_default_graph,
993                iri_only,
994                &comparisons,
995                |row| {
996                    // Page-limit discipline, selected by the consumer's
997                    // `verdict_wanted` declaration (see the
998                    // caller-collected branch's note for the full
999                    // reasoning): EDGE-triggered when wanted,
1000                    // LEVEL-triggered when not; both stops flush the
1001                    // pending partial frame. Only the EDGE stop's flush
1002                    // carries a verdict (LIMITED — the refusing row proved
1003                    // more data); the LEVEL stop's carries none, matching
1004                    // the wire protocol.
1005                    if limit > 0 && remaining == 0 {
1006                        if !frame.is_empty() {
1007                            let ready = std::mem::take(&mut frame);
1008                            let ready_rows = ready.len();
1009                            let _ = tx.blocking_send(Ok(waratah_storage::ScanPage {
1010                                rows: ready,
1011                                exhausted: Some(waratah_storage::ScanExhaustion::Limited),
1012                            }));
1013                            waratah_compute::note_wire_stream_item(ready_rows);
1014                        }
1015                        return false;
1016                    }
1017                    match waratah_storage::decode_index_key_omitting(
1018                        row.permutation,
1019                        row.logical(),
1020                        &pattern,
1021                        omitted,
1022                    ) {
1023                        Ok(quad) => frame.push(quad),
1024                        Err(error) => {
1025                            let partition_error = waratah_partition::PartitionError::from(error);
1026                            let _ = tx.blocking_send(Err(Status::from(partition_error)));
1027                            client_dropped = true;
1028                            return false;
1029                        }
1030                    }
1031                    remaining = remaining.saturating_sub(1);
1032                    if frame.len() >= SCAN_STREAM_FRAME_ROWS {
1033                        // Mid-walk frame-size flush: no verdict — the walk
1034                        // being live at a frame boundary says nothing
1035                        // about what follows the frame.
1036                        let ready = std::mem::take(&mut frame);
1037                        let ready_rows = ready.len();
1038                        if tx
1039                            .blocking_send(Ok(waratah_storage::ScanPage {
1040                                rows: ready,
1041                                exhausted: None,
1042                            }))
1043                            .is_err()
1044                        {
1045                            client_dropped = true;
1046                            return false;
1047                        }
1048                        waratah_compute::note_wire_stream_item(ready_rows);
1049                    }
1050                    if limit > 0 && remaining == 0 && !verdict_wanted {
1051                        if !frame.is_empty() {
1052                            let ready = std::mem::take(&mut frame);
1053                            let ready_rows = ready.len();
1054                            let _ = tx.blocking_send(Ok(waratah_storage::ScanPage {
1055                                rows: ready,
1056                                exhausted: None,
1057                            }));
1058                            waratah_compute::note_wire_stream_item(ready_rows);
1059                        }
1060                        return false;
1061                    }
1062                    true
1063                },
1064            );
1065            match walked {
1066                Ok(verdict) => {
1067                    if verdict.is_terminal() {
1068                        // Flush the trailing partial frame of a COMPLETED
1069                        // walk under either flag (a limit-stop drain already
1070                        // flushed inside the walk; a dropped stream has
1071                        // nowhere to send). The flushed frame carries no
1072                        // verdict — mid-walk frames never do. Then the
1073                        // terminal frame, but only when the verdict was
1074                        // purchased: without `verdict_wanted` no frame
1075                        // carries a verdict and none is sent, the same
1076                        // frame shape the partition's stream handler emits,
1077                        // so in-process and gRPC consumers read the
1078                        // identical protocol. A dropped stream has nowhere
1079                        // to send it either.
1080                        if !frame.is_empty() {
1081                            let ready = std::mem::take(&mut frame);
1082                            let ready_rows = ready.len();
1083                            let _ = tx.blocking_send(Ok(waratah_storage::ScanPage {
1084                                rows: ready,
1085                                exhausted: None,
1086                            }));
1087                            waratah_compute::note_wire_stream_item(ready_rows);
1088                        }
1089                        if verdict_wanted && !client_dropped {
1090                            let _ = tx.blocking_send(Ok(waratah_storage::ScanPage {
1091                                rows: Vec::new(),
1092                                exhausted: Some(verdict),
1093                            }));
1094                        }
1095                    }
1096                }
1097                Err(error) => {
1098                    let _ = tx.blocking_send(Err(Status::from(error)));
1099                }
1100            }
1101            let _ = client_dropped;
1102        });
1103        Ok(Box::pin(ReceiverStream::new(rx)))
1104    }
1105
1106    #[allow(clippy::too_many_arguments)]
1107    async fn count_pattern(
1108        &self,
1109        axis: PartitionAxis,
1110        pattern: &EncodedTriplePattern,
1111        snapshot: SnapshotId,
1112        limit: u64,
1113        permutation: Option<IndexPermutation>,
1114        filter: Option<&BroadcastFilter>,
1115        graph_filter: Option<&GraphFilter>,
1116        merge_default_graph: bool,
1117    ) -> Result<u64, Status> {
1118        let (slot, terms) = broadcast_args(filter);
1119        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1120        let graph_terms = graph_terms.to_vec();
1121        let pattern = pattern.clone();
1122        let partition = self.partition(axis)?.clone();
1123        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): an estimable
1124        // count at or below the threshold runs directly on this worker —
1125        // same walk shape as the scans, same ~600 µs pool-wake stall
1126        // avoided (see scan_runs_on_caller).
1127        if partition.scan_runs_on_caller(
1128            permutation,
1129            &pattern,
1130            slot,
1131            terms.as_deref().unwrap_or(&[]),
1132        ) {
1133            return Ok(partition.count_filtered(
1134                permutation,
1135                &pattern,
1136                snapshot,
1137                limit,
1138                slot,
1139                terms.as_deref().unwrap_or(&[]),
1140                &graph_terms,
1141                graph_allow,
1142                merge_default_graph,
1143            )?);
1144        }
1145        Ok(tokio::task::spawn_blocking(move || {
1146            partition.count_filtered(
1147                permutation,
1148                &pattern,
1149                snapshot,
1150                limit,
1151                slot,
1152                terms.as_deref().unwrap_or(&[]),
1153                &graph_terms,
1154                graph_allow,
1155                merge_default_graph,
1156            )
1157        })
1158        .await
1159        .map_err(|join| blocking_join_error("storage", join))??)
1160    }
1161
1162    #[allow(clippy::too_many_arguments)]
1163    /// Distinct slot-1 head terms under each slot-0 constraint of
1164    /// `permutation`.
1165    async fn scan_domain(
1166        &self,
1167        permutation: IndexPermutation,
1168        constraints: &[EncodedTerm],
1169        snapshot: SnapshotId,
1170        limit: u64,
1171        start_after_constraint: Option<&EncodedTerm>,
1172        start_after_term: Option<&EncodedTerm>,
1173        graph_name: Option<&EncodedTerm>,
1174        graph_filter: Option<&GraphFilter>,
1175        iri_only_head: bool,
1176    ) -> Result<Vec<DomainScanHit>, Status> {
1177        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1178        let graph_terms = graph_terms.to_vec();
1179        let constraints = constraints.to_vec();
1180        let start_after_constraint = start_after_constraint.cloned();
1181        let start_after_term = start_after_term.cloned();
1182        let graph_name = graph_name.cloned();
1183        let partition = self.partition(PartitionAxis::from(permutation))?.clone();
1184        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): a predicate-keyed
1185        // domain scan whose constraint sum is at or below the threshold runs
1186        // directly on this worker (see domain_scan_runs_on_caller).
1187        if partition.domain_scan_runs_on_caller(permutation, &constraints) {
1188            return Ok(partition.scan_domain(
1189                permutation,
1190                &constraints,
1191                snapshot,
1192                limit,
1193                start_after_constraint.as_ref(),
1194                start_after_term.as_ref(),
1195                graph_name.as_ref(),
1196                &graph_terms,
1197                graph_allow,
1198                iri_only_head,
1199            )?);
1200        }
1201        let hits = tokio::task::spawn_blocking(move || {
1202            partition.scan_domain(
1203                permutation,
1204                &constraints,
1205                snapshot,
1206                limit,
1207                start_after_constraint.as_ref(),
1208                start_after_term.as_ref(),
1209                graph_name.as_ref(),
1210                &graph_terms,
1211                graph_allow,
1212                iri_only_head,
1213            )
1214        })
1215        .await
1216        .map_err(|join| blocking_join_error("storage", join))??;
1217        Ok(hits)
1218    }
1219
1220    #[allow(clippy::too_many_arguments)]
1221    /// Run lengths of slot-1 head terms under each slot-0 constraint of
1222    /// `permutation`.
1223    async fn scan_domain_counts(
1224        &self,
1225        permutation: IndexPermutation,
1226        constraints: &[EncodedTerm],
1227        snapshot: SnapshotId,
1228        limit: u64,
1229        start_after_constraint: Option<&EncodedTerm>,
1230        start_after_term: Option<&EncodedTerm>,
1231        graph_name: Option<&EncodedTerm>,
1232        graph_filter: Option<&GraphFilter>,
1233        iri_only_head: bool,
1234        merge_default_graph: bool,
1235        mode: DomainCountMode,
1236    ) -> Result<Vec<DomainScanCountHit>, Status> {
1237        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1238        let graph_terms = graph_terms.to_vec();
1239        let constraints = constraints.to_vec();
1240        let start_after_constraint = start_after_constraint.cloned();
1241        let start_after_term = start_after_term.cloned();
1242        let graph_name = graph_name.cloned();
1243        let partition = self.partition(PartitionAxis::from(permutation))?.clone();
1244        // Exact-stats gate (SCAN_DISPATCH_ROW_THRESHOLD): same as the
1245        // domain-scan gate — the count variant walks the same prefixes
1246        // (see domain_scan_runs_on_caller).
1247        if partition.domain_scan_runs_on_caller(permutation, &constraints) {
1248            return Ok(partition.scan_domain_counts(
1249                permutation,
1250                &constraints,
1251                snapshot,
1252                limit,
1253                start_after_constraint.as_ref(),
1254                start_after_term.as_ref(),
1255                graph_name.as_ref(),
1256                &graph_terms,
1257                graph_allow,
1258                iri_only_head,
1259                merge_default_graph,
1260                mode,
1261            )?);
1262        }
1263        let hits = tokio::task::spawn_blocking(move || {
1264            partition.scan_domain_counts(
1265                permutation,
1266                &constraints,
1267                snapshot,
1268                limit,
1269                start_after_constraint.as_ref(),
1270                start_after_term.as_ref(),
1271                graph_name.as_ref(),
1272                &graph_terms,
1273                graph_allow,
1274                iri_only_head,
1275                merge_default_graph,
1276                mode,
1277            )
1278        })
1279        .await
1280        .map_err(|join| blocking_join_error("storage", join))??;
1281        Ok(hits)
1282    }
1283
1284    #[allow(clippy::too_many_arguments)]
1285    /// Distinct slot-0 head terms of the whole `permutation` CF.
1286    async fn scan_axis_head(
1287        &self,
1288        permutation: IndexPermutation,
1289        snapshot: SnapshotId,
1290        limit: u64,
1291        start_after_term: Option<&EncodedTerm>,
1292        graph_name: Option<&EncodedTerm>,
1293        graph_filter: Option<&GraphFilter>,
1294        iri_only_head: bool,
1295        head_prefixes: &[Vec<u8>],
1296    ) -> Result<Vec<EncodedTerm>, Status> {
1297        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1298        let graph_terms = graph_terms.to_vec();
1299        let start_after_term = start_after_term.cloned();
1300        let graph_name = graph_name.cloned();
1301        let head_prefixes = head_prefixes.to_vec();
1302        let partition = self.partition(PartitionAxis::from(permutation))?.clone();
1303        let terms = tokio::task::spawn_blocking(move || {
1304            partition.scan_axis_head(
1305                permutation,
1306                snapshot,
1307                limit,
1308                start_after_term.as_ref(),
1309                graph_name.as_ref(),
1310                &graph_terms,
1311                graph_allow,
1312                iri_only_head,
1313                &head_prefixes,
1314            )
1315        })
1316        .await
1317        .map_err(|join| blocking_join_error("storage", join))??;
1318        Ok(terms)
1319    }
1320
1321    #[allow(clippy::too_many_arguments)]
1322    async fn count_axis_heads(
1323        &self,
1324        permutation: IndexPermutation,
1325        snapshot: SnapshotId,
1326        graph_name: Option<&EncodedTerm>,
1327        graph_filter: Option<&GraphFilter>,
1328        iri_only_head: bool,
1329    ) -> Result<u64, Status> {
1330        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1331        let graph_terms = graph_terms.to_vec();
1332        let graph_name = graph_name.cloned();
1333        let partition = self.partition(PartitionAxis::from(permutation))?.clone();
1334        let total = tokio::task::spawn_blocking(move || {
1335            partition.count_axis_heads(
1336                permutation,
1337                snapshot,
1338                graph_name.as_ref(),
1339                &graph_terms,
1340                graph_allow,
1341                iri_only_head,
1342            )
1343        })
1344        .await
1345        .map_err(|join| blocking_join_error("storage", join))??;
1346        Ok(total)
1347    }
1348
1349    #[allow(clippy::too_many_arguments)]
1350    async fn scan_axis_head_counts(
1351        &self,
1352        permutation: IndexPermutation,
1353        snapshot: SnapshotId,
1354        limit: u64,
1355        start_after_term: Option<&EncodedTerm>,
1356        graph_name: Option<&EncodedTerm>,
1357        graph_filter: Option<&GraphFilter>,
1358        iri_only_head: bool,
1359    ) -> Result<Vec<AxisHeadCountHit>, Status> {
1360        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1361        let graph_terms = graph_terms.to_vec();
1362        let start_after_term = start_after_term.cloned();
1363        let graph_name = graph_name.cloned();
1364        let partition = self.partition(PartitionAxis::from(permutation))?.clone();
1365        let hits = tokio::task::spawn_blocking(move || {
1366            partition.scan_axis_head_counts(
1367                permutation,
1368                snapshot,
1369                limit,
1370                start_after_term.as_ref(),
1371                graph_name.as_ref(),
1372                &graph_terms,
1373                graph_allow,
1374                iri_only_head,
1375            )
1376        })
1377        .await
1378        .map_err(|join| blocking_join_error("storage", join))??;
1379        Ok(hits)
1380    }
1381}
1382
1383impl HexastoreFlush for LocalHexastoreClients {
1384    async fn flush_memtables(&self, axis: PartitionAxis) -> Result<(), Status> {
1385        let partition = self.partition(axis)?.clone();
1386        Ok(
1387            tokio::task::spawn_blocking(move || partition.flush_memtables())
1388                .await
1389                .map_err(|join| blocking_join_error("storage", join))??,
1390        )
1391    }
1392}
1393
1394impl HexastoreCompact for LocalHexastoreClients {
1395    async fn compact_range(&self, axis: PartitionAxis) -> Result<(), Status> {
1396        let partition = self.partition(axis)?.clone();
1397        Ok(
1398            tokio::task::spawn_blocking(move || partition.compact_range())
1399                .await
1400                .map_err(|join| blocking_join_error("storage", join))??,
1401        )
1402    }
1403}
1404
1405impl HexastoreStats for LocalHexastoreClients {
1406    async fn stats_profile(&self, axis: PartitionAxis) -> Result<Vec<u8>, Status> {
1407        let partition = self.partition(axis)?.clone();
1408        let profile = tokio::task::spawn_blocking(move || partition.shard_profile())
1409            .await
1410            .map_err(|join| blocking_join_error("storage", join))??;
1411        // Same contract as the gRPC partition handler: the CORE blob is
1412        // trimmed and carries EMPTY geo/temporal sections (they travel in
1413        // their own frames below). The in-process path could skip the trim,
1414        // but keeping the two transports byte-identical means the compute
1415        // rollup's frame merge cannot double-count a core-embedded map.
1416        Ok(to_bytes(&profile.capped_for_wire()))
1417    }
1418
1419    async fn geo_histogram(
1420        &self,
1421        axis: PartitionAxis,
1422        section: waratah_proto::pb::GeoHistogramSection,
1423    ) -> Result<Vec<u8>, Status> {
1424        let partition = self.partition(axis)?.clone();
1425        let profile = tokio::task::spawn_blocking(move || partition.shard_profile())
1426            .await
1427            .map_err(|join| blocking_join_error("storage", join))??;
1428        let trimmed = profile.capped_geo_histogram_for_wire();
1429        let frame = match section {
1430            waratah_proto::pb::GeoHistogramSection::Unspecified => {
1431                // Same contract as the gRPC partition handler: reject the
1432                // proto3 default instead of silently serving the fine frame
1433                // (in-process callers have no excuse — the trait passes the
1434                // enum directly).
1435                return Err(Status::invalid_argument(
1436                    "section must be FINE or COARSE; UNSPECIFIED names no frame",
1437                ));
1438            }
1439            waratah_proto::pb::GeoHistogramSection::Fine => waratah_stats::GeoCellHistogram {
1440                coarse: std::collections::BTreeMap::new(),
1441                ..trimmed
1442            },
1443            waratah_proto::pb::GeoHistogramSection::Coarse => waratah_stats::GeoCellHistogram {
1444                fine: std::collections::BTreeMap::new(),
1445                remainder: std::collections::BTreeMap::new(),
1446                ..trimmed
1447            },
1448        };
1449        let mut histogram = Vec::new();
1450        frame.encode_body(&mut histogram);
1451        Ok(histogram)
1452    }
1453
1454    async fn temporal_histogram(&self, axis: PartitionAxis) -> Result<Vec<u8>, Status> {
1455        let partition = self.partition(axis)?.clone();
1456        let profile = tokio::task::spawn_blocking(move || partition.shard_profile())
1457            .await
1458            .map_err(|join| blocking_join_error("storage", join))??;
1459        let mut histogram = Vec::new();
1460        profile.temporal_histogram.encode_body(&mut histogram);
1461        Ok(histogram)
1462    }
1463
1464    async fn text_seed_sketch(&self, axis: PartitionAxis) -> Result<Vec<u8>, Status> {
1465        // The sketch lives in the text index's sidecar, not the stats
1466        // profile; the partition serves it trimmed (the same contract as
1467        // the gRPC path).
1468        let partition = self.partition(axis)?.clone();
1469        let sketch = tokio::task::spawn_blocking(move || partition.text_seed_sketch_frame())
1470            .await
1471            .map_err(|join| blocking_join_error("storage", join))?;
1472        let mut sketch_bytes = Vec::new();
1473        if let Some(sketch) = sketch {
1474            sketch.encode_body(&mut sketch_bytes);
1475        }
1476        Ok(sketch_bytes)
1477    }
1478}
1479
1480impl HexastoreAdmin for LocalHexastoreClients {
1481    async fn describe(&self, axis: PartitionAxis) -> Result<HexastoreDescribe, Status> {
1482        let partition = self.partition(axis)?.clone();
1483        let response = tokio::task::spawn_blocking(move || partition.describe())
1484            .await
1485            .map_err(|join| blocking_join_error("storage", join))?;
1486        standalone_hexastore_describe(response)
1487    }
1488}
1489
1490impl HexastoreCatalog for LocalHexastoreClients {
1491    async fn list_named_graphs(&self, snapshot: SnapshotId) -> Result<Vec<EncodedTerm>, Status> {
1492        let partition = self.partition(PartitionAxis::S)?.clone();
1493        Ok(
1494            tokio::task::spawn_blocking(move || partition.list_named_graphs(snapshot))
1495                .await
1496                .map_err(|join| blocking_join_error("storage", join))??,
1497        )
1498    }
1499
1500    async fn add_named_graph(
1501        &self,
1502        graph: &EncodedTerm,
1503        commit_ts: CommitTs,
1504    ) -> Result<(), Status> {
1505        let partition = self.partition(PartitionAxis::S)?.clone();
1506        let graph = graph.clone();
1507        Ok(
1508            tokio::task::spawn_blocking(move || partition.add_named_graph(&graph, commit_ts))
1509                .await
1510                .map_err(|join| blocking_join_error("storage", join))??,
1511        )
1512    }
1513}
1514
1515impl StringRegister for LocalRegistryClients {
1516    async fn register_strings(&self, entries: &[(StrHash, String)]) -> Result<u64, Status> {
1517        let service = self.service.clone();
1518        let entries = entries.to_vec();
1519        Ok(
1520            tokio::task::spawn_blocking(move || service.register(entries))
1521                .await
1522                .map_err(|join| blocking_join_error("registry", join))??,
1523        )
1524    }
1525}
1526
1527impl StringResolve for LocalRegistryClients {
1528    async fn resolve_strings(&self, hashes: &[StrHash]) -> Result<Vec<Option<String>>, Status> {
1529        let service = self.service.clone();
1530        let hashes = hashes.to_vec();
1531        Ok(
1532            tokio::task::spawn_blocking(move || service.resolve(&hashes))
1533                .await
1534                .map_err(|join| blocking_join_error("registry", join))??,
1535        )
1536    }
1537}
1538
1539impl StringRegistryFlush for LocalRegistryClients {
1540    async fn flush_memtables(&self) -> Result<(), Status> {
1541        let service = self.service.clone();
1542        Ok(
1543            tokio::task::spawn_blocking(move || service.flush_memtables())
1544                .await
1545                .map_err(|join| blocking_join_error("registry", join))??,
1546        )
1547    }
1548}
1549
1550impl StringRegistryCompact for LocalRegistryClients {
1551    async fn compact_range(&self) -> Result<(), Status> {
1552        let service = self.service.clone();
1553        Ok(tokio::task::spawn_blocking(move || service.compact_range())
1554            .await
1555            .map_err(|join| blocking_join_error("registry", join))??)
1556    }
1557}
1558
1559impl RegistryAdmin for LocalRegistryClients {
1560    async fn describe(
1561        &self,
1562        _node: waratah_router::RegistryNodeId,
1563    ) -> Result<RegistryDescribe, Status> {
1564        let service = self.service.clone();
1565        let response = tokio::task::spawn_blocking(move || service.describe())
1566            .await
1567            .map_err(|join| blocking_join_error("registry", join))??;
1568        Ok(standalone_registry_describe(response))
1569    }
1570}
1571
1572fn standalone_hexastore_describe(
1573    response: pb::HexastoreDescribeResponse,
1574) -> Result<HexastoreDescribe, Status> {
1575    let axis = axis_from_proto(
1576        pb::PartitionAxis::try_from(response.axis).unwrap_or(pb::PartitionAxis::Unspecified),
1577    )
1578    .ok_or_else(|| Status::internal("describe returned unspecified axis"))?;
1579    Ok(HexastoreDescribe {
1580        axis,
1581        node_id: response.node_id,
1582        listen: response.listen,
1583        data_dir: response.data_dir,
1584        backend: standalone_backend_name(response.backend),
1585        version: response.version,
1586        repository_id: response.repository_id,
1587        serving: response.serving,
1588        metrics: standalone_lsm(response.metrics),
1589        geo_index_epoch: response.geo_index_epoch,
1590        temporal_index_epoch: response.temporal_index_epoch,
1591        temporal_rebuild_in_progress: response.temporal_rebuild_in_progress,
1592        geo_rebuild_in_progress: response.geo_rebuild_in_progress,
1593        text_index_epoch: response.text_index_epoch,
1594        text_index_fingerprint: response.text_index_fingerprint,
1595        text_index_terms: response.text_index_terms,
1596        text_rebuild_in_progress: response.text_rebuild_in_progress,
1597    })
1598}
1599
1600fn standalone_registry_describe(response: pb::RegistryDescribeResponse) -> RegistryDescribe {
1601    RegistryDescribe {
1602        node_id: response.node_id,
1603        listen: response.listen,
1604        data_dir: response.data_dir,
1605        backend: standalone_backend_name(response.backend),
1606        version: response.version,
1607        repository_id: response.repository_id,
1608        shard_count: response.shard_count,
1609        entry_count: response.entry_count,
1610        serving: response.serving,
1611        metrics: standalone_lsm(response.metrics),
1612    }
1613}
1614
1615fn standalone_backend_name(value: i32) -> String {
1616    match pb::StorageBackend::try_from(value).unwrap_or(pb::StorageBackend::Unspecified) {
1617        pb::StorageBackend::Memory => "memory".to_owned(),
1618        pb::StorageBackend::Rocksdb => "rocksdb".to_owned(),
1619        pb::StorageBackend::Unspecified => "unspecified".to_owned(),
1620    }
1621}
1622
1623fn standalone_lsm(metrics: Option<pb::LsmMetrics>) -> LsmMetricsView {
1624    let Some(m) = metrics else {
1625        return LsmMetricsView::default();
1626    };
1627    LsmMetricsView {
1628        estimate_live_data_bytes: m.estimate_live_data_bytes,
1629        estimate_num_keys: m.estimate_num_keys,
1630        total_sst_bytes: m.total_sst_bytes,
1631        memtable_bytes: m.memtable_bytes,
1632        num_running_compactions: m.num_running_compactions,
1633        num_running_flushes: m.num_running_flushes,
1634        open_total_puts: m.open_total_puts,
1635        compaction_event_count: m.compaction_event_count,
1636        named_graph_count: m.named_graph_count,
1637        entry_count: None,
1638        block_cache_capacity_bytes: m.block_cache_capacity_bytes,
1639        block_cache_usage_bytes: m.block_cache_usage_bytes,
1640    }
1641}
1642
1643/// Clone the broadcast filter's `Arc` term handle for the `'static` blocking
1644/// closure — no deep copy of the term list.
1645fn broadcast_args(
1646    filter: Option<&BroadcastFilter>,
1647) -> (Option<PatternSlot>, Option<Arc<[EncodedTerm]>>) {
1648    match filter {
1649        Some(filter) if !filter.terms.is_empty() => {
1650            (Some(filter.slot), Some(Arc::clone(&filter.terms)))
1651        }
1652        _ => (None, None),
1653    }
1654}
1655
1656#[cfg(test)]
1657mod tests {
1658    use super::*;
1659    use tokio_stream::StreamExt;
1660    use waratah_compute::{BlobStoreClient, HexastoreGeo};
1661    use waratah_storage::{
1662        CommitTs, CompareOp, CrsId, EncodedTerm, GeoCellInterval, GeoDatatype, GeoIndexPut,
1663        QuadSlot, ReplacePair, SlotComparison, SmallString, StorageOp, StrHash, VisibilityLabel,
1664        encode_term_bytes,
1665    };
1666
1667    /// A client over the in-memory backend — the topology is what is under
1668    /// test, so the engine underneath is irrelevant.
1669    fn client() -> LocalHexastoreClients {
1670        LocalHexastoreClients::open(
1671            &Backend::Memory,
1672            false,
1673            &waratah_storage::WarmState::empty(),
1674        )
1675        .expect("memory clients open")
1676    }
1677
1678    fn geo_put(cell_id: u64, term: &str) -> GeoIndexPut {
1679        GeoIndexPut {
1680            cell_id,
1681            term: encode_term_bytes(&EncodedTerm::NamedNode {
1682                iri_id: StrHash::new(term),
1683            }),
1684            commit_ts: CommitTs(7),
1685            op: StorageOp::Put,
1686            visibility: VisibilityLabel::default(),
1687            envelope: None,
1688        }
1689    }
1690
1691    /// Distinct candidates a geo scan returns for one cell interval.
1692    async fn scan_cells(client: &LocalHexastoreClients, interval: GeoCellInterval) -> usize {
1693        let mut stream =
1694            <LocalHexastoreClients as waratah_compute::HexastoreGeo>::geo_candidate_scan(
1695                client,
1696                &[interval],
1697                SnapshotId::latest(),
1698                None,
1699                0,
1700            )
1701            .await
1702            .expect("the scan itself must succeed");
1703        let mut terms = 0;
1704        while let Some(page) = stream.next().await {
1705            terms += page.expect("a scan page must decode").len();
1706        }
1707        terms
1708    }
1709
1710    /// The `waratah standalone` geo rebuild lease, end to end.
1711    ///
1712    /// All three lease RPCs used to fall through to the trait defaults'
1713    /// `unimplemented`, so the upgrade driver failed at startup and the geo
1714    /// rewrite's trust gate never opened — reads stayed unindexed with only a
1715    /// warning. This pins the client to the partition's own lease semantics:
1716    /// take (wipe + `upgrade_ts`), reject a second taker, renew, finish
1717    /// (stamp the epoch), then refuse a finish without a fresh lease.
1718    #[tokio::test]
1719    async fn standalone_geo_rebuild_lease_lifecycle() {
1720        let client = client();
1721        // Whole axis above cell 1: `max_cell_id == u64::MAX` is the interval
1722        // whose exclusive end bound the memory backend used to wrap to zero.
1723        let whole_axis = GeoCellInterval {
1724            min_cell_id: 1,
1725            max_cell_id: u64::MAX,
1726        };
1727
1728        // Sanity: the posting is visible before the rebuild, so the wipe
1729        // below is an observable, not an assertion about an empty store.
1730        client
1731            .put_geo_index(&[geo_put(1, "http://ex/geometry")])
1732            .await
1733            .expect("geo postings apply");
1734        assert_eq!(
1735            scan_cells(&client, whole_axis).await,
1736            1,
1737            "the posting must be scanable before the rebuild"
1738        );
1739
1740        // ---- Take the lease: the CF is wiped and upgrade_ts is the
1741        // partition's max commit_ts at lease take.
1742        let before = <LocalHexastoreClients as waratah_compute::HexastoreAdmin>::describe(
1743            &client,
1744            PartitionAxis::O,
1745        )
1746        .await
1747        .expect("describe");
1748        assert_eq!(before.geo_index_epoch, None, "no epoch before the rebuild");
1749        let (started, already, upgrade_ts) = client
1750            .rebuild_geo_index()
1751            .await
1752            .expect("taking a free lease succeeds");
1753        assert!(started && !already, "a free lease is taken by this caller");
1754        assert_eq!(
1755            scan_cells(&client, whole_axis).await,
1756            0,
1757            "taking the lease wipes the index — the client really called through"
1758        );
1759        // The wipe also dropped the LIVENESS marker, so a surviving epoch is
1760        // no longer a trust signal: the gate reads untrusted while the index
1761        // is empty. That is the whole point of the marker — a trusted-but-empty
1762        // index would answer every `geof:*` rewrite with zero rows.
1763        assert_eq!(
1764            <LocalHexastoreClients as waratah_compute::HexastoreAdmin>::describe(
1765                &client,
1766                PartitionAxis::O
1767            )
1768            .await
1769            .expect("describe")
1770            .geo_index_epoch,
1771            None,
1772            "mid-rebuild the index is empty, so it must read untrusted even \
1773             with an epoch on disk"
1774        );
1775
1776        // ---- A second taker loses, exactly as the gRPC responder reports it.
1777        let (second_started, second_already, second_ts) = client
1778            .rebuild_geo_index()
1779            .await
1780            .expect("a held lease is reported");
1781        assert!(
1782            !second_started && second_already,
1783            "a held, fresh lease reports already-in-progress"
1784        );
1785        assert_eq!(second_ts, 0, "a loser gets no upgrade_ts");
1786
1787        // ---- Renew keeps the lease alive for a slow walk.
1788        client
1789            .renew_geo_rebuild_lease()
1790            .await
1791            .expect("renewing a held lease succeeds");
1792
1793        // ---- Finish stamps the epoch and releases the lease. Nothing wrote
1794        // between take and finish, so the stamped epoch equals upgrade_ts.
1795        let epoch = client
1796            .finish_geo_index_rebuild()
1797            .await
1798            .expect("finishing under a held lease succeeds");
1799        assert_eq!(epoch, upgrade_ts, "nothing wrote between take and finish");
1800        let after = <LocalHexastoreClients as waratah_compute::HexastoreAdmin>::describe(
1801            &client,
1802            PartitionAxis::O,
1803        )
1804        .await
1805        .expect("describe");
1806        assert_eq!(after.geo_index_epoch, Some(epoch), "the epoch is stamped");
1807        assert!(
1808            !after.geo_rebuild_in_progress,
1809            "finishing releases the lease"
1810        );
1811
1812        // ---- A finish without a fresh lease is refused.
1813        assert!(
1814            client.finish_geo_index_rebuild().await.is_err(),
1815            "finishing twice is rejected: the grant is single-use"
1816        );
1817
1818        // ---- The released lease can be taken again (a second driver).
1819        let (again, _, _) = client
1820            .rebuild_geo_index()
1821            .await
1822            .expect("the released lease is free again");
1823        assert!(again, "the lease is reusable after finishing");
1824    }
1825
1826    /// Seed one `(subject, predicate, object)` quad into all three axes at
1827    /// ts 7 (the write fan-out's per-axis convention: every partition stores
1828    /// its own permutation rows of the same logical quad).
1829    async fn seed_quad_on_every_axis(
1830        client: &LocalHexastoreClients,
1831        subject: &EncodedTerm,
1832        predicate: &EncodedTerm,
1833        object: &EncodedTerm,
1834        ts: u64,
1835    ) {
1836        for axis in [PartitionAxis::S, PartitionAxis::P, PartitionAxis::O] {
1837            client
1838                .insert_quads(
1839                    axis,
1840                    &[QuadVersion {
1841                        quad: EncodedQuad {
1842                            subject: subject.clone(),
1843                            predicate: predicate.clone(),
1844                            object: object.clone(),
1845                            graph_name: EncodedTerm::DefaultGraph,
1846                        },
1847                        commit_ts: CommitTs(ts),
1848                        op: StorageOp::Put,
1849                        visibility: VisibilityLabel::default(),
1850                    }],
1851                )
1852                .await
1853                .expect("the seed insert must succeed");
1854        }
1855    }
1856
1857    /// Live objects of `(subject, predicate)` in the default graph at
1858    /// `snapshot`, read on the S axis (SPOG, object free).
1859    async fn live_objects(
1860        client: &LocalHexastoreClients,
1861        subject: &EncodedTerm,
1862        predicate: &EncodedTerm,
1863        snapshot: SnapshotId,
1864    ) -> Vec<EncodedTerm> {
1865        let pattern = EncodedTriplePattern {
1866            subject: Some(subject.clone()),
1867            predicate: Some(predicate.clone()),
1868            object: None,
1869            graph_name: Some(EncodedTerm::DefaultGraph),
1870        };
1871        client
1872            .scan_pattern(
1873                PartitionAxis::S,
1874                &pattern,
1875                snapshot,
1876                0,
1877                Some(IndexPermutation::Spog),
1878                None,
1879                None,
1880                None,
1881                false,
1882                IriOnlyMask::default(),
1883                waratah_proto::OMIT_NONE,
1884                // Liveness probe over a bound S+P pair: a drain at
1885                // limit 0, so the flag never changes anything.
1886                false,
1887            )
1888            .await
1889            .expect("the liveness scan must succeed")
1890            .rows
1891            .into_iter()
1892            .map(|row| row.object)
1893            .collect()
1894    }
1895
1896    fn point_1_2() -> EncodedTerm {
1897        EncodedTerm::LiteralPoint {
1898            x: 1.0,
1899            y: 2.0,
1900            crs: CrsId::Crs84,
1901            geo_datatype: GeoDatatype::WktLiteral,
1902        }
1903    }
1904
1905    /// The plugin-less `geo:wktLiteral` point this store would hold before
1906    /// the geo plugin ever ran (plain typed literal, no native encoding).
1907    fn orphan_point_1_2() -> EncodedTerm {
1908        EncodedTerm::SmallTypedLiteral {
1909            value: SmallString::try_from("POINT(1 2)").unwrap(),
1910            datatype_id: StrHash::new(waratah_storage::GEO_WKT_LITERAL),
1911        }
1912    }
1913
1914    fn has_location_terms() -> (EncodedTerm, EncodedTerm) {
1915        (
1916            EncodedTerm::NamedNode {
1917                iri_id: StrHash::new("http://ex/spatialThing"),
1918            },
1919            EncodedTerm::NamedNode {
1920                iri_id: StrHash::new("http://ex/hasLocation"),
1921            },
1922        )
1923    }
1924
1925    /// `replace_quads` on the standalone client used to fall through to the
1926    /// trait default's `unimplemented` — the startup geo auto-upgrade then
1927    /// failed on any store holding orphaned geo literals, warned, and stayed
1928    /// UNINDEXED on every start. Pin the S/P/O fan-out: one pair replaces on
1929    /// every axis (summed count 3), and the swap stays MVCC-atomic (below
1930    /// the replace ts the OLD object is live; at/above it ONLY the native
1931    /// one is).
1932    #[tokio::test]
1933    async fn standalone_replace_quads_swaps_objects_on_every_axis() {
1934        let client = client();
1935        let (subject, predicate) = has_location_terms();
1936        let old_object = orphan_point_1_2();
1937        let new_object = point_1_2();
1938        seed_quad_on_every_axis(&client, &subject, &predicate, &old_object, 7).await;
1939
1940        let pair = ReplacePair {
1941            subject: subject.clone(),
1942            predicate: predicate.clone(),
1943            graph_name: EncodedTerm::DefaultGraph,
1944            old_object: old_object.clone(),
1945            new_object: new_object.clone(),
1946        };
1947        let replaced = client
1948            .replace_quads(&[pair], CommitTs(8))
1949            .await
1950            .expect("replace_quads must be implemented on the local client");
1951        assert_eq!(replaced, 3, "one replaced row per axis");
1952
1953        assert_eq!(
1954            live_objects(&client, &subject, &predicate, SnapshotId(7)).await,
1955            vec![old_object],
1956            "below the replace ts the old typed row is still live"
1957        );
1958        assert_eq!(
1959            live_objects(&client, &subject, &predicate, SnapshotId::latest()).await,
1960            vec![new_object],
1961            "at/above the replace ts only the native row is live"
1962        );
1963    }
1964
1965    /// Pin the local registry's blob-store twin: `put_blobs` / `get_blobs`
1966    /// are the trait methods behind the geo upgrade's blob puts, the cover
1967    /// pass's fetches, and the write fan-out's oversized-blob chunk path.
1968    /// The store is content-addressed, so the id is the payload's own hash.
1969    #[tokio::test]
1970    async fn standalone_registry_blob_roundtrip() {
1971        let registry = LocalRegistryClients::open(
1972            &Backend::Memory,
1973            false,
1974            &waratah_storage::WarmState::empty(),
1975        )
1976        .expect("registry open");
1977        // The blob store is content-addressed: the id must BE the payload's
1978        // hash (a mismatched pair is rejected at put, exactly like the RPC).
1979        let payload: Arc<[u8]> = Arc::from(&b"\x01\x02\x03"[..]);
1980        let id = StrHash::from_bytes(&payload);
1981        registry
1982            .put_blobs(&[(id, Arc::clone(&payload))])
1983            .await
1984            .expect("put_blobs must be implemented on the local client");
1985        let got = registry
1986            .get_blobs(&[id, StrHash::from_bytes(b"http://ex/missing")])
1987            .await
1988            .expect("get_blobs must be implemented on the local client");
1989        assert_eq!(got[0].as_deref(), Some(&b"\x01\x02\x03"[..]));
1990        assert_eq!(got[1], None, "a miss resolves to None, not an error");
1991    }
1992
1993    /// End to end, the exact startup auto-upgrade scenario: a plugin-less
1994    /// `geo:wktLiteral` point is discovered by the head scan, planned from
1995    /// its inline lexical, REPLACED across the three axes (the driver used
1996    /// to die right there on the trait default), covered into the rebuilt
1997    /// index, and the run stamps the epoch.
1998    #[tokio::test]
1999    async fn standalone_geo_auto_upgrade_replaces_orphan_and_stamps_epoch() {
2000        let client = client();
2001        let registry = LocalRegistryClients::open(
2002            &Backend::Memory,
2003            false,
2004            &waratah_storage::WarmState::empty(),
2005        )
2006        .expect("registry open");
2007        let (subject, predicate) = has_location_terms();
2008        let orphan = orphan_point_1_2();
2009        seed_quad_on_every_axis(&client, &subject, &predicate, &orphan, 7).await;
2010
2011        let report = crate::geo_upgrade::drive_geo_upgrade(&client, &registry)
2012            .await
2013            .expect("the auto-upgrade must run on the local clients")
2014            .expect("no competing driver holds the lease");
2015        assert_eq!(report.orphans_upgraded, 1, "the orphan upgrades");
2016        assert_eq!(report.native_recovered, 0, "the store holds no natives");
2017
2018        assert_eq!(
2019            live_objects(&client, &subject, &predicate, SnapshotId::latest()).await,
2020            vec![point_1_2()],
2021            "the typed row is replaced by the native term"
2022        );
2023
2024        let epoch = <LocalHexastoreClients as waratah_compute::HexastoreAdmin>::describe(
2025            &client,
2026            PartitionAxis::O,
2027        )
2028        .await
2029        .expect("describe")
2030        .geo_index_epoch;
2031        assert_eq!(
2032            epoch,
2033            Some(8),
2034            "epoch = walked max (7) + 1, never the 0 counter"
2035        );
2036
2037        // The rebuilt index serves the upgraded term (whole-axis interval,
2038        // same convention as the lease test above).
2039        let whole_axis = GeoCellInterval {
2040            min_cell_id: 1,
2041            max_cell_id: u64::MAX,
2042        };
2043        assert_eq!(
2044            scan_cells(&client, whole_axis).await,
2045            1,
2046            "the rebuilt index serves the upgraded point"
2047        );
2048    }
2049
2050    /// The reported bug shape: rows land on disk through a path that never
2051    /// bumps the partition's commit-ts counter (offline import, or a previous
2052    /// process), so a fresh process opens with counter 0 beside data at ts 7.
2053    /// The lease ts is therefore 0 — and the two-stage upgrade must NOT use
2054    /// it: the swap ts is derived from the walked rows (7 + 1), the deletes
2055    /// dominate, and the stamped epoch is 8, never 0.
2056    #[tokio::test]
2057    async fn standalone_geo_auto_upgrade_survives_fresh_process_counter() {
2058        let client = client();
2059        let registry = LocalRegistryClients::open(
2060            &Backend::Memory,
2061            false,
2062            &waratah_storage::WarmState::empty(),
2063        )
2064        .expect("registry open");
2065        let (subject, predicate) = has_location_terms();
2066        let orphan = orphan_point_1_2();
2067
2068        // Seed the way an offline import would: straight through the storage
2069        // brick, bypassing the partition counter entirely.
2070        for axis in [PartitionAxis::S, PartitionAxis::P, PartitionAxis::O] {
2071            let partition = client
2072                .partitions
2073                .get(&axis)
2074                .expect("axis partition")
2075                .clone();
2076            partition
2077                .storage()
2078                .insert_encoded_quad_version(
2079                    &EncodedQuad {
2080                        subject: subject.clone(),
2081                        predicate: predicate.clone(),
2082                        object: orphan.clone(),
2083                        graph_name: EncodedTerm::DefaultGraph,
2084                    },
2085                    CommitTs(7),
2086                    StorageOp::Put,
2087                    VisibilityLabel::default(),
2088                )
2089                .expect("the plugin-less seed put must succeed");
2090        }
2091
2092        let report = crate::geo_upgrade::drive_geo_upgrade(&client, &registry)
2093            .await
2094            .expect("the auto-upgrade must run on the local clients")
2095            .expect("no competing driver holds the lease");
2096        assert_eq!(report.orphans_upgraded, 1, "the orphan upgrades");
2097
2098        assert_eq!(
2099            live_objects(&client, &subject, &predicate, SnapshotId::latest()).await,
2100            vec![point_1_2()],
2101            "the swap dominates the imported rows: typed row gone, no duplicates"
2102        );
2103
2104        let epoch = <LocalHexastoreClients as waratah_compute::HexastoreAdmin>::describe(
2105            &client,
2106            PartitionAxis::O,
2107        )
2108        .await
2109        .expect("describe")
2110        .geo_index_epoch;
2111        assert_eq!(
2112            epoch,
2113            Some(8),
2114            "epoch = walked max (7) + 1, never the 0 counter"
2115        );
2116    }
2117
2118    /// The in-process adapter must hand the comparison list to the walk on
2119    /// both transports, exactly as the proto client puts it on the request.
2120    /// `Eq` on named nodes is decidable from the shared 128-bit identity, so
2121    /// the comparison drops one of the two seeded rows and never needs the
2122    /// registry.
2123    #[tokio::test]
2124    async fn standalone_scan_applies_slot_comparisons_on_both_transports() {
2125        let client = client();
2126        let subject = EncodedTerm::NamedNode {
2127            iri_id: StrHash::new("http://ex/s"),
2128        };
2129        let predicate = EncodedTerm::NamedNode {
2130            iri_id: StrHash::new("http://ex/value"),
2131        };
2132        let keep = EncodedTerm::NamedNode {
2133            iri_id: StrHash::new("http://ex/keep"),
2134        };
2135        let drop = EncodedTerm::NamedNode {
2136            iri_id: StrHash::new("http://ex/drop"),
2137        };
2138        seed_quad_on_every_axis(&client, &subject, &predicate, &keep, 7).await;
2139        seed_quad_on_every_axis(&client, &subject, &predicate, &drop, 7).await;
2140
2141        let pattern = EncodedTriplePattern {
2142            subject: Some(subject),
2143            predicate: Some(predicate),
2144            object: None,
2145            graph_name: Some(EncodedTerm::DefaultGraph),
2146        };
2147        let comparisons = [SlotComparison {
2148            slot: QuadSlot::Object,
2149            op: CompareOp::Eq,
2150            term: keep.clone(),
2151        }];
2152
2153        let page = client
2154            .scan_pattern_with_comparisons(
2155                PartitionAxis::S,
2156                &pattern,
2157                SnapshotId(7),
2158                0,
2159                Some(IndexPermutation::Spog),
2160                None,
2161                None,
2162                None,
2163                false,
2164                IriOnlyMask::default(),
2165                &comparisons,
2166                waratah_proto::OMIT_NONE,
2167                false,
2168            )
2169            .await
2170            .expect("the unary comparison scan must succeed");
2171        assert_eq!(page.rows.len(), 1, "the unary path drops the other object");
2172        assert_eq!(page.rows[0].object, keep);
2173
2174        let mut frames = client
2175            .scan_pattern_stream_with_comparisons(
2176                PartitionAxis::S,
2177                &pattern,
2178                SnapshotId(7),
2179                0,
2180                Some(IndexPermutation::Spog),
2181                None,
2182                None,
2183                None,
2184                false,
2185                IriOnlyMask::default(),
2186                &comparisons,
2187                waratah_proto::OMIT_NONE,
2188                false,
2189            )
2190            .await
2191            .expect("the stream comparison scan must succeed");
2192        let mut rows = 0;
2193        while let Some(frame) = frames.next().await {
2194            rows += frame.expect("a frame must decode").rows.len();
2195        }
2196        assert_eq!(rows, 1, "the streamed path applies the same comparison");
2197    }
2198}