Skip to main content

waratah_compute/
clients.rs

1//! Client traits and tonic adapters for hexastore + string-registry RPCs.
2//!
3//! Traits keep the fan-out coordinator unit-testable with mock clients. The
4//! tonic adapters open channels from a [`ClusterConfig`]; Phase 8 can swap the
5//! hexastore adapter for a Raft-propose client without changing call sites.
6
7use std::collections::BTreeMap;
8use std::future::Future;
9use std::net::SocketAddr;
10use std::pin::Pin;
11use std::sync::Arc;
12
13use tokio_stream::{Stream, StreamExt};
14use tonic::transport::Channel;
15use waratah_proto::{
16    GRPC_MAX_MESSAGE_SIZE, HexastoreClient, PatternSlot, QuadVersion, StringRegistryClient,
17    count_mode_to_proto, insert_request, pb, permutation_to_proto, quad_from_proto_omitting,
18    register_request, resolve_request, scan_request_page, with_comparisons, with_omitted_slots,
19    with_verdict_wanted,
20};
21use waratah_router::{ClusterConfig, RegistryNodeId};
22use waratah_stats::PUSHDOWN_TERMS_LIMIT;
23use waratah_storage::IriOnlyMask;
24use waratah_storage::{
25    AxisHeadCountHit, DomainCountMode, DomainScanCountHit, DomainScanHit, EncodedQuad, EncodedTerm,
26    EncodedTriplePattern, GeoCellInterval, GeoEnvelope, GeoIndexPut, IndexPermutation,
27    PartitionAxis, ScanPage, SlotComparison, SnapshotId, StrHash, TemporalCellInterval,
28    TemporalIndexPut, TemporalQueryPredicate, TextIndexDoc, TextSearchRequest, TextSubjectRequest,
29    TextSubjectRow,
30};
31
32use crate::dataset::GraphFilter;
33use crate::error::ComputeError;
34
35/// Wire-level counters for `ScanPatternStream` transport diagnosis: how many
36/// stream items (and rows within them) the compute side received from the
37/// partition since the last [`take_wire_stream_totals`]. Global by design —
38/// read the delta around a single fetch in a single-query debug run, where
39/// fetches are effectively serial.
40static WIRE_STREAM_ITEMS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
41static WIRE_STREAM_ROWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
42
43/// Count one delivered stream item of `rows` rows at the transport boundary.
44pub fn note_wire_stream_item(rows: usize) {
45    WIRE_STREAM_ITEMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
46    WIRE_STREAM_ROWS.fetch_add(rows as u64, std::sync::atomic::Ordering::Relaxed);
47}
48
49/// Read-and-reset the wire counters: `(items, rows)` observed since the
50/// previous call.
51pub fn take_wire_stream_totals() -> (u64, u64) {
52    (
53        WIRE_STREAM_ITEMS.swap(0, std::sync::atomic::Ordering::Relaxed),
54        WIRE_STREAM_ROWS.swap(0, std::sync::atomic::Ordering::Relaxed),
55    )
56}
57
58/// Allow-list of encoded terms for one unbound pattern slot (Phase 9b broadcast).
59///
60/// `terms` is an `Arc` slice so the same list can be lent to every scan call
61/// of one logical scan (paged `next_batch` batches, retry attempts, parallel
62/// arms) by refcount, instead of deep-copying the term list per RPC.
63#[derive(Debug, Clone, PartialEq)]
64pub struct BroadcastFilter {
65    /// Slot to bind for each filter term.
66    pub slot: PatternSlot,
67    /// Distinct encoded terms pushed to storage.
68    pub terms: Arc<[EncodedTerm]>,
69}
70
71/// Storage-driven drain of one scan: pages of encoded quads until the
72/// partition exhausts the prefix (or the request `limit` rows have been
73/// emitted); an `Err` item terminates the stream.
74///
75/// This is the eager-path transport: unlike a unary [`HexastoreScan`]
76/// response it never has to fit in one gRPC message, but — unlike the
77/// OpenNode pull loop — paging is driven by the storage side, not by
78/// compute's remaining demand.
79///
80/// Each item carries the producing frame's [`ScanExhaustion`] verdict,
81/// present only when the request purchased one (`verdict_wanted`): a
82/// mid-walk data frame carries NOTHING (the walk being live at a frame
83/// boundary says nothing about what follows it), the limit-stop flush
84/// carries `Limited`, and the terminal frame (emitted just before
85/// end-of-stream) carries the walk's terminal verdict. A consumer that
86/// stops pulling before the terminal frame never holds a terminal
87/// claim — the conservative reading.
88pub type QuadPageStream = Pin<Box<dyn Stream<Item = Result<ScanPage, tonic::Status>> + Send>>;
89
90/// Re-frame one unary scan page as the frame sequence the
91/// `ScanPatternStream` protocol speaks, so a unary-backed transport (the
92/// trait's default [`HexastoreScan::scan_pattern_stream`], and test
93/// doubles built on it) is indistinguishable from the partition's walk: a
94/// COMPLETED walk's terminal verdict never rides a data frame — the rows
95/// go out as one verdict-less frame and the verdict follows as one EMPTY
96/// terminal frame — while a limit stop (`Limited`) and an unpurchased
97/// verdict (`None`) stay on the single frame, exactly as the partition's
98/// limit-stop flush does. Emitting the empty terminal frame here is
99/// deliberate: the consumer branches written for that shape (the driver
100/// funnel's terminal-frame break, bounded drains' last-frame-wins) must
101/// hold for every transport, not only the gRPC one.
102pub fn scan_page_as_wire_frames(page: ScanPage) -> QuadPageStream {
103    match page.exhausted {
104        Some(verdict) if verdict.is_terminal() => Box::pin(tokio_stream::iter(vec![
105            Ok(ScanPage {
106                rows: page.rows,
107                exhausted: None,
108            }),
109            Ok(ScanPage {
110                rows: Vec::new(),
111                exhausted: Some(verdict),
112            }),
113        ])),
114        _ => Box::pin(tokio_stream::once(Ok(page))),
115    }
116}
117
118/// Insert versioned quads onto one hexastore axis.
119pub trait HexastoreInsert: Send + Sync {
120    /// Atomically replace object terms on EVERY axis (the migration
121    /// primitive; see the proto contract). Returns the summed replaced
122    /// count across S/P/O.
123    fn replace_quads(
124        &self,
125        pairs: &[waratah_storage::ReplacePair],
126        commit_ts: waratah_storage::CommitTs,
127    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
128        let _ = (pairs, commit_ts);
129        std::future::ready(Err(tonic::Status::unimplemented(
130            "this client does not serve replace",
131        )))
132    }
133
134    /// Apply `versions` on `axis` (asserted in the request for axis isolation).
135    fn insert_quads(
136        &self,
137        axis: PartitionAxis,
138        versions: &[QuadVersion],
139    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
140}
141
142/// Max commit_ts among the versioned keys whose slot-0 head term falls under
143/// `head_prefixes` (every version counts; liveness is not evaluated, so the
144/// result only ever overestimates — safe for its one consumer, the geo
145/// upgrade's stage-1 swap-timestamp bound).
146pub trait HexastoreAxisHeadStats: Send + Sync {
147    /// Max commit_ts among the versioned keys whose slot-0 head term falls
148    /// under `head_prefixes`. Every version counts — liveness is not
149    /// evaluated — so the result only ever overestimates the true bound,
150    /// which is safe for the geo upgrade's stage-1 swap timestamp.
151    fn axis_head_max_commit_ts(
152        &self,
153        permutation: IndexPermutation,
154        head_prefixes: &[Vec<u8>],
155    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
156}
157
158/// Completion value of a [`HexastoreScan::scan_pattern_detached`] task:
159/// the fetched rows plus the walk's verdict (see the method doc for the
160/// last-read semantics).
161pub type DetachedScanOutcome =
162    Result<(Vec<EncodedQuad>, Option<waratah_storage::ScanExhaustion>), tonic::Status>;
163
164/// Scan a pattern on one hexastore axis, as of a snapshot.
165///
166/// Clients are cheap handles (`Clone` = refcount bump over shared channels)
167/// and may be moved across threads, which is what lets callers detach work:
168/// [`Self::scan_pattern_detached`] clones the client into a spawned task and
169/// returns a handle the caller can await while doing other work.
170#[allow(clippy::too_many_arguments)]
171pub trait HexastoreScan: Clone + Send + Sync + 'static {
172    /// Encoded rows matching `pattern`; `limit` of `0` is unlimited.
173    ///
174    /// `permutation` selects the axis-local index (`None` lets the partition
175    /// choose via [`EncodedTriplePattern::best_permutation`]).
176    ///
177    /// `filter` (Phase 9b) pushes a broadcast allow-list for one unbound slot.
178    /// `graph_filter` is residual G membership. Compute allow-lists map to
179    /// `graph_filter_allow = true`; block-lists (including `{DefaultGraph}`
180    /// for unbound `GRAPH ?g`) map to `false`. Omitted/`None` is an empty
181    /// block-list (block nothing). An empty allow-list is skip-RPC on compute.
182    /// `merge_default_graph` asks storage to emit each S/P/O once and rewrite G to
183    /// DefaultGraph (SPARQL default-graph RDF merge). `start_after` is then
184    /// exclusive on that triple (any G), not one logical quad.
185    /// `start_after` is an exclusive resume cursor (logical quad, not versioned
186    /// key). With a filter, concatenation order is `filter.terms`: earlier
187    /// terms are skipped, the matching term resumes at the cursor, later terms
188    /// scan from the start of their prefix.
189    ///
190    /// Returns the page plus the walk's own [`ScanExhaustion`] verdict —
191    /// the server-side fact that replaces the short-page inference
192    /// (`rows.len() < limit` cannot distinguish "stopped at the limit"
193    /// from "ran out, exactly at the limit").
194    ///
195    /// `verdict_wanted` is the consumer's declaration that a FULL page
196    /// will be followed by another request, and therefore that the walk
197    /// should spend look-ahead work reporting an honest terminal verdict
198    /// at exact limit boundaries: `true` keeps the walk running past a
199    /// full page until the next emitting row proves more data
200    /// (`Limited`) or the key range ends (terminal verdict); `false`
201    /// stops at the limit'th row, and the response carries no verdict at
202    /// all — the field is left unset, even when the walk's fact was free
203    /// to know. Callers whose demand equals their
204    /// whole remaining interest (an ASK / one-shot slice: no follow-up
205    /// request can exist) pass `false` so the walk never scans past its
206    /// last delivered row. Inert when `limit == 0` (a drain never fills
207    /// its page).
208    #[allow(clippy::too_many_arguments)]
209    fn scan_pattern(
210        &self,
211        axis: PartitionAxis,
212        pattern: &EncodedTriplePattern,
213        snapshot: SnapshotId,
214        limit: u64,
215        permutation: Option<IndexPermutation>,
216        filter: Option<&BroadcastFilter>,
217        graph_filter: Option<&GraphFilter>,
218        start_after: Option<&EncodedQuad>,
219        merge_default_graph: bool,
220        // Planner-derived `FILTER(isIRI(?x))` pushdown (S/O only).
221        iri_only: IriOnlyMask,
222        // Slots this call asks the partition to leave empty
223        // (`ScanPatternRequest.omitted_slots`). A non-zero mask is a
224        // requirement, not a hint: the receiver reassembles each masked
225        // slot from the request's own pattern term, or as the
226        // counted-presence sentinel for a dead slot — a value that differs
227        // from the stored term. An implementation that ignores the mask
228        // therefore does NOT return rows equal to an unmasked scan's
229        // whenever a dead slot is omitted, and a payload carrying bytes
230        // for a masked slot trips `quad_from_proto_omitting`'s debug
231        // assertion. Test doubles that hand back stored quads directly
232        // satisfy callers only because they never encode the payload.
233        omitted: u8,
234        verdict_wanted: bool,
235    ) -> impl Future<Output = Result<ScanPage, tonic::Status>> + Send;
236
237    /// [`Self::scan_pattern`] with slot comparison pushdown.
238    ///
239    /// `comparisons` is a conjunction of `slot OP term` constraints
240    /// (`SlotComparison`, S/P/O only) that the partition evaluates on the
241    /// encoded term before a row reaches the sink. The partition drops only
242    /// rows the comparison provably fails; every row it cannot decide is
243    /// kept for the compute-side `FILTER`, which remains authoritative. An
244    /// empty list is exactly [`Self::scan_pattern`], including its verdict
245    /// and page-limit accounting (the limit counts post-comparison rows).
246    ///
247    /// The default evaluates nothing and delegates to
248    /// [`Self::scan_pattern`]: a transport that does not understand the
249    /// list still returns **correct** rows, because the compute-side
250    /// `FILTER` stays in the plan and remains authoritative — the list is
251    /// a read reduction, not a correctness requirement. Production
252    /// transports (the gRPC client and the in-process standalone adapter)
253    /// override this to actually apply it.
254    #[allow(clippy::too_many_arguments)]
255    fn scan_pattern_with_comparisons(
256        &self,
257        axis: PartitionAxis,
258        pattern: &EncodedTriplePattern,
259        snapshot: SnapshotId,
260        limit: u64,
261        permutation: Option<IndexPermutation>,
262        filter: Option<&BroadcastFilter>,
263        graph_filter: Option<&GraphFilter>,
264        start_after: Option<&EncodedQuad>,
265        merge_default_graph: bool,
266        iri_only: IriOnlyMask,
267        comparisons: &[SlotComparison],
268        omitted: u8,
269        verdict_wanted: bool,
270    ) -> impl Future<Output = Result<ScanPage, tonic::Status>> + Send {
271        // Deliberately ignored: see the method doc. Correct, unfiltered.
272        let _ = comparisons;
273        async move {
274            self.scan_pattern(
275                axis,
276                pattern,
277                snapshot,
278                limit,
279                permutation,
280                filter,
281                graph_filter,
282                start_after,
283                merge_default_graph,
284                iri_only,
285                omitted,
286                verdict_wanted,
287            )
288            .await
289        }
290    }
291
292    /// Storage-driven drain of `pattern` as a [`QuadPageStream`].
293    ///
294    /// Same routing arguments and semantics as [`Self::scan_pattern`]
295    /// (`limit` of `0` is unlimited, `start_after` positions the first page),
296    /// but the implementation keeps streaming pages until the prefix is
297    /// exhausted (or `limit` rows have been emitted). Used by the fetch
298    /// service whenever compute cannot prove the result set fits in one
299    /// gRPC message (unbounded drains whose bound proof failed, and window
300    /// demands above [`crate::query::tunables::MAX_UNARY_SCAN_QUADS`]);
301    /// unary callers keep using [`Self::scan_pattern`] for demands within
302    /// that ceiling.
303    ///
304    /// The default adapts a unary implementation to the stream protocol's
305    /// own frame shapes ([`scan_page_as_wire_frames`]): a completed walk
306    /// arrives as one verdict-less data frame plus the empty terminal
307    /// frame carrying its verdict, and a limit stop keeps `Limited` on
308    /// the single frame. Correct for in-process transports with no
309    /// message-size ceiling; over-gRPC clients override it with the
310    /// `ScanPatternStream` RPC.
311    #[allow(clippy::too_many_arguments)]
312    fn scan_pattern_stream(
313        &self,
314        axis: PartitionAxis,
315        pattern: &EncodedTriplePattern,
316        snapshot: SnapshotId,
317        limit: u64,
318        permutation: Option<IndexPermutation>,
319        filter: Option<&BroadcastFilter>,
320        graph_filter: Option<&GraphFilter>,
321        start_after: Option<&EncodedQuad>,
322        merge_default_graph: bool,
323        iri_only: IriOnlyMask,
324        omitted: u8,
325        verdict_wanted: bool,
326    ) -> impl Future<Output = Result<QuadPageStream, tonic::Status>> + Send {
327        async move {
328            let rows = self
329                .scan_pattern(
330                    axis,
331                    pattern,
332                    snapshot,
333                    limit,
334                    permutation,
335                    filter,
336                    graph_filter,
337                    start_after,
338                    merge_default_graph,
339                    iri_only,
340                    omitted,
341                    verdict_wanted,
342                )
343                .await?;
344            Ok(scan_page_as_wire_frames(rows))
345        }
346    }
347
348    /// [`Self::scan_pattern_stream`] with slot comparison pushdown.
349    ///
350    /// Same request semantics as [`Self::scan_pattern_with_comparisons`];
351    /// each delivered frame carries the rows that survived the partition's
352    /// comparison evaluation, and the verdict/paging rules are the stream
353    /// protocol's.
354    ///
355    /// The default evaluates nothing and delegates to
356    /// [`Self::scan_pattern_stream`], keeping the transport's own frame
357    /// protocol. As with the unary fallback, the rows are correct without
358    /// the comparison — only the read reduction is lost. Production
359    /// transports override this to carry the list.
360    #[allow(clippy::too_many_arguments)]
361    fn scan_pattern_stream_with_comparisons(
362        &self,
363        axis: PartitionAxis,
364        pattern: &EncodedTriplePattern,
365        snapshot: SnapshotId,
366        limit: u64,
367        permutation: Option<IndexPermutation>,
368        filter: Option<&BroadcastFilter>,
369        graph_filter: Option<&GraphFilter>,
370        start_after: Option<&EncodedQuad>,
371        merge_default_graph: bool,
372        iri_only: IriOnlyMask,
373        comparisons: &[SlotComparison],
374        omitted: u8,
375        verdict_wanted: bool,
376    ) -> impl Future<Output = Result<QuadPageStream, tonic::Status>> + Send {
377        // Deliberately ignored: see the method doc. Correct, unfiltered.
378        let _ = comparisons;
379        async move {
380            self.scan_pattern_stream(
381                axis,
382                pattern,
383                snapshot,
384                limit,
385                permutation,
386                filter,
387                graph_filter,
388                start_after,
389                merge_default_graph,
390                iri_only,
391                omitted,
392                verdict_wanted,
393            )
394            .await
395        }
396    }
397
398    /// Fetch up to `limit` rows in a **detached task** that owns a clone of
399    /// the client; the returned handle completes with the rows and the
400    /// walk's verdict once the task finishes.
401    ///
402    /// Exists for the aggregation executor's pipelined loop: the caller holds
403    /// the handle while folding the *previous* page, so the fetch overlaps
404    /// compute instead of serializing after it. The transport follows the
405    /// same rule as the engine's bounded scans — demands at or under
406    /// `scan_batch` take one unary message, larger demands open the
407    /// storage-driven stream and drain exactly `limit` rows (the stream is
408    /// closed on completion or on drop, which cancels the partition side).
409    ///
410    /// The verdict is last-read: the unary branch carries the page's own
411    /// verdict; the stream branch carries the last frame's — a full drain
412    /// that purchased the verdict ends on its terminal frame, a drain that
413    /// broke at the limit holds the last verdict it read (`None` on a
414    /// mid-walk frame, `Limited` on a limit-stop flush), never a terminal
415    /// claim it did not see.
416    #[allow(clippy::too_many_arguments)]
417    fn scan_pattern_detached(
418        &self,
419        axis: PartitionAxis,
420        pattern: &EncodedTriplePattern,
421        snapshot: SnapshotId,
422        limit: u64,
423        permutation: Option<IndexPermutation>,
424        filter: Option<&BroadcastFilter>,
425        graph_filter: Option<&GraphFilter>,
426        start_after: Option<&EncodedQuad>,
427        merge_default_graph: bool,
428        iri_only: IriOnlyMask,
429        omitted: u8,
430        verdict_wanted: bool,
431    ) -> tokio::task::JoinHandle<DetachedScanOutcome> {
432        self.scan_pattern_detached_with_comparisons(
433            axis,
434            pattern,
435            snapshot,
436            limit,
437            permutation,
438            filter,
439            graph_filter,
440            start_after,
441            merge_default_graph,
442            iri_only,
443            &[],
444            omitted,
445            verdict_wanted,
446        )
447    }
448
449    /// [`Self::scan_pattern_detached`] with slot comparison pushdown.
450    ///
451    /// Same task and transport choice as the unfiltered sibling; a non-empty
452    /// list rides whichever transport the demand selects. The pipelined
453    /// aggregation loop uses this path, so a filtered aggregate scan must
454    /// come through here rather than the unfiltered wrapper.
455    #[allow(clippy::too_many_arguments)]
456    fn scan_pattern_detached_with_comparisons(
457        &self,
458        axis: PartitionAxis,
459        pattern: &EncodedTriplePattern,
460        snapshot: SnapshotId,
461        limit: u64,
462        permutation: Option<IndexPermutation>,
463        filter: Option<&BroadcastFilter>,
464        graph_filter: Option<&GraphFilter>,
465        start_after: Option<&EncodedQuad>,
466        merge_default_graph: bool,
467        iri_only: IriOnlyMask,
468        comparisons: &[SlotComparison],
469        omitted: u8,
470        verdict_wanted: bool,
471    ) -> tokio::task::JoinHandle<DetachedScanOutcome> {
472        let client = self.clone();
473        let pattern = pattern.clone();
474        let filter = filter.cloned();
475        let graph_filter = graph_filter.cloned();
476        let start_after = start_after.cloned();
477        let comparisons = comparisons.to_vec();
478        tokio::spawn(async move {
479            if limit as usize > crate::query::tunables::scan_batch() {
480                // Large demand: storage-driven stream capped at `limit` rows.
481                // Dropping the stream (consumer done or aborted) cancels the
482                // partition side; nothing blocks on a vanished receiver.
483                let mut pages = client
484                    .scan_pattern_stream_with_comparisons(
485                        axis,
486                        &pattern,
487                        snapshot,
488                        limit,
489                        permutation,
490                        filter.as_ref(),
491                        graph_filter.as_ref(),
492                        start_after.as_ref(),
493                        merge_default_graph,
494                        iri_only,
495                        &comparisons,
496                        omitted,
497                        verdict_wanted,
498                    )
499                    .await?;
500                let mut rows = Vec::new();
501                let mut verdict: Option<waratah_storage::ScanExhaustion> = None;
502                while let Some(page) = pages.next().await {
503                    let page = page?;
504                    verdict = page.exhausted;
505                    rows.extend(page.rows);
506                    if rows.len() >= limit as usize {
507                        break;
508                    }
509                }
510                Ok((rows, verdict))
511            } else {
512                client
513                    .scan_pattern_with_comparisons(
514                        axis,
515                        &pattern,
516                        snapshot,
517                        limit,
518                        permutation,
519                        filter.as_ref(),
520                        graph_filter.as_ref(),
521                        start_after.as_ref(),
522                        merge_default_graph,
523                        iri_only,
524                        &comparisons,
525                        omitted,
526                        verdict_wanted,
527                    )
528                    .await
529                    .map(|page| (page.rows, page.exhausted))
530            }
531        })
532    }
533
534    /// Count matching quads without returning rows; `limit` of `0` is unlimited.
535    ///
536    /// Same routing arguments as [`Self::scan_pattern`]. The partition walks
537    /// the prefix locally and returns a single integer.
538    #[allow(clippy::too_many_arguments)]
539    fn count_pattern(
540        &self,
541        axis: PartitionAxis,
542        pattern: &EncodedTriplePattern,
543        snapshot: SnapshotId,
544        limit: u64,
545        permutation: Option<IndexPermutation>,
546        filter: Option<&BroadcastFilter>,
547        graph_filter: Option<&GraphFilter>,
548        merge_default_graph: bool,
549    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
550
551    /// Constrained domain scan: distinct slot-1 head terms under each slot-0
552    /// constraint of `permutation` (POSG predicates→objects, SPOG
553    /// subjects→predicates, SOPG subjects→objects, OPSG objects→predicates).
554    ///
555    /// A permutation not owned by the serving partition returns
556    /// `UNIMPLEMENTED`. `limit` of `0` is unlimited; the exclusive resume
557    /// cursor is `(start_after_constraint, start_after_term)`. G is
558    /// existence-only: a head term is emitted when any visible Put quad
559    /// satisfies the graph window, and the graph slot is never returned.
560    #[allow(clippy::too_many_arguments)]
561    fn scan_domain(
562        &self,
563        permutation: IndexPermutation,
564        constraints: &[EncodedTerm],
565        snapshot: SnapshotId,
566        limit: u64,
567        start_after_constraint: Option<&EncodedTerm>,
568        start_after_term: Option<&EncodedTerm>,
569        graph_name: Option<&EncodedTerm>,
570        graph_filter: Option<&GraphFilter>,
571        // Planner-derived `FILTER(isIRI(?head))` pushdown.
572        iri_only_head: bool,
573    ) -> impl Future<Output = Result<Vec<DomainScanHit>, tonic::Status>> + Send;
574
575    /// Constrained domain count scan: run lengths of slot-1 head terms under
576    /// each slot-0 constraint of `permutation` — the same constraint/head
577    /// families and cursor semantics as [`Self::scan_domain`], but the graph
578    /// window applies per row (a head in `n` graphs of the window counts
579    /// `n`) unless `merge_default_graph` is set. Merge counts distinct S/P/O
580    /// prefixes and seeks past extra G. Zero-count runs are not emitted, and
581    /// each hit carries the multiplicity of its `(constraint, head)` pair.
582    #[allow(clippy::too_many_arguments)]
583    fn scan_domain_counts(
584        &self,
585        permutation: IndexPermutation,
586        constraints: &[EncodedTerm],
587        snapshot: SnapshotId,
588        limit: u64,
589        start_after_constraint: Option<&EncodedTerm>,
590        start_after_term: Option<&EncodedTerm>,
591        graph_name: Option<&EncodedTerm>,
592        graph_filter: Option<&GraphFilter>,
593        // Planner-derived `FILTER(isIRI(?head))` pushdown.
594        iri_only_head: bool,
595        merge_default_graph: bool,
596        // What one run-count increment represents.
597        mode: DomainCountMode,
598    ) -> impl Future<Output = Result<Vec<DomainScanCountHit>, tonic::Status>> + Send;
599
600    /// Bare axis head scan: distinct slot-0 head terms of the whole CF for
601    /// `permutation` (SPOG subjects, PSOG predicates, OPSG objects, TSG
602    /// classes). No anchor terms; same graph-window semantics and exclusive
603    /// single-term cursor as [`Self::scan_domain`]. `head_prefixes` are
604    /// opaque seek-union byte ranges: when non-empty, only heads whose
605    /// encoded bytes start with one of them are visited (empty =
606    /// unfiltered).
607    #[allow(clippy::too_many_arguments)]
608    fn scan_axis_head(
609        &self,
610        permutation: IndexPermutation,
611        snapshot: SnapshotId,
612        limit: u64,
613        start_after_term: Option<&EncodedTerm>,
614        graph_name: Option<&EncodedTerm>,
615        graph_filter: Option<&GraphFilter>,
616        // Planner-derived `FILTER(isIRI(?head))` pushdown.
617        iri_only_head: bool,
618        head_prefixes: &[Vec<u8>],
619    ) -> impl Future<Output = Result<Vec<EncodedTerm>, tonic::Status>> + Send;
620
621    /// Axis head count, `TOTAL` mode: the number of distinct slot-0 head
622    /// terms of the whole CF for `permutation`.
623    #[allow(clippy::too_many_arguments)]
624    fn count_axis_heads(
625        &self,
626        permutation: IndexPermutation,
627        snapshot: SnapshotId,
628        graph_name: Option<&EncodedTerm>,
629        graph_filter: Option<&GraphFilter>,
630        iri_only_head: bool,
631    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
632
633    /// Axis head count, `PER_HEAD` mode: per-head distinct slot-1 counts,
634    /// paged at head boundaries with an exclusive resume cursor.
635    #[allow(clippy::too_many_arguments)]
636    fn scan_axis_head_counts(
637        &self,
638        permutation: IndexPermutation,
639        snapshot: SnapshotId,
640        limit: u64,
641        start_after_term: Option<&EncodedTerm>,
642        graph_name: Option<&EncodedTerm>,
643        graph_filter: Option<&GraphFilter>,
644        iri_only_head: bool,
645    ) -> impl Future<Output = Result<Vec<AxisHeadCountHit>, tonic::Status>> + Send;
646}
647
648/// Flush MemTables to SST on one hexastore axis.
649pub trait HexastoreFlush: Send + Sync {
650    /// Ask `axis` to flush its RocksDB MemTables (no-op on memory backends).
651    fn flush_memtables(
652        &self,
653        axis: PartitionAxis,
654    ) -> impl Future<Output = Result<(), tonic::Status>> + Send;
655}
656
657/// Full-range compact on one hexastore axis.
658pub trait HexastoreCompact: Send + Sync {
659    /// Ask `axis` to compact both column families (no-op on memory backends).
660    fn compact_range(
661        &self,
662        axis: PartitionAxis,
663    ) -> impl Future<Output = Result<(), tonic::Status>> + Send;
664}
665
666/// Fetch a shard statistical profile (Phase 7).
667pub trait HexastoreStats: Send + Sync {
668    /// Serialized CORE [`waratah_stats::StatsProfile`] blob from `axis`
669    /// (geo/temporal sections empty — each rides its own frame below).
670    fn stats_profile(
671        &self,
672        axis: PartitionAxis,
673    ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
674
675    /// ONE geo cell-count histogram frame from `axis`: self-versioned
676    /// `GeoCellHistogram` section bytes carrying exactly the requested map
677    /// (the unrequested maps empty — subset-populated sections are valid
678    /// merge inputs on their own).
679    fn geo_histogram(
680        &self,
681        axis: PartitionAxis,
682        section: waratah_proto::pb::GeoHistogramSection,
683    ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
684
685    /// The temporal tick histogram frame from `axis`: self-versioned
686    /// `TickHistogram` section bytes (bounded by construction, untrimmed).
687    fn temporal_histogram(
688        &self,
689        axis: PartitionAxis,
690    ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
691
692    /// The text seed-population sketch frame from `axis`: self-versioned
693    /// `TextSeedSketch` section bytes, wire-trimmed deepest-first at the
694    /// partition. Empty bytes = no trusted sketch (never built, wiped, or
695    /// undecodable) — the caller keeps its unpriced estimate.
696    fn text_seed_sketch(
697        &self,
698        axis: PartitionAxis,
699    ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
700}
701
702/// Decoded hexastore `Describe` payload for the cluster snapshot.
703#[derive(Debug, Clone)]
704pub struct HexastoreDescribe {
705    /// Axis the process reports it owns.
706    pub axis: PartitionAxis,
707    /// Routing id.
708    pub node_id: String,
709    /// Advertised listen address.
710    pub listen: String,
711    /// RocksDB path (empty for memory).
712    pub data_dir: String,
713    /// `memory` or `rocksdb`.
714    pub backend: String,
715    /// Build version (`semver+git-describe`), from `HexastoreDescribeResponse`.
716    pub version: String,
717    /// Repository id.
718    pub repository_id: String,
719    /// Process is serving RPCs.
720    pub serving: bool,
721    /// LSM / process counters.
722    pub metrics: crate::cluster::LsmMetricsView,
723    /// Rebuild epoch of the O-axis geometry index. `None` = never stamped
724    /// (S/P partitions, or O before the first rebuild) — the planner treats
725    /// a missing epoch as trusted.
726    pub geo_index_epoch: Option<u64>,
727    /// Rebuild epoch of the O-axis temporal index. `None` = UNTRUSTED (the
728    /// compute auto-rebuild triggers on it at startup).
729    pub temporal_index_epoch: Option<u64>,
730    /// A temporal index rebuild is executing on this partition.
731    pub temporal_rebuild_in_progress: bool,
732    /// A FRESH geo rebuild lease is held on this partition.
733    pub geo_rebuild_in_progress: bool,
734    /// Rebuild epoch of the O-axis text index. `None` = UNTRUSTED: string
735    /// literals predate the plugin, so the compute auto-builds at startup
736    /// and the text rewrites stay off until the epoch lands.
737    pub text_index_epoch: Option<u64>,
738    /// Config fingerprint the text index was built with (empty when none).
739    pub text_index_fingerprint: String,
740    /// Live text-index documents (one per indexed literal); advisory.
741    pub text_index_terms: u64,
742    /// A FRESH text rebuild lease is held on this partition.
743    pub text_rebuild_in_progress: bool,
744}
745
746/// Decoded registry `Describe` payload.
747#[derive(Debug, Clone)]
748pub struct RegistryDescribe {
749    /// Routing id.
750    pub node_id: String,
751    /// Advertised listen address.
752    pub listen: String,
753    /// RocksDB path (empty for memory).
754    pub data_dir: String,
755    /// `memory` or `rocksdb`.
756    pub backend: String,
757    /// Build version (`semver+git-describe`), from `RegistryDescribeResponse`.
758    pub version: String,
759    /// Repository id.
760    pub repository_id: String,
761    /// In-process shard count.
762    pub shard_count: u64,
763    /// Entry count / estimate.
764    pub entry_count: Option<u64>,
765    /// Process is serving RPCs.
766    pub serving: bool,
767    /// LSM counters (empty on memory).
768    pub metrics: crate::cluster::LsmMetricsView,
769}
770
771/// Health + Describe for cluster HTTP (hexastore axes).
772pub trait HexastoreAdmin: Send + Sync {
773    /// Identity and operational metrics for `axis`.
774    fn describe(
775        &self,
776        axis: PartitionAxis,
777    ) -> impl Future<Output = Result<HexastoreDescribe, tonic::Status>> + Send;
778}
779
780/// Health + Describe for the string-registry process this compute dials.
781pub trait RegistryAdmin: Send + Sync {
782    /// Identity and operational metrics for `node`.
783    fn describe(
784        &self,
785        node: waratah_router::RegistryNodeId,
786    ) -> impl Future<Output = Result<RegistryDescribe, tonic::Status>> + Send;
787}
788
789/// S-axis named-graph catalog (empty graphs included; never the RDF default graph).
790///
791/// Coordinators call **S only**. P/O implementations return `UNIMPLEMENTED`.
792pub trait HexastoreCatalog: Send + Sync {
793    /// Named-node graph IRIs visible at `snapshot`.
794    fn list_named_graphs(
795        &self,
796        snapshot: SnapshotId,
797    ) -> impl Future<Output = Result<Vec<EncodedTerm>, tonic::Status>> + Send;
798
799    /// Insert an empty named graph, or no-op if already Present.
800    fn add_named_graph(
801        &self,
802        graph: &EncodedTerm,
803        commit_ts: waratah_storage::CommitTs,
804    ) -> impl Future<Output = Result<(), tonic::Status>> + Send;
805}
806
807/// O-axis geometry-index client (GeoSPARQL plugin path).
808///
809/// Apply-only writes + one streaming candidate drain. `GeoCandidateScan` is
810/// NEVER cursor-paged — one call drains the whole distinct candidate set.
811pub trait HexastoreGeo: Send + Sync {
812    /// Apply geometry-index postings on the O partition.
813    fn put_geo_index(
814        &self,
815        puts: &[GeoIndexPut],
816    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
817        let _ = puts;
818        std::future::ready(Err(tonic::Status::unimplemented(
819            "this client does not serve the geometry index",
820        )))
821    }
822
823    /// Delete every posting of one encoded geo term (rebuild support).
824    fn delete_geo_term(
825        &self,
826        term: &[u8],
827    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
828        let _ = term;
829        std::future::ready(Err(tonic::Status::unimplemented(
830            "this client does not serve the geometry index",
831        )))
832    }
833
834    /// Drain the merged cell-interval candidate scan as term pages.
835    /// `query_envelope` enables the partition-side AABB reject; `limit` of
836    /// `0` is unlimited (and is a per-drain cap, not a cursor).
837    #[allow(clippy::too_many_arguments)]
838    fn geo_candidate_scan(
839        &self,
840        intervals: &[GeoCellInterval],
841        snapshot: SnapshotId,
842        query_envelope: Option<GeoEnvelope>,
843        limit: u64,
844    ) -> impl Future<Output = Result<TermPageStream, tonic::Status>> + Send {
845        let _ = (intervals, snapshot, query_envelope, limit);
846        std::future::ready(Err(tonic::Status::unimplemented(
847            "this client does not serve the geometry index",
848        )))
849    }
850
851    /// Apply temporal-index postings on the O partition.
852    fn put_temporal_index(
853        &self,
854        puts: &[TemporalIndexPut],
855    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
856        let _ = puts;
857        std::future::ready(Err(tonic::Status::unimplemented(
858            "this client does not serve the temporal index",
859        )))
860    }
861
862    /// Drain the merged key-interval candidate scan as term pages. The
863    /// exact-interval `predicate` rejects postings partition-side; `limit`
864    /// of `0` is unlimited (and is a per-drain cap, not a cursor).
865    fn temporal_candidate_scan(
866        &self,
867        intervals: &[TemporalCellInterval],
868        snapshot: SnapshotId,
869        predicate: TemporalQueryPredicate,
870        limit: u64,
871    ) -> impl Future<Output = Result<TermPageStream, tonic::Status>> + Send {
872        let _ = (intervals, snapshot, predicate, limit);
873        std::future::ready(Err(tonic::Status::unimplemented(
874            "this client does not serve the temporal index",
875        )))
876    }
877
878    /// Begin the O-axis geo index rebuild: take the lease and wipe the CF.
879    /// Returns `(started, already_in_progress, upgrade_ts)` — the upgrade
880    /// ts is the partition's max commit_ts at lease take and is the ts
881    /// every ReplaceQuads row of this rebuild must carry; the CALLING
882    /// compute then drives the walk and finishes (unlike temporal, the
883    /// walk is not partition-owned).
884    fn rebuild_geo_index(
885        &self,
886    ) -> impl Future<Output = Result<(bool, bool, u64), tonic::Status>> + Send {
887        std::future::ready(Err(tonic::Status::unimplemented(
888            "this client does not serve the geometry index",
889        )))
890    }
891
892    /// Refresh the geo rebuild lease (the driver calls this per batch so a
893    /// slow walk is not taken over).
894    fn renew_geo_rebuild_lease(&self) -> impl Future<Output = Result<(), tonic::Status>> + Send {
895        std::future::ready(Err(tonic::Status::unimplemented(
896            "this client does not serve the geometry index",
897        )))
898    }
899
900    /// Finish the geo index rebuild: stamp the partition's max-seen
901    /// commit_ts as the epoch and release the lease. Returns the epoch.
902    fn finish_geo_index_rebuild(&self) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
903        std::future::ready(Err(tonic::Status::unimplemented(
904            "this client does not serve the geometry index",
905        )))
906    }
907
908    /// Trigger the O-axis temporal index rebuild. Returns `(started,
909    /// already_in_progress)` — see the proto contract; concurrent callers
910    /// poll Describe for the epoch instead of blocking here.
911    fn rebuild_temporal_index(
912        &self,
913        config: waratah_storage::DyadicCovererConfig,
914    ) -> impl Future<Output = Result<(bool, bool), tonic::Status>> + Send {
915        let _ = config;
916        std::future::ready(Err(tonic::Status::unimplemented(
917            "this client does not serve the temporal index",
918        )))
919    }
920
921    /// Append text-index documents on the O partition (text plugin). Sent
922    /// BEFORE the three axis `InsertQuads` calls, so a visible row never
923    /// lacks its document. The partition commits and reloads its reader
924    /// before acknowledging.
925    fn put_text_index(
926        &self,
927        docs: &[TextIndexDoc],
928    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
929        let _ = docs;
930        std::future::ready(Err(tonic::Status::unimplemented(
931            "this client does not serve the text index",
932        )))
933    }
934
935    /// Drain one text candidate request as term pages. One RPC drains the
936    /// whole distinct candidate set; `limit` of `0` is unlimited (and is a
937    /// per-drain guard that errors, not a cursor).
938    fn text_candidate_scan(
939        &self,
940        request: &TextSearchRequest,
941        snapshot: SnapshotId,
942    ) -> impl Future<Output = Result<TermPageStream, tonic::Status>> + Send {
943        let _ = (request, snapshot);
944        std::future::ready(Err(tonic::Status::unimplemented(
945            "this client does not serve the text index",
946        )))
947    }
948
949    /// Resolve one text search to DISTINCT subjects on the O partition.
950    ///
951    /// The partition runs ONE candidate search over the request's whole
952    /// predicate set (a single OR of term filters on the stored predicate),
953    /// resolves each matched literal against the OPSG index at `snapshot`, and
954    /// streams `(subject, graph)` rows; the graph column is present only when
955    /// the request asks for it. `limit` of `0` is unlimited (a guard on the
956    /// emitted distinct rows that ERRORS, not a cursor). Empty `predicates`
957    /// means no predicate restriction: the literals still come only from the
958    /// text index, but each is read under any predicate.
959    fn text_subject_scan(
960        &self,
961        request: &TextSubjectRequest,
962        snapshot: SnapshotId,
963    ) -> impl Future<Output = Result<SubjectRowStream, tonic::Status>> + Send {
964        let _ = (request, snapshot);
965        std::future::ready(Err(tonic::Status::unimplemented(
966            "this client does not serve the text index",
967        )))
968    }
969
970    /// Open-or-create the text index with an explicit config, optionally
971    /// wipe, and take the rebuild lease. Returns `(started,
972    /// already_in_progress, lease_token)` — the token is the caller's proof
973    /// of lease ownership (non-zero exactly when started); every renew /
974    /// finish must carry it. The calling compute drives the walk and
975    /// finishes with [`Self::finish_text_index_rebuild`].
976    fn rebuild_text_index(
977        &self,
978        analyzer: &str,
979        seed_chars: u32,
980        fingerprint: &str,
981        wipe: bool,
982    ) -> impl Future<Output = Result<(bool, bool, u64), tonic::Status>> + Send {
983        let _ = (analyzer, seed_chars, fingerprint, wipe);
984        std::future::ready(Err(tonic::Status::unimplemented(
985            "this client does not serve the text index",
986        )))
987    }
988
989    /// Refresh the text rebuild lease (driver keepalive per batch). Rejected
990    /// unless `lease_token` identifies the current fresh lease.
991    fn renew_text_rebuild_lease(
992        &self,
993        lease_token: u64,
994    ) -> impl Future<Output = Result<(), tonic::Status>> + Send {
995        let _ = lease_token;
996        std::future::ready(Err(tonic::Status::unimplemented(
997            "this client does not serve the text index",
998        )))
999    }
1000
1001    /// Finish the text index rebuild: release the lease, and — when `stamp`
1002    /// — stamp the partition's max-seen commit_ts as the epoch. `stamp =
1003    /// false` releases without stamping (the index stays untrusted). Returns
1004    /// the stamped epoch (0 when not stamping). Rejected unless
1005    /// `lease_token` identifies the current fresh lease.
1006    fn finish_text_index_rebuild(
1007        &self,
1008        lease_token: u64,
1009        stamp: bool,
1010    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
1011        let _ = (lease_token, stamp);
1012        std::future::ready(Err(tonic::Status::unimplemented(
1013            "this client does not serve the text index",
1014        )))
1015    }
1016}
1017
1018/// Streaming page of distinct candidate terms.
1019pub type TermPageStream =
1020    Pin<Box<dyn Stream<Item = Result<Vec<EncodedTerm>, tonic::Status>> + Send>>;
1021
1022/// Streaming page of resolved `(subject, graph)` rows.
1023pub type SubjectRowStream =
1024    Pin<Box<dyn Stream<Item = Result<Vec<TextSubjectRow>, tonic::Status>> + Send>>;
1025
1026/// Decode one wire subject row.
1027///
1028/// `graph` PRESENCE is the request's `return_graph` echo, not a length test:
1029/// the RDF default graph encodes to zero bytes, so `Some(empty)` is a real
1030/// graph term and `None` means the column was not requested.
1031fn text_subject_row_from_proto(row: &pb::TextSubjectRow) -> Result<TextSubjectRow, tonic::Status> {
1032    let subject = waratah_proto::term_from_bytes(&row.subject)
1033        .map_err(|error| tonic::Status::internal(error.to_string()))?;
1034    let graph = row
1035        .graph
1036        .as_deref()
1037        .map(waratah_proto::term_from_bytes)
1038        .transpose()
1039        .map_err(|error| tonic::Status::internal(error.to_string()))?;
1040    Ok(TextSubjectRow { subject, graph })
1041}
1042
1043/// Content-addressed blob client against the registry process.
1044///
1045/// Compute-only (query residual / output materialization on the read side,
1046/// write fan-out on the write side); hexastore partitions never fetch
1047/// blobs. Payloads travel as `Arc<[u8]>` so callers (write fan-out, cache
1048/// pre-warm) share one buffer across batch frames and retry attempts
1049/// instead of copying.
1050///
1051/// # Write-path contract
1052///
1053/// - [`Self::put_blobs`] sends whole blobs batched into ONE unary request.
1054///   The caller frames batches under [`crate::PUT_BLOBS_BATCH_BYTES`]
1055///   so every request fits the gRPC message ceiling. The server commits
1056///   the batch atomically: every content hash is validated before anything
1057///   is written, and one index commit carries the whole batch — so a
1058///   failed call leaves no index entries, and retrying the **whole
1059///   batch** idempotently is safe under content addressing (every retry
1060///   re-validates the same content hash; ids that already exist skip).
1061/// - [`Self::put_blob_chunks`] streams ONE oversized blob chunk-by-chunk
1062///   under the frame budget (blobs above the batch budget).
1063///
1064/// In both cases a failure returns `Err` and the caller retries per its
1065/// retry policy; a blob must never be visible at its content address
1066/// without full validation.
1067pub trait BlobStoreClient: Send + Sync {
1068    /// Stream one blob's chunks under the gRPC message budget (legacy path
1069    /// for blobs above the `PutBlobs` batch budget; the 64 MiB blob size
1070    /// limit is enforced server-side at assembly).
1071    fn put_blob_chunks(
1072        &self,
1073        blob_id: StrHash,
1074        payload: Arc<[u8]>,
1075    ) -> impl Future<Output = Result<(), tonic::Status>> + Send {
1076        let _ = (blob_id, payload);
1077        std::future::ready(Err(tonic::Status::unimplemented(
1078            "this client has no blob store",
1079        )))
1080    }
1081
1082    /// Put a batch of whole blobs in one unary request (see the trait docs
1083    /// for the idempotency / atomicity contract). Batches are framed by the
1084    /// caller under [`crate::PUT_BLOBS_BATCH_BYTES`].
1085    fn put_blobs(
1086        &self,
1087        blobs: &[(StrHash, Arc<[u8]>)],
1088    ) -> impl Future<Output = Result<(), tonic::Status>> + Send {
1089        let _ = blobs;
1090        std::future::ready(Err(tonic::Status::unimplemented(
1091            "this client has no blob store",
1092        )))
1093    }
1094
1095    /// Batched get: payloads aligned with `ids` (`None` = miss).
1096    fn get_blobs(
1097        &self,
1098        ids: &[StrHash],
1099    ) -> impl Future<Output = Result<Vec<Option<Vec<u8>>>, tonic::Status>> + Send {
1100        let _ = ids;
1101        std::future::ready(Err(tonic::Status::unimplemented(
1102            "this client has no blob store",
1103        )))
1104    }
1105}
1106
1107/// Flush MemTables on the string-registry process (no-op on memory).
1108pub trait StringRegistryFlush: Send + Sync {
1109    /// Ask every connected registry node to flush its MemTables.
1110    fn flush_memtables(&self) -> impl Future<Output = Result<(), tonic::Status>> + Send;
1111}
1112
1113/// Full-range compact on the string-registry process (no-op on memory).
1114pub trait StringRegistryCompact: Send + Sync {
1115    /// Ask every connected registry node to compact its dictionary CF.
1116    fn compact_range(&self) -> impl Future<Output = Result<(), tonic::Status>> + Send;
1117}
1118
1119/// Register hashed strings on the string-registry process(es).
1120pub trait StringRegister: Send + Sync {
1121    /// Persist `(hash, raw)` pairs; multi-node registries group by hash ownership.
1122    fn register_strings(
1123        &self,
1124        entries: &[(StrHash, String)],
1125    ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
1126}
1127
1128/// Resolve hashed strings for final output bindings (late materialization).
1129pub trait StringResolve: Send + Sync {
1130    /// Raw strings positionally aligned with `hashes`; `None` marks an unknown hash.
1131    fn resolve_strings(
1132        &self,
1133        hashes: &[StrHash],
1134    ) -> impl Future<Output = Result<Vec<Option<String>>, tonic::Status>> + Send;
1135}
1136
1137/// Tonic clients for all three hexastore axes.
1138#[derive(Debug, Clone)]
1139pub struct GrpcHexastoreClients {
1140    clients: BTreeMap<&'static str, HexastoreClient<Channel>>,
1141    /// Dedicated connections for `ScanPatternStream` walks. A driver walk
1142    /// stalls between compute-side batches (that stall *is* the
1143    /// backpressure), leaving unread frames outstanding up to the h2
1144    /// connection-level flow-control window. Sharing that window with
1145    /// everything else deadlocks: once it is exhausted by the stalled walk,
1146    /// the partition cannot send *any* response on the connection —
1147    /// including the very probe the join loop is awaiting. Separate
1148    /// connections confine the stall to the walk.
1149    stream_clients: BTreeMap<&'static str, HexastoreClient<Channel>>,
1150}
1151
1152impl GrpcHexastoreClients {
1153    /// Connect to S, P, and O from `config`.
1154    pub async fn connect(config: &ClusterConfig) -> Result<Self, ComputeError> {
1155        let mut clients = BTreeMap::new();
1156        let mut stream_clients = BTreeMap::new();
1157        for axis in PartitionAxis::ALL {
1158            let addr = config.hexastore(axis)?;
1159            // Pin the response-decode ceiling so the eager path's
1160            // unary-vs-stream decision runs against a known limit instead
1161            // of whatever tonic's default happens to be. NODELAY is set
1162            // explicitly (kernel default is Nagle-on; hyper-util sets it on
1163            // connect today, but the request/response latency of a
1164            // distributed query must not depend on that default).
1165            let endpoint =
1166                tonic::transport::Endpoint::from_shared(http_url(addr))?.tcp_nodelay(true);
1167            let client = HexastoreClient::connect(endpoint)
1168                .await?
1169                .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
1170            clients.insert(axis.as_str(), client);
1171            // A second connection per axis for stream walks (see the field
1172            // doc): same ceiling, same NODELAY.
1173            let stream_endpoint =
1174                tonic::transport::Endpoint::from_shared(http_url(addr))?.tcp_nodelay(true);
1175            let stream_client = HexastoreClient::connect(stream_endpoint)
1176                .await?
1177                .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
1178            stream_clients.insert(axis.as_str(), stream_client);
1179        }
1180        Ok(Self {
1181            clients,
1182            stream_clients,
1183        })
1184    }
1185
1186    fn client(&self, axis: PartitionAxis) -> HexastoreClient<Channel> {
1187        self.clients
1188            .get(axis.as_str())
1189            .expect("ClusterConfig validation requires every axis")
1190            .clone()
1191    }
1192
1193    fn stream_client(&self, axis: PartitionAxis) -> HexastoreClient<Channel> {
1194        self.stream_clients
1195            .get(axis.as_str())
1196            .expect("ClusterConfig validation requires every axis")
1197            .clone()
1198    }
1199}
1200
1201impl HexastoreInsert for GrpcHexastoreClients {
1202    async fn insert_quads(
1203        &self,
1204        axis: PartitionAxis,
1205        versions: &[QuadVersion],
1206    ) -> Result<u64, tonic::Status> {
1207        let mut client = self.client(axis);
1208        let response = client.insert_quads(insert_request(axis, versions)).await?;
1209        Ok(response.into_inner().inserted)
1210    }
1211    async fn replace_quads(
1212        &self,
1213        pairs: &[waratah_storage::ReplacePair],
1214        commit_ts: waratah_storage::CommitTs,
1215    ) -> Result<u64, tonic::Status> {
1216        // Byte-framed chunks (the InsertQuads convention), then one call
1217        // per axis — each partition translates the pairs into its own
1218        // permutations and applies its own rows in one batch.
1219        const FRAME_BUDGET: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE / 2;
1220        let mut frames: Vec<Vec<pb::replace_quads_request::Pair>> = vec![Vec::new()];
1221        let mut frame_bytes = 0usize;
1222        for pair in pairs {
1223            let proto_pair = waratah_proto::replace_pair_to_proto(pair);
1224            let bytes = proto_pair.subject.len()
1225                + proto_pair.predicate.len()
1226                + proto_pair.graph_name.len()
1227                + proto_pair.old_object.len()
1228                + proto_pair.new_object.len()
1229                + 16;
1230            if frame_bytes + bytes > FRAME_BUDGET && !frames.last().unwrap().is_empty() {
1231                frames.push(Vec::new());
1232                frame_bytes = 0;
1233            }
1234            frame_bytes += bytes;
1235            frames.last_mut().unwrap().push(proto_pair);
1236        }
1237        let mut replaced = 0u64;
1238        for frame in &frames {
1239            let mut s_client = self.client(PartitionAxis::S);
1240            let mut p_client = self.client(PartitionAxis::P);
1241            let mut o_client = self.client(PartitionAxis::O);
1242            let make_request = || pb::ReplaceQuadsRequest {
1243                pairs: frame.clone(),
1244                commit_ts: commit_ts.0,
1245            };
1246            let (s, p, o) = tokio::join!(
1247                s_client.replace_quads(make_request()),
1248                p_client.replace_quads(make_request()),
1249                o_client.replace_quads(make_request()),
1250            );
1251            replaced += s?.into_inner().replaced;
1252            replaced += p?.into_inner().replaced;
1253            replaced += o?.into_inner().replaced;
1254        }
1255        Ok(replaced)
1256    }
1257}
1258
1259impl HexastoreAxisHeadStats for GrpcHexastoreClients {
1260    async fn axis_head_max_commit_ts(
1261        &self,
1262        permutation: IndexPermutation,
1263        head_prefixes: &[Vec<u8>],
1264    ) -> Result<u64, tonic::Status> {
1265        let response = self
1266            .client(PartitionAxis::from(permutation))
1267            .axis_head_max_commit_ts(pb::AxisHeadMaxCommitTsRequest {
1268                permutation: permutation_to_proto(permutation) as i32,
1269                head_prefixes: head_prefixes.to_vec(),
1270            })
1271            .await?;
1272        Ok(response.into_inner().max_commit_ts)
1273    }
1274}
1275
1276impl HexastoreScan for GrpcHexastoreClients {
1277    #[allow(clippy::too_many_arguments)]
1278    async fn scan_pattern(
1279        &self,
1280        axis: PartitionAxis,
1281        pattern: &EncodedTriplePattern,
1282        snapshot: SnapshotId,
1283        limit: u64,
1284        permutation: Option<IndexPermutation>,
1285        filter: Option<&BroadcastFilter>,
1286        graph_filter: Option<&GraphFilter>,
1287        start_after: Option<&EncodedQuad>,
1288        merge_default_graph: bool,
1289        iri_only: IriOnlyMask,
1290        omitted: u8,
1291        verdict_wanted: bool,
1292    ) -> Result<ScanPage, tonic::Status> {
1293        self.scan_pattern_with_comparisons(
1294            axis,
1295            pattern,
1296            snapshot,
1297            limit,
1298            permutation,
1299            filter,
1300            graph_filter,
1301            start_after,
1302            merge_default_graph,
1303            iri_only,
1304            &[],
1305            omitted,
1306            verdict_wanted,
1307        )
1308        .await
1309    }
1310
1311    #[allow(clippy::too_many_arguments)]
1312    async fn scan_pattern_with_comparisons(
1313        &self,
1314        axis: PartitionAxis,
1315        pattern: &EncodedTriplePattern,
1316        snapshot: SnapshotId,
1317        limit: u64,
1318        permutation: Option<IndexPermutation>,
1319        filter: Option<&BroadcastFilter>,
1320        graph_filter: Option<&GraphFilter>,
1321        start_after: Option<&EncodedQuad>,
1322        merge_default_graph: bool,
1323        iri_only: IriOnlyMask,
1324        comparisons: &[SlotComparison],
1325        omitted: u8,
1326        verdict_wanted: bool,
1327    ) -> Result<ScanPage, tonic::Status> {
1328        let mut client = self.client(axis);
1329        // `?` converts a rejected comparison list (graph slot, empty term)
1330        // into `INVALID_ARGUMENT` before anything reaches the wire.
1331        let request = with_comparisons(
1332            pattern_scan_request(
1333                pattern,
1334                snapshot,
1335                limit,
1336                permutation,
1337                filter,
1338                graph_filter,
1339                start_after,
1340                merge_default_graph,
1341                iri_only,
1342            ),
1343            comparisons,
1344        )?;
1345        let response = client
1346            .scan_pattern(with_verdict_wanted(
1347                with_omitted_slots(request, omitted),
1348                verdict_wanted,
1349            ))
1350            .await?;
1351        let inner = response.into_inner();
1352        let rows = inner
1353            .quads
1354            .iter()
1355            .map(|quad| {
1356                quad_from_proto_omitting(quad, pattern, omitted)
1357                    .map_err(|e| tonic::Status::internal(e.to_string()))
1358            })
1359            .collect::<Result<Vec<_>, _>>()?;
1360        Ok(ScanPage {
1361            rows,
1362            exhausted: waratah_proto::scan_exhaustion_from_proto_opt(inner.exhausted),
1363        })
1364    }
1365
1366    #[allow(clippy::too_many_arguments)]
1367    async fn scan_pattern_stream(
1368        &self,
1369        axis: PartitionAxis,
1370        pattern: &EncodedTriplePattern,
1371        snapshot: SnapshotId,
1372        limit: u64,
1373        permutation: Option<IndexPermutation>,
1374        filter: Option<&BroadcastFilter>,
1375        graph_filter: Option<&GraphFilter>,
1376        start_after: Option<&EncodedQuad>,
1377        merge_default_graph: bool,
1378        iri_only: IriOnlyMask,
1379        omitted: u8,
1380        verdict_wanted: bool,
1381    ) -> Result<QuadPageStream, tonic::Status> {
1382        self.scan_pattern_stream_with_comparisons(
1383            axis,
1384            pattern,
1385            snapshot,
1386            limit,
1387            permutation,
1388            filter,
1389            graph_filter,
1390            start_after,
1391            merge_default_graph,
1392            iri_only,
1393            &[],
1394            omitted,
1395            verdict_wanted,
1396        )
1397        .await
1398    }
1399
1400    #[allow(clippy::too_many_arguments)]
1401    async fn scan_pattern_stream_with_comparisons(
1402        &self,
1403        axis: PartitionAxis,
1404        pattern: &EncodedTriplePattern,
1405        snapshot: SnapshotId,
1406        limit: u64,
1407        permutation: Option<IndexPermutation>,
1408        filter: Option<&BroadcastFilter>,
1409        graph_filter: Option<&GraphFilter>,
1410        start_after: Option<&EncodedQuad>,
1411        merge_default_graph: bool,
1412        iri_only: IriOnlyMask,
1413        comparisons: &[SlotComparison],
1414        omitted: u8,
1415        verdict_wanted: bool,
1416    ) -> Result<QuadPageStream, tonic::Status> {
1417        // The dedicated stream connection: this walk stalls between
1418        // compute-side batches, and its outstanding unread frames must not
1419        // exhaust a window shared with other requests (see the
1420        // `stream_clients` field doc).
1421        let mut client = self.stream_client(axis);
1422        let request = with_comparisons(
1423            pattern_scan_request(
1424                pattern,
1425                snapshot,
1426                limit,
1427                permutation,
1428                filter,
1429                graph_filter,
1430                start_after,
1431                merge_default_graph,
1432                iri_only,
1433            ),
1434            comparisons,
1435        )?;
1436        let response = client
1437            .scan_pattern_stream(with_verdict_wanted(
1438                with_omitted_slots(request, omitted),
1439                verdict_wanted,
1440            ))
1441            .await?;
1442        // Each stream item decodes through the same path as the unary
1443        // response; a decode failure surfaces as one terminating Err page.
1444        // The pattern is cloned into the stream because reassembling an
1445        // omitted slot reads the term this request bound. Each frame's
1446        // verdict rides along (mid-walk data frames carry nothing; the
1447        // limit-stop flush carries Limited; the terminal frame carries
1448        // the walk's verdict — last-frame-wins on the consumer).
1449        let pattern = pattern.clone();
1450        let pages = response.into_inner().map(move |page| {
1451            page.and_then(|page| {
1452                note_wire_stream_item(page.quads.len());
1453                let exhausted = waratah_proto::scan_exhaustion_from_proto_opt(page.exhausted);
1454                page.quads
1455                    .iter()
1456                    .map(|quad| {
1457                        quad_from_proto_omitting(quad, &pattern, omitted)
1458                            .map_err(|e| tonic::Status::internal(e.to_string()))
1459                    })
1460                    .collect::<Result<Vec<_>, _>>()
1461                    .map(|rows| ScanPage { rows, exhausted })
1462            })
1463        });
1464        Ok(Box::pin(pages))
1465    }
1466
1467    #[allow(clippy::too_many_arguments)]
1468    async fn count_pattern(
1469        &self,
1470        axis: PartitionAxis,
1471        pattern: &EncodedTriplePattern,
1472        snapshot: SnapshotId,
1473        limit: u64,
1474        permutation: Option<IndexPermutation>,
1475        filter: Option<&BroadcastFilter>,
1476        graph_filter: Option<&GraphFilter>,
1477        merge_default_graph: bool,
1478    ) -> Result<u64, tonic::Status> {
1479        let mut client = self.client(axis);
1480        let response = client
1481            .count_pattern(pattern_scan_request(
1482                pattern,
1483                snapshot,
1484                limit,
1485                permutation,
1486                filter,
1487                graph_filter,
1488                None,
1489                merge_default_graph,
1490                // Counts never carry the mask (the partition rejects one).
1491                IriOnlyMask::NONE,
1492            ))
1493            .await?;
1494        Ok(response.into_inner().count)
1495    }
1496
1497    #[allow(clippy::too_many_arguments)]
1498    async fn scan_domain(
1499        &self,
1500        permutation: IndexPermutation,
1501        constraints: &[EncodedTerm],
1502        snapshot: SnapshotId,
1503        limit: u64,
1504        start_after_constraint: Option<&EncodedTerm>,
1505        start_after_term: Option<&EncodedTerm>,
1506        graph_name: Option<&EncodedTerm>,
1507        graph_filter: Option<&GraphFilter>,
1508        iri_only_head: bool,
1509    ) -> Result<Vec<DomainScanHit>, tonic::Status> {
1510        assert_wire_budget(constraints);
1511        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1512        let response = self
1513            .client(PartitionAxis::from(permutation))
1514            .domain_scan(waratah_proto::pb::DomainScanRequest {
1515                permutation: permutation_to_proto(permutation) as i32,
1516                constraints: constraints
1517                    .iter()
1518                    .map(waratah_proto::term_to_bytes)
1519                    .collect(),
1520                snapshot_id: snapshot.0,
1521                limit,
1522                // Presence carries DefaultGraph on the wire: an empty byte
1523                // string means "bound to the default graph", not "unset".
1524                graph_name: graph_name.map(|term| {
1525                    let bytes = waratah_proto::term_to_bytes(term);
1526                    if bytes.is_empty() {
1527                        // DefaultGraph encodes as zero bytes; keep Some so the
1528                        // partition does not confuse it with an unset G.
1529                        Vec::new()
1530                    } else {
1531                        bytes
1532                    }
1533                }),
1534                graph_filter_terms: graph_terms
1535                    .iter()
1536                    .map(waratah_proto::term_to_bytes)
1537                    .collect(),
1538                graph_filter_allow: graph_allow,
1539                start_after_constraint: start_after_constraint
1540                    .map(waratah_proto::term_to_bytes)
1541                    .unwrap_or_default(),
1542                start_after_term: start_after_term
1543                    .map(waratah_proto::term_to_bytes)
1544                    .unwrap_or_default(),
1545                iri_only_head,
1546            })
1547            .await?;
1548        response
1549            .into_inner()
1550            .hits
1551            .iter()
1552            .map(|hit| {
1553                Ok(DomainScanHit {
1554                    constraint: waratah_proto::term_from_bytes(&hit.constraint)
1555                        .map_err(|e| tonic::Status::internal(e.to_string()))?,
1556                    term: waratah_proto::term_from_bytes(&hit.term)
1557                        .map_err(|e| tonic::Status::internal(e.to_string()))?,
1558                })
1559            })
1560            .collect()
1561    }
1562
1563    #[allow(clippy::too_many_arguments)]
1564    async fn scan_domain_counts(
1565        &self,
1566        permutation: IndexPermutation,
1567        constraints: &[EncodedTerm],
1568        snapshot: SnapshotId,
1569        limit: u64,
1570        start_after_constraint: Option<&EncodedTerm>,
1571        start_after_term: Option<&EncodedTerm>,
1572        graph_name: Option<&EncodedTerm>,
1573        graph_filter: Option<&GraphFilter>,
1574        iri_only_head: bool,
1575        merge_default_graph: bool,
1576        mode: DomainCountMode,
1577    ) -> Result<Vec<DomainScanCountHit>, tonic::Status> {
1578        assert_wire_budget(constraints);
1579        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1580        let response = self
1581            .client(PartitionAxis::from(permutation))
1582            .domain_scan_counts(waratah_proto::pb::DomainScanCountRequest {
1583                permutation: permutation_to_proto(permutation) as i32,
1584                constraints: constraints
1585                    .iter()
1586                    .map(waratah_proto::term_to_bytes)
1587                    .collect(),
1588                snapshot_id: snapshot.0,
1589                limit,
1590                // Presence carries DefaultGraph on the wire: an empty byte
1591                // string means "bound to the default graph", not "unset".
1592                graph_name: graph_name.map(|term| {
1593                    let bytes = waratah_proto::term_to_bytes(term);
1594                    if bytes.is_empty() {
1595                        // DefaultGraph encodes as zero bytes; keep Some so the
1596                        // partition does not confuse it with an unset G.
1597                        Vec::new()
1598                    } else {
1599                        bytes
1600                    }
1601                }),
1602                graph_filter_terms: graph_terms
1603                    .iter()
1604                    .map(waratah_proto::term_to_bytes)
1605                    .collect(),
1606                graph_filter_allow: graph_allow,
1607                start_after_constraint: start_after_constraint
1608                    .map(waratah_proto::term_to_bytes)
1609                    .unwrap_or_default(),
1610                start_after_term: start_after_term
1611                    .map(waratah_proto::term_to_bytes)
1612                    .unwrap_or_default(),
1613                iri_only_head,
1614                merge_default_graph,
1615                count_mode: count_mode_to_proto(mode) as i32,
1616            })
1617            .await?;
1618        response
1619            .into_inner()
1620            .hits
1621            .iter()
1622            .map(|hit| {
1623                Ok(DomainScanCountHit {
1624                    constraint: waratah_proto::term_from_bytes(&hit.constraint)
1625                        .map_err(|e| tonic::Status::internal(e.to_string()))?,
1626                    term: waratah_proto::term_from_bytes(&hit.term)
1627                        .map_err(|e| tonic::Status::internal(e.to_string()))?,
1628                    count: hit.count,
1629                })
1630            })
1631            .collect()
1632    }
1633
1634    #[allow(clippy::too_many_arguments)]
1635    async fn scan_axis_head(
1636        &self,
1637        permutation: IndexPermutation,
1638        snapshot: SnapshotId,
1639        limit: u64,
1640        start_after_term: Option<&EncodedTerm>,
1641        graph_name: Option<&EncodedTerm>,
1642        graph_filter: Option<&GraphFilter>,
1643        iri_only_head: bool,
1644        head_prefixes: &[Vec<u8>],
1645    ) -> Result<Vec<EncodedTerm>, tonic::Status> {
1646        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1647        let response = self
1648            .client(PartitionAxis::from(permutation))
1649            .axis_head_scan(waratah_proto::pb::AxisHeadScanRequest {
1650                permutation: permutation_to_proto(permutation) as i32,
1651                snapshot_id: snapshot.0,
1652                limit,
1653                graph_name: graph_name.map(waratah_proto::term_to_bytes),
1654                graph_filter_terms: graph_terms
1655                    .iter()
1656                    .map(waratah_proto::term_to_bytes)
1657                    .collect(),
1658                graph_filter_allow: graph_allow,
1659                start_after_term: start_after_term
1660                    .map(waratah_proto::term_to_bytes)
1661                    .unwrap_or_default(),
1662                iri_only_head,
1663                head_prefixes: head_prefixes.to_vec(),
1664            })
1665            .await?;
1666        response
1667            .into_inner()
1668            .terms
1669            .iter()
1670            .map(|bytes| {
1671                waratah_proto::term_from_bytes(bytes)
1672                    .map_err(|e| tonic::Status::internal(e.to_string()))
1673            })
1674            .collect()
1675    }
1676
1677    #[allow(clippy::too_many_arguments)]
1678    async fn count_axis_heads(
1679        &self,
1680        permutation: IndexPermutation,
1681        snapshot: SnapshotId,
1682        graph_name: Option<&EncodedTerm>,
1683        graph_filter: Option<&GraphFilter>,
1684        iri_only_head: bool,
1685    ) -> Result<u64, tonic::Status> {
1686        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1687        let response = self
1688            .client(PartitionAxis::from(permutation))
1689            .axis_head_scan_counts(pb::AxisHeadScanCountsRequest {
1690                permutation: permutation_to_proto(permutation) as i32,
1691                snapshot_id: snapshot.0,
1692                mode: pb::AxisHeadCountMode::Total as i32,
1693                graph_name: graph_name.map(waratah_proto::term_to_bytes),
1694                graph_filter_terms: graph_terms
1695                    .iter()
1696                    .map(waratah_proto::term_to_bytes)
1697                    .collect(),
1698                graph_filter_allow: graph_allow,
1699                start_after_term: Vec::new(),
1700                iri_only_head,
1701                limit: 0,
1702            })
1703            .await?;
1704        Ok(response.into_inner().total)
1705    }
1706
1707    #[allow(clippy::too_many_arguments)]
1708    async fn scan_axis_head_counts(
1709        &self,
1710        permutation: IndexPermutation,
1711        snapshot: SnapshotId,
1712        limit: u64,
1713        start_after_term: Option<&EncodedTerm>,
1714        graph_name: Option<&EncodedTerm>,
1715        graph_filter: Option<&GraphFilter>,
1716        iri_only_head: bool,
1717    ) -> Result<Vec<AxisHeadCountHit>, tonic::Status> {
1718        let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1719        let response = self
1720            .client(PartitionAxis::from(permutation))
1721            .axis_head_scan_counts(pb::AxisHeadScanCountsRequest {
1722                permutation: permutation_to_proto(permutation) as i32,
1723                snapshot_id: snapshot.0,
1724                mode: pb::AxisHeadCountMode::PerHead as i32,
1725                graph_name: graph_name.map(waratah_proto::term_to_bytes),
1726                graph_filter_terms: graph_terms
1727                    .iter()
1728                    .map(waratah_proto::term_to_bytes)
1729                    .collect(),
1730                graph_filter_allow: graph_allow,
1731                start_after_term: start_after_term
1732                    .map(waratah_proto::term_to_bytes)
1733                    .unwrap_or_default(),
1734                iri_only_head,
1735                limit,
1736            })
1737            .await?;
1738        response
1739            .into_inner()
1740            .hits
1741            .iter()
1742            .map(|hit| {
1743                Ok(AxisHeadCountHit {
1744                    term: waratah_proto::term_from_bytes(&hit.term)
1745                        .map_err(|e| tonic::Status::internal(e.to_string()))?,
1746                    count: hit.count,
1747                })
1748            })
1749            .collect()
1750    }
1751}
1752
1753/// Wire-budget boundary guard shared by the request builders: a request
1754/// term list must never exceed one threshold-sized chunk
1755/// (`PUSHDOWN_TERMS_LIMIT`). See the longer rationale on
1756/// `pattern_scan_request`.
1757///
1758/// Firing is a FINDING, not a mistake. The specialized-scan roads (domain /
1759/// domain-counts) legitimately receive user-constructible over-threshold
1760/// constraint lists today (a large VALUES clause on a class-constrained
1761/// pattern), and the partition answers those with the clean typed
1762/// `DomainScanTooLarge` error in every build profile. In debug and test
1763/// builds this assert deliberately converts that into a panic: each
1764/// firing names one road awaiting its scoped fix (chunked delivery or a
1765/// compute-side typed refusal), discovered empirically as queries
1766/// exercise the shape — release builds keep the graceful failure. Do not
1767/// widen the bound or fence a call site to silence a firing; fix the
1768/// road that tripped it.
1769fn assert_wire_budget(terms: &[EncodedTerm]) {
1770    debug_assert!(
1771        terms.len() <= PUSHDOWN_TERMS_LIMIT as usize,
1772        "oversized scan request: {} terms (threshold {}) — \
1773         a scan road bypassed the wire-budget boundary",
1774        terms.len(),
1775        PUSHDOWN_TERMS_LIMIT
1776    );
1777}
1778
1779#[allow(clippy::too_many_arguments)]
1780fn pattern_scan_request(
1781    pattern: &EncodedTriplePattern,
1782    snapshot: SnapshotId,
1783    limit: u64,
1784    permutation: Option<IndexPermutation>,
1785    filter: Option<&BroadcastFilter>,
1786    graph_filter: Option<&GraphFilter>,
1787    start_after: Option<&EncodedQuad>,
1788    merge_default_graph: bool,
1789    iri_only: IriOnlyMask,
1790) -> waratah_proto::pb::ScanPatternRequest {
1791    let (slot, terms) = match filter {
1792        Some(f) if !f.terms.is_empty() => (Some(f.slot), &*f.terms),
1793        _ => (None, &[][..]),
1794    };
1795    // The wire-budget boundary guard and its kept-by-design firing
1796    // contract live on `assert_wire_budget` (one invariant, one copy).
1797    // Road context for this builder: the eager whole-read road delivers
1798    // an over-threshold pushed broadcast filter through the chunked hook
1799    // in `fetch_whole`; every other road currently ships its list on the
1800    // wire as-is — one oversized request exceeds the clustered gRPC
1801    // message ceiling for large lists and fails the query.
1802    assert_wire_budget(terms);
1803    let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1804    scan_request_page(
1805        pattern,
1806        snapshot,
1807        limit,
1808        permutation,
1809        slot,
1810        terms,
1811        start_after,
1812        graph_terms,
1813        graph_allow,
1814        merge_default_graph,
1815        iri_only,
1816    )
1817}
1818
1819impl HexastoreFlush for GrpcHexastoreClients {
1820    async fn flush_memtables(&self, axis: PartitionAxis) -> Result<(), tonic::Status> {
1821        let mut client = self.client(axis);
1822        client
1823            .flush_memtables(waratah_proto::pb::FlushMemtablesRequest {})
1824            .await?;
1825        Ok(())
1826    }
1827}
1828
1829impl HexastoreCompact for GrpcHexastoreClients {
1830    async fn compact_range(&self, axis: PartitionAxis) -> Result<(), tonic::Status> {
1831        let mut client = self.client(axis);
1832        client
1833            .compact_range(waratah_proto::pb::CompactRangeRequest {})
1834            .await?;
1835        Ok(())
1836    }
1837}
1838
1839impl HexastoreStats for GrpcHexastoreClients {
1840    async fn stats_profile(&self, axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1841        let mut client = self.client(axis);
1842        let response = client
1843            .get_stats_profile(waratah_proto::pb::GetStatsProfileRequest {})
1844            .await?;
1845        Ok(response.into_inner().profile)
1846    }
1847
1848    async fn geo_histogram(
1849        &self,
1850        axis: PartitionAxis,
1851        section: waratah_proto::pb::GeoHistogramSection,
1852    ) -> Result<Vec<u8>, tonic::Status> {
1853        let mut client = self.client(axis);
1854        let response = client
1855            .get_geo_histogram(waratah_proto::pb::GetGeoHistogramRequest {
1856                section: section.into(),
1857            })
1858            .await?;
1859        Ok(response.into_inner().histogram)
1860    }
1861
1862    async fn temporal_histogram(&self, axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1863        let mut client = self.client(axis);
1864        let response = client
1865            .get_temporal_histogram(waratah_proto::pb::GetTemporalHistogramRequest {})
1866            .await?;
1867        Ok(response.into_inner().histogram)
1868    }
1869
1870    async fn text_seed_sketch(&self, axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1871        let mut client = self.client(axis);
1872        let response = client
1873            .get_text_seed_sketch(waratah_proto::pb::GetTextSeedSketchRequest {})
1874            .await?;
1875        Ok(response.into_inner().sketch)
1876    }
1877}
1878
1879impl HexastoreAdmin for GrpcHexastoreClients {
1880    async fn describe(&self, axis: PartitionAxis) -> Result<HexastoreDescribe, tonic::Status> {
1881        let mut client = self.client(axis);
1882        let response = client
1883            .describe(waratah_proto::pb::HexastoreDescribeRequest {})
1884            .await?
1885            .into_inner();
1886        hexastore_describe_from_proto(response)
1887    }
1888}
1889
1890impl HexastoreCatalog for GrpcHexastoreClients {
1891    async fn list_named_graphs(
1892        &self,
1893        snapshot: SnapshotId,
1894    ) -> Result<Vec<EncodedTerm>, tonic::Status> {
1895        let mut client = self.client(PartitionAxis::S);
1896        let response = client
1897            .list_named_graphs(waratah_proto::list_named_graphs_request(snapshot))
1898            .await?;
1899        response
1900            .into_inner()
1901            .graph_names
1902            .iter()
1903            .map(|bytes| {
1904                waratah_proto::term_from_bytes(bytes)
1905                    .map_err(|error| tonic::Status::internal(error.to_string()))
1906            })
1907            .collect()
1908    }
1909
1910    async fn add_named_graph(
1911        &self,
1912        graph: &EncodedTerm,
1913        commit_ts: waratah_storage::CommitTs,
1914    ) -> Result<(), tonic::Status> {
1915        let mut client = self.client(PartitionAxis::S);
1916        client
1917            .add_named_graph(waratah_proto::add_named_graph_request(graph, commit_ts))
1918            .await?;
1919        Ok(())
1920    }
1921}
1922
1923impl HexastoreGeo for GrpcHexastoreClients {
1924    async fn rebuild_geo_index(&self) -> Result<(bool, bool, u64), tonic::Status> {
1925        let mut client = self.client(PartitionAxis::O);
1926        let response = client
1927            .rebuild_geo_index(pb::RebuildGeoIndexRequest {})
1928            .await?;
1929        let response = response.into_inner();
1930        Ok((
1931            response.started,
1932            response.already_in_progress,
1933            response.upgrade_ts,
1934        ))
1935    }
1936
1937    async fn renew_geo_rebuild_lease(&self) -> Result<(), tonic::Status> {
1938        let mut client = self.client(PartitionAxis::O);
1939        client
1940            .renew_geo_rebuild_lease(pb::RenewGeoRebuildLeaseRequest {})
1941            .await?;
1942        Ok(())
1943    }
1944
1945    async fn finish_geo_index_rebuild(&self) -> Result<u64, tonic::Status> {
1946        let mut client = self.client(PartitionAxis::O);
1947        let response = client
1948            .finish_geo_index_rebuild(pb::FinishGeoIndexRebuildRequest {})
1949            .await?;
1950        Ok(response.into_inner().epoch)
1951    }
1952    async fn put_geo_index(&self, puts: &[GeoIndexPut]) -> Result<u64, tonic::Status> {
1953        // Chunk by accumulated posting bytes so one frame stays bounded —
1954        // the fan-out budget already flushes at ~3.5 MiB, this is a backstop.
1955        const FRAME_BUDGET: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE / 2;
1956        let mut client = self.client(PartitionAxis::O);
1957        let mut applied = 0u64;
1958        let mut frame: Vec<pb::GeoIndexPut> = Vec::new();
1959        let mut frame_bytes = 0usize;
1960        for put in puts {
1961            let bytes = 8 + put.term.len() + 8 + 21;
1962            if !frame.is_empty() && frame_bytes + bytes > FRAME_BUDGET {
1963                let response = client
1964                    .put_geo_index(pb::PutGeoIndexRequest {
1965                        puts: std::mem::take(&mut frame),
1966                    })
1967                    .await?;
1968                applied += response.into_inner().applied;
1969                frame_bytes = 0;
1970            }
1971            frame_bytes += bytes;
1972            frame.push(pb::GeoIndexPut {
1973                s2_cell_id: put.cell_id,
1974                term: put.term.clone(),
1975                commit_ts: put.commit_ts.0,
1976                op: match put.op {
1977                    waratah_storage::StorageOp::Put => pb::StorageOp::Put as i32,
1978                    waratah_storage::StorageOp::Delete => pb::StorageOp::Delete as i32,
1979                },
1980                visibility: put.visibility.0,
1981                crs84_envelope: put.envelope.map(|env| env.encode().to_vec()),
1982            });
1983        }
1984        if !frame.is_empty() {
1985            let response = client
1986                .put_geo_index(pb::PutGeoIndexRequest { puts: frame })
1987                .await?;
1988            applied += response.into_inner().applied;
1989        }
1990        Ok(applied)
1991    }
1992
1993    async fn delete_geo_term(&self, term: &[u8]) -> Result<u64, tonic::Status> {
1994        let mut client = self.client(PartitionAxis::O);
1995        let response = client
1996            .delete_geo_term(pb::DeleteGeoTermRequest {
1997                term: term.to_vec(),
1998            })
1999            .await?;
2000        Ok(response.into_inner().deleted)
2001    }
2002
2003    async fn geo_candidate_scan(
2004        &self,
2005        intervals: &[GeoCellInterval],
2006        snapshot: SnapshotId,
2007        query_envelope: Option<GeoEnvelope>,
2008        limit: u64,
2009    ) -> Result<TermPageStream, tonic::Status> {
2010        let mut client = self.client(PartitionAxis::O);
2011        let request = pb::GeoCandidateScanRequest {
2012            intervals: intervals
2013                .iter()
2014                .map(|interval| pb::geo_candidate_scan_request::CellInterval {
2015                    min_cell_id: interval.min_cell_id,
2016                    max_cell_id: interval.max_cell_id,
2017                })
2018                .collect(),
2019            snapshot_id: snapshot.0,
2020            limit,
2021            query_envelope: query_envelope.map(|env| env.encode().to_vec()),
2022        };
2023        let response = client.geo_candidate_scan(request).await?;
2024        let pages = response.into_inner().map(|page| {
2025            page.and_then(|page| {
2026                page.terms
2027                    .iter()
2028                    .map(|bytes| {
2029                        waratah_proto::term_from_bytes(bytes)
2030                            .map_err(|e| tonic::Status::internal(e.to_string()))
2031                    })
2032                    .collect()
2033            })
2034        });
2035        Ok(Box::pin(pages))
2036    }
2037
2038    async fn put_temporal_index(&self, puts: &[TemporalIndexPut]) -> Result<u64, tonic::Status> {
2039        // Chunk by accumulated posting bytes so one frame stays bounded —
2040        // the fan-out budget already flushes at ~3.5 MiB, this is a backstop.
2041        const FRAME_BUDGET: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE / 2;
2042        let mut client = self.client(PartitionAxis::O);
2043        let mut applied = 0u64;
2044        let mut frame: Vec<pb::TemporalIndexPut> = Vec::new();
2045        let mut frame_bytes = 0usize;
2046        for put in puts {
2047            let bytes = 16 + put.term.len() + 8 + 37;
2048            if !frame.is_empty() && frame_bytes + bytes > FRAME_BUDGET {
2049                let response = client
2050                    .put_temporal_index(pb::PutTemporalIndexRequest {
2051                        puts: std::mem::take(&mut frame),
2052                    })
2053                    .await?;
2054                applied += response.into_inner().applied;
2055                frame_bytes = 0;
2056            }
2057            frame_bytes += bytes;
2058            frame.push(pb::TemporalIndexPut {
2059                node_key: put.node_key.to_be_bytes().to_vec(),
2060                term: put.term.clone(),
2061                commit_ts: put.commit_ts.0,
2062                op: match put.op {
2063                    waratah_storage::StorageOp::Put => pb::StorageOp::Put,
2064                    waratah_storage::StorageOp::Delete => pb::StorageOp::Delete,
2065                } as i32,
2066                visibility: put.visibility.0,
2067                begin: put.begin.to_be_bytes().to_vec(),
2068                end: put.end.to_be_bytes().to_vec(),
2069            });
2070        }
2071        if !frame.is_empty() {
2072            let response = client
2073                .put_temporal_index(pb::PutTemporalIndexRequest { puts: frame })
2074                .await?;
2075            applied += response.into_inner().applied;
2076        }
2077        Ok(applied)
2078    }
2079
2080    async fn temporal_candidate_scan(
2081        &self,
2082        intervals: &[TemporalCellInterval],
2083        snapshot: SnapshotId,
2084        predicate: TemporalQueryPredicate,
2085        limit: u64,
2086    ) -> Result<TermPageStream, tonic::Status> {
2087        let mut client = self.client(PartitionAxis::O);
2088        let request = pb::TemporalCandidateScanRequest {
2089            intervals: intervals
2090                .iter()
2091                .map(|interval| interval.encode().to_vec())
2092                .collect(),
2093            snapshot_id: snapshot.0,
2094            predicate: predicate.encode().to_vec(),
2095            limit,
2096        };
2097        let response = client.temporal_candidate_scan(request).await?;
2098        let pages = response.into_inner().map(|page| {
2099            page.and_then(|page| {
2100                page.terms
2101                    .iter()
2102                    .map(|bytes| {
2103                        waratah_proto::term_from_bytes(bytes)
2104                            .map_err(|e| tonic::Status::internal(e.to_string()))
2105                    })
2106                    .collect()
2107            })
2108        });
2109        Ok(Box::pin(pages))
2110    }
2111
2112    async fn rebuild_temporal_index(
2113        &self,
2114        config: waratah_storage::DyadicCovererConfig,
2115    ) -> Result<(bool, bool), tonic::Status> {
2116        let mut client = self.client(PartitionAxis::O);
2117        let response = client
2118            .rebuild_temporal_index(pb::RebuildTemporalIndexRequest {
2119                min_level: u32::from(config.min_level),
2120                max_level: u32::from(config.max_level),
2121                max_nodes: config.max_nodes as u64,
2122            })
2123            .await?;
2124        let response = response.into_inner();
2125        Ok((response.started, response.already_in_progress))
2126    }
2127
2128    async fn put_text_index(&self, docs: &[TextIndexDoc]) -> Result<u64, tonic::Status> {
2129        // Chunk by accumulated document bytes so one frame stays bounded —
2130        // the fan-out budget already flushes the batch, this is a backstop.
2131        // Same estimator and same budget as the write path's flush (see
2132        // `text_index_doc_wire_bytes`): one wire budget for the same
2133        // documents, never two divergent ones.
2134        const FRAME_BUDGET: usize = crate::fanout::TEXT_INDEX_WIRE_BUDGET_BYTES;
2135        let mut client = self.client(PartitionAxis::O);
2136        let mut applied = 0u64;
2137        let mut frame: Vec<pb::TextIndexDoc> = Vec::new();
2138        let mut frame_bytes = 0usize;
2139        for doc in docs {
2140            let bytes = crate::fanout::text_index_doc_wire_bytes(doc);
2141            if !frame.is_empty() && frame_bytes + bytes > FRAME_BUDGET {
2142                let response = client
2143                    .put_text_index(pb::PutTextIndexRequest {
2144                        docs: std::mem::take(&mut frame),
2145                    })
2146                    .await?;
2147                applied += response.into_inner().applied;
2148                frame_bytes = 0;
2149            }
2150            frame_bytes += bytes;
2151            frame.push(waratah_proto::text_index_doc_to_proto(doc));
2152        }
2153        if !frame.is_empty() {
2154            let response = client
2155                .put_text_index(pb::PutTextIndexRequest { docs: frame })
2156                .await?;
2157            applied += response.into_inner().applied;
2158        }
2159        Ok(applied)
2160    }
2161
2162    async fn text_candidate_scan(
2163        &self,
2164        request: &TextSearchRequest,
2165        snapshot: SnapshotId,
2166    ) -> Result<TermPageStream, tonic::Status> {
2167        let mut client = self.client(PartitionAxis::O);
2168        let mode = match request.mode {
2169            waratah_storage::TextCandidateMode::Fts => pb::TextCandidateMode::Fts,
2170            waratah_storage::TextCandidateMode::Prefix => pb::TextCandidateMode::Prefix,
2171            waratah_storage::TextCandidateMode::Suffix => pb::TextCandidateMode::Suffix,
2172        };
2173        let wire = pb::TextCandidateScanRequest {
2174            mode: mode as i32,
2175            query: request.query.clone(),
2176            language: request.language.clone(),
2177            limit: request.limit,
2178            snapshot_id: snapshot.0,
2179        };
2180        let response = client.text_candidate_scan(wire).await?;
2181        let pages = response.into_inner().map(|page| {
2182            page.and_then(|page| {
2183                page.terms
2184                    .iter()
2185                    .map(|bytes| {
2186                        waratah_proto::term_from_bytes(bytes)
2187                            .map_err(|e| tonic::Status::internal(e.to_string()))
2188                    })
2189                    .collect()
2190            })
2191        });
2192        Ok(Box::pin(pages))
2193    }
2194
2195    async fn text_subject_scan(
2196        &self,
2197        request: &TextSubjectRequest,
2198        snapshot: SnapshotId,
2199    ) -> Result<SubjectRowStream, tonic::Status> {
2200        let mut client = self.client(PartitionAxis::O);
2201        let mode = match request.mode {
2202            waratah_storage::TextCandidateMode::Fts => pb::TextCandidateMode::Fts,
2203            waratah_storage::TextCandidateMode::Prefix => pb::TextCandidateMode::Prefix,
2204            waratah_storage::TextCandidateMode::Suffix => pb::TextCandidateMode::Suffix,
2205        };
2206        let wire = pb::TextSubjectScanRequest {
2207            mode: mode as i32,
2208            query: request.query.clone(),
2209            language: request.language.clone(),
2210            limit: request.limit,
2211            snapshot_id: snapshot.0,
2212            predicates: request
2213                .predicates
2214                .iter()
2215                .map(waratah_proto::term_to_bytes)
2216                .collect(),
2217            graph_filter_terms: request
2218                .graph_filter_terms
2219                .iter()
2220                .map(waratah_proto::term_to_bytes)
2221                .collect(),
2222            graph_filter_allow: request.graph_filter_allow,
2223            graph_name: request
2224                .graph_name
2225                .as_ref()
2226                .map(waratah_proto::term_to_bytes),
2227            merge_default_graph: request.merge_default_graph,
2228            return_graph: request.return_graph,
2229            subject_equals_graph: request.subject_equals_graph,
2230        };
2231        let response = client.text_subject_scan(wire).await?;
2232        let pages = response.into_inner().map(|page| {
2233            page.and_then(|page| {
2234                page.rows
2235                    .iter()
2236                    .map(text_subject_row_from_proto)
2237                    .collect::<Result<Vec<_>, tonic::Status>>()
2238            })
2239        });
2240        Ok(Box::pin(pages))
2241    }
2242
2243    async fn rebuild_text_index(
2244        &self,
2245        analyzer: &str,
2246        seed_chars: u32,
2247        fingerprint: &str,
2248        wipe: bool,
2249    ) -> Result<(bool, bool, u64), tonic::Status> {
2250        let mut client = self.client(PartitionAxis::O);
2251        let response = client
2252            .rebuild_text_index(pb::RebuildTextIndexRequest {
2253                analyzer: analyzer.to_owned(),
2254                seed_chars,
2255                fingerprint: fingerprint.to_owned(),
2256                wipe,
2257            })
2258            .await?;
2259        let response = response.into_inner();
2260        Ok((
2261            response.started,
2262            response.already_in_progress,
2263            response.lease_token,
2264        ))
2265    }
2266
2267    async fn renew_text_rebuild_lease(&self, lease_token: u64) -> Result<(), tonic::Status> {
2268        let mut client = self.client(PartitionAxis::O);
2269        client
2270            .renew_text_rebuild_lease(pb::RenewTextRebuildLeaseRequest { lease_token })
2271            .await?;
2272        Ok(())
2273    }
2274
2275    async fn finish_text_index_rebuild(
2276        &self,
2277        lease_token: u64,
2278        stamp: bool,
2279    ) -> Result<u64, tonic::Status> {
2280        let mut client = self.client(PartitionAxis::O);
2281        let response = client
2282            .finish_text_index_rebuild(pb::FinishTextIndexRebuildRequest { lease_token, stamp })
2283            .await?;
2284        Ok(response.into_inner().epoch)
2285    }
2286}
2287
2288/// Tonic client(s) for the string-registry endpoint(s).
2289///
2290/// MVP holds one process (`RegistryNodeId(0)`). Entries are still routed with
2291/// [`ClusterConfig::registry_for_hash`] so splitting the registry later only
2292/// needs more connections in this map.
2293#[derive(Debug, Clone)]
2294pub struct GrpcRegistryClients {
2295    clients: BTreeMap<RegistryNodeId, StringRegistryClient<Channel>>,
2296    config: ClusterConfig,
2297}
2298
2299impl GrpcRegistryClients {
2300    /// Connect to every registry node listed in `config`.
2301    pub async fn connect(config: &ClusterConfig) -> Result<Self, ComputeError> {
2302        let mut clients = BTreeMap::new();
2303        for (node, addr) in config.registry_nodes() {
2304            let endpoint =
2305                tonic::transport::Endpoint::from_shared(http_url(addr))?.tcp_nodelay(true);
2306            let client = StringRegistryClient::connect(endpoint)
2307                .await?
2308                .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
2309            clients.insert(node, client);
2310        }
2311        if clients.is_empty() {
2312            return Err(ComputeError::Router(
2313                waratah_router::RouterError::NoRegistryNodes,
2314            ));
2315        }
2316        Ok(Self {
2317            clients,
2318            config: config.clone(),
2319        })
2320    }
2321
2322    fn client_for_addr(
2323        &self,
2324        addr: SocketAddr,
2325    ) -> Result<StringRegistryClient<Channel>, ComputeError> {
2326        for (node, client) in &self.clients {
2327            if self.config.registry(*node)? == addr {
2328                return Ok(client.clone());
2329            }
2330        }
2331        Err(ComputeError::Router(
2332            waratah_router::RouterError::NoRegistryNodes,
2333        ))
2334    }
2335}
2336
2337impl StringRegister for GrpcRegistryClients {
2338    async fn register_strings(&self, entries: &[(StrHash, String)]) -> Result<u64, tonic::Status> {
2339        if entries.is_empty() {
2340            return Ok(0);
2341        }
2342
2343        // Group by owning registry address (MVP: one bucket).
2344        let mut by_addr: BTreeMap<SocketAddr, Vec<(StrHash, String)>> = BTreeMap::new();
2345        for (hash, raw) in entries {
2346            let addr = self
2347                .config
2348                .registry_for_hash(*hash)
2349                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2350            by_addr.entry(addr).or_default().push((*hash, raw.clone()));
2351        }
2352
2353        let mut registered = 0u64;
2354        for (addr, batch) in by_addr {
2355            let mut client = self
2356                .client_for_addr(addr)
2357                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2358            // Requests stay single gRPC messages: split the batch by a byte
2359            // budget so a handful of near-cap literals cannot overflow the
2360            // server's decode limit. Compute knows these sizes; the request
2361            // side never needs streaming.
2362            for chunk in register_byte_chunks(&batch) {
2363                let response = client
2364                    .register_strings(register_request(
2365                        chunk.iter().map(|(h, r)| (*h, r.as_str())),
2366                    ))
2367                    .await?;
2368                registered += response.into_inner().registered;
2369            }
2370        }
2371        Ok(registered)
2372    }
2373}
2374
2375/// Entry batches whose estimated request payload fits comfortably in one
2376/// gRPC message.
2377///
2378/// Budget is half the message ceiling (mirroring the registry's frame
2379/// budget); per-entry wire cost is the 16-byte hash plus the raw UTF-8
2380/// bytes plus proto framing. The registry's
2381/// [`MAX_REGISTERED_STRING_BYTES`](waratah_registry::MAX_REGISTERED_STRING_BYTES)
2382/// cap guarantees any single entry fits, so every chunk is non-empty.
2383fn register_byte_chunks(batch: &[(StrHash, String)]) -> Vec<&[(StrHash, String)]> {
2384    const BUDGET: usize = GRPC_MAX_MESSAGE_SIZE / 2;
2385    const ENTRY_FRAMING: usize = 16;
2386    let mut chunks = Vec::new();
2387    let mut start = 0;
2388    let mut bytes = 0usize;
2389    for (index, (_, raw)) in batch.iter().enumerate() {
2390        let entry = ENTRY_FRAMING + std::mem::size_of::<StrHash>() + raw.len();
2391        if index > start && bytes + entry > BUDGET {
2392            chunks.push(&batch[start..index]);
2393            start = index;
2394            bytes = 0;
2395        }
2396        bytes += entry;
2397    }
2398    chunks.push(&batch[start..]);
2399    chunks
2400}
2401
2402impl StringResolve for GrpcRegistryClients {
2403    async fn resolve_strings(
2404        &self,
2405        hashes: &[StrHash],
2406    ) -> Result<Vec<Option<String>>, tonic::Status> {
2407        if hashes.is_empty() {
2408            return Ok(Vec::new());
2409        }
2410
2411        // Ask each owning registry only for the hashes it holds, then restore
2412        // the caller's order (MVP resolves to a single node).
2413        let mut by_addr: BTreeMap<SocketAddr, Vec<usize>> = BTreeMap::new();
2414        for (index, hash) in hashes.iter().enumerate() {
2415            let addr = self
2416                .config
2417                .registry_for_hash(*hash)
2418                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2419            by_addr.entry(addr).or_default().push(index);
2420        }
2421
2422        let mut resolved = vec![None; hashes.len()];
2423        for (addr, indexes) in by_addr {
2424            let mut client = self
2425                .client_for_addr(addr)
2426                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2427            // Drain the streamed frames; entries are consecutive runs in
2428            // request order, so the concatenation is positionally aligned
2429            // with the hashes we asked for.
2430            let mut stream = client
2431                .resolve_strings(resolve_request(indexes.iter().map(|i| hashes[*i])))
2432                .await?
2433                .into_inner();
2434            let mut values = Vec::with_capacity(indexes.len());
2435            while let Some(frame) = stream.next().await {
2436                values.extend(frame?.values);
2437            }
2438            if values.len() != indexes.len() {
2439                return Err(tonic::Status::internal(format!(
2440                    "registry {addr} returned {} values for {} hashes",
2441                    values.len(),
2442                    indexes.len()
2443                )));
2444            }
2445            for (index, value) in indexes.into_iter().zip(values) {
2446                resolved[index] = value.raw;
2447            }
2448        }
2449        Ok(resolved)
2450    }
2451}
2452
2453impl StringRegistryFlush for GrpcRegistryClients {
2454    async fn flush_memtables(&self) -> Result<(), tonic::Status> {
2455        for client in self.clients.values() {
2456            let mut client = client.clone();
2457            client
2458                .flush_memtables(waratah_proto::pb::FlushMemtablesRequest {})
2459                .await?;
2460        }
2461        Ok(())
2462    }
2463}
2464
2465impl StringRegistryCompact for GrpcRegistryClients {
2466    async fn compact_range(&self) -> Result<(), tonic::Status> {
2467        for client in self.clients.values() {
2468            let mut client = client.clone();
2469            client
2470                .compact_range(waratah_proto::pb::CompactRangeRequest {})
2471                .await?;
2472        }
2473        Ok(())
2474    }
2475}
2476
2477impl RegistryAdmin for GrpcRegistryClients {
2478    async fn describe(
2479        &self,
2480        node: waratah_router::RegistryNodeId,
2481    ) -> Result<RegistryDescribe, tonic::Status> {
2482        let mut client =
2483            self.clients.get(&node).cloned().ok_or_else(|| {
2484                tonic::Status::not_found(format!("no registry client for {node}"))
2485            })?;
2486        let response = client
2487            .describe(waratah_proto::pb::RegistryDescribeRequest {})
2488            .await?
2489            .into_inner();
2490        Ok(registry_describe_from_proto(response))
2491    }
2492}
2493
2494impl BlobStoreClient for GrpcRegistryClients {
2495    async fn put_blob_chunks(
2496        &self,
2497        blob_id: StrHash,
2498        payload: Arc<[u8]>,
2499    ) -> Result<(), tonic::Status> {
2500        // Route to the owning registry node (MVP: one node).
2501        let addr = self
2502            .config
2503            .registry_for_hash(blob_id)
2504            .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2505        let mut client = self
2506            .client_for_addr(addr)
2507            .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2508        // Chunk frames under half the message ceiling; each frame carries
2509        // the running chunk list of the single blob.
2510        const CHUNK: usize = GRPC_MAX_MESSAGE_SIZE / 2;
2511        let total_chunks = payload.len().div_ceil(CHUNK).max(1) as u64;
2512        let id_bytes = blob_id.to_be_bytes().to_vec();
2513        let frames: Vec<pb::PutBlobRequest> = payload
2514            .chunks(CHUNK)
2515            .enumerate()
2516            .map(|(seq, data)| pb::PutBlobRequest {
2517                chunks: vec![pb::BlobChunk {
2518                    blob_id: id_bytes.clone(),
2519                    seq: seq as u64,
2520                    total_chunks,
2521                    data: data.to_vec(),
2522                }],
2523            })
2524            .collect();
2525        let stream = tokio_stream::iter(frames);
2526        client.put_blob_chunks(stream).await?;
2527        Ok(())
2528    }
2529
2530    async fn put_blobs(&self, blobs: &[(StrHash, Arc<[u8]>)]) -> Result<(), tonic::Status> {
2531        if blobs.is_empty() {
2532            return Ok(());
2533        }
2534        // Route each blob to its owning registry node (MVP: one node gets
2535        // the whole batch). The caller frames the batch under
2536        // PUT_BLOBS_BATCH_BYTES, so every per-owner sub-batch is one gRPC
2537        // message with headroom; the server commits each batch atomically
2538        // (hash validation before any write, skip-existing), making
2539        // whole-batch retries idempotent.
2540        let mut by_addr: BTreeMap<SocketAddr, Vec<pb::Blob>> = BTreeMap::new();
2541        for (blob_id, payload) in blobs {
2542            let addr = self
2543                .config
2544                .registry_for_hash(*blob_id)
2545                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2546            by_addr.entry(addr).or_default().push(pb::Blob {
2547                id: blob_id.to_be_bytes().to_vec(),
2548                data: payload.to_vec(),
2549            });
2550        }
2551        for (addr, batch) in by_addr {
2552            let mut client = self
2553                .client_for_addr(addr)
2554                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2555            client
2556                .put_blobs(pb::PutBlobsRequest { blobs: batch })
2557                .await?;
2558        }
2559        Ok(())
2560    }
2561
2562    async fn get_blobs(&self, ids: &[StrHash]) -> Result<Vec<Option<Vec<u8>>>, tonic::Status> {
2563        if ids.is_empty() {
2564            return Ok(Vec::new());
2565        }
2566        // Registry ownership is by registered-string hash; blob ids are
2567        // content hashes — route the whole batch to every node's owner by
2568        // the same hash ring (MVP: one node receives all).
2569        let mut per_addr: BTreeMap<SocketAddr, Vec<usize>> = BTreeMap::new();
2570        for (index, hash) in ids.iter().enumerate() {
2571            let addr = self
2572                .config
2573                .registry_for_hash(*hash)
2574                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2575            per_addr.entry(addr).or_default().push(index);
2576        }
2577        let mut out: Vec<Option<Vec<u8>>> = vec![None; ids.len()];
2578        for (addr, indexes) in per_addr {
2579            let mut client = self
2580                .client_for_addr(addr)
2581                .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2582            // The id list may repeat an id across indexes; request each
2583            // distinct id once and fan the reassembled payload back out to
2584            // every original index that asked for it.
2585            let mut distinct: BTreeMap<StrHash, Vec<usize>> = BTreeMap::new();
2586            for &index in &indexes {
2587                distinct.entry(ids[index]).or_default().push(index);
2588            }
2589            let request_ids: Vec<Vec<u8>> = distinct
2590                .keys()
2591                .map(|id| id.to_be_bytes().to_vec())
2592                .collect();
2593            let mut stream = client
2594                .get_blobs(pb::GetBlobsRequest {
2595                    blob_ids: request_ids,
2596                })
2597                .await?
2598                .into_inner();
2599            // Reassemble: id → (declared total_chunks, parts). Mirrors the
2600            // registry's PutBlobChunks contract: the first chunk of a blob sets
2601            // the declared total and later chunks must agree with it, seqs
2602            // must arrive contiguously from 0, and once concatenated the
2603            // payload must hash back to its blob id (content addressing).
2604            // A hit delivers every chunk of its payload; misses send
2605            // nothing.
2606            let mut pending: BTreeMap<StrHash, (u64, Vec<Vec<u8>>)> = BTreeMap::new();
2607            while let Some(frame) = stream.next().await {
2608                for chunk in frame?.chunks {
2609                    let Ok(id_bytes) = <[u8; 16]>::try_from(chunk.blob_id.as_slice()) else {
2610                        return Err(tonic::Status::internal("blob id must be 16 bytes"));
2611                    };
2612                    let id = StrHash::from_be_bytes(id_bytes);
2613                    let entry = pending
2614                        .entry(id)
2615                        .or_insert((chunk.total_chunks, Vec::new()));
2616                    if entry.0 != chunk.total_chunks {
2617                        return Err(tonic::Status::invalid_argument(
2618                            "inconsistent total_chunks across blob chunks",
2619                        ));
2620                    }
2621                    let seq = entry.1.len() as u64;
2622                    if chunk.seq != seq {
2623                        return Err(tonic::Status::invalid_argument(format!(
2624                            "blob {id}: expected chunk seq {seq}, got {}",
2625                            chunk.seq
2626                        )));
2627                    }
2628                    entry.1.push(chunk.data);
2629                }
2630            }
2631            for (id, fanout) in distinct {
2632                let Some((total_chunks, parts)) = pending.remove(&id) else {
2633                    // Miss: the server sends nothing for absent ids.
2634                    continue;
2635                };
2636                let mut payload = parts.concat();
2637                if parts.len() as u64 != total_chunks {
2638                    return Err(tonic::Status::internal(format!(
2639                        "blob {id} declared {total_chunks} chunks but delivered {}",
2640                        parts.len()
2641                    )));
2642                }
2643                if StrHash::from_bytes(&payload) != id {
2644                    return Err(tonic::Status::internal(format!(
2645                        "blob {id} failed content-addressing verification"
2646                    )));
2647                }
2648                payload.shrink_to_fit();
2649                if let Some((last, rest)) = fanout.split_last() {
2650                    for index in rest {
2651                        out[*index] = Some(payload.clone());
2652                    }
2653                    out[*last] = Some(payload);
2654                }
2655            }
2656            if !pending.is_empty() {
2657                // The server echoes the REQUESTED id on every chunk, so a
2658                // correct server can never land here — this branch is a
2659                // wire-integrity backstop against a server that keys
2660                // chunks under ids we did not ask for. A corrupted stored
2661                // payload arrives under the requested id and is caught by
2662                // the content-addressing check above, which is the
2663                // load-bearing end-to-end identity check.
2664                let unclaimed: Vec<String> = pending.keys().map(ToString::to_string).collect();
2665                return Err(tonic::Status::internal(format!(
2666                    "registry {addr} delivered chunks under unrequested blob ids: {unclaimed:?}"
2667                )));
2668            }
2669        }
2670        Ok(out)
2671    }
2672}
2673
2674pub(crate) fn http_url(addr: SocketAddr) -> String {
2675    format!("http://{addr}")
2676}
2677
2678fn backend_name(value: i32) -> String {
2679    match pb::StorageBackend::try_from(value).unwrap_or(pb::StorageBackend::Unspecified) {
2680        pb::StorageBackend::Memory => "memory".to_owned(),
2681        pb::StorageBackend::Rocksdb => "rocksdb".to_owned(),
2682        pb::StorageBackend::Unspecified => "unspecified".to_owned(),
2683    }
2684}
2685
2686fn lsm_from_proto(metrics: Option<pb::LsmMetrics>) -> crate::cluster::LsmMetricsView {
2687    let Some(m) = metrics else {
2688        return crate::cluster::LsmMetricsView::default();
2689    };
2690    crate::cluster::LsmMetricsView {
2691        estimate_live_data_bytes: m.estimate_live_data_bytes,
2692        estimate_num_keys: m.estimate_num_keys,
2693        total_sst_bytes: m.total_sst_bytes,
2694        memtable_bytes: m.memtable_bytes,
2695        num_running_compactions: m.num_running_compactions,
2696        num_running_flushes: m.num_running_flushes,
2697        open_total_puts: m.open_total_puts,
2698        compaction_event_count: m.compaction_event_count,
2699        named_graph_count: m.named_graph_count,
2700        entry_count: None,
2701        block_cache_capacity_bytes: m.block_cache_capacity_bytes,
2702        block_cache_usage_bytes: m.block_cache_usage_bytes,
2703    }
2704}
2705
2706pub(crate) fn hexastore_describe_from_proto(
2707    response: pb::HexastoreDescribeResponse,
2708) -> Result<HexastoreDescribe, tonic::Status> {
2709    let axis = waratah_proto::axis_from_proto(
2710        pb::PartitionAxis::try_from(response.axis).unwrap_or(pb::PartitionAxis::Unspecified),
2711    )
2712    .ok_or_else(|| tonic::Status::internal("describe returned unspecified axis"))?;
2713    Ok(HexastoreDescribe {
2714        axis,
2715        node_id: response.node_id,
2716        listen: response.listen,
2717        data_dir: response.data_dir,
2718        backend: backend_name(response.backend),
2719        version: response.version,
2720        repository_id: response.repository_id,
2721        serving: response.serving,
2722        metrics: lsm_from_proto(response.metrics),
2723        geo_index_epoch: response.geo_index_epoch,
2724        temporal_index_epoch: response.temporal_index_epoch,
2725        temporal_rebuild_in_progress: response.temporal_rebuild_in_progress,
2726        geo_rebuild_in_progress: response.geo_rebuild_in_progress,
2727        text_index_epoch: response.text_index_epoch,
2728        text_index_fingerprint: response.text_index_fingerprint,
2729        text_index_terms: response.text_index_terms,
2730        text_rebuild_in_progress: response.text_rebuild_in_progress,
2731    })
2732}
2733
2734fn registry_describe_from_proto(response: pb::RegistryDescribeResponse) -> RegistryDescribe {
2735    RegistryDescribe {
2736        node_id: response.node_id,
2737        listen: response.listen,
2738        data_dir: response.data_dir,
2739        backend: backend_name(response.backend),
2740        version: response.version,
2741        repository_id: response.repository_id,
2742        shard_count: response.shard_count,
2743        entry_count: response.entry_count,
2744        serving: response.serving,
2745        metrics: lsm_from_proto(response.metrics),
2746    }
2747}
2748
2749#[cfg(test)]
2750mod wire_frame_tests {
2751    use super::*;
2752    use tokio_stream::StreamExt;
2753    use waratah_storage::{NamedNode, ScanExhaustion};
2754
2755    /// The wire-budget debug assert is the kept-by-design firing
2756    /// contract: a debug build panics the moment a road that cannot
2757    /// chunk its list ships one over the threshold, naming the road;
2758    /// a release build fails the query cleanly via the partition's
2759    /// typed `DomainScanTooLarge`. This pin fails if the assert is ever
2760    /// widened, fenced, or quietly removed — the revisit condition is
2761    /// the specialized-leaf constraint-chunking fix landing, at which point
2762    /// this test flips to asserting the chunked delivery.
2763    #[test]
2764    #[should_panic(expected = "oversized scan request")]
2765    fn wire_budget_assert_names_the_road_in_debug() {
2766        // Exactly threshold + 1 terms: the assert must fire at the
2767        // boundary itself, not merely for comfortably-oversized lists.
2768        let terms: Vec<EncodedTerm> = (0..=PUSHDOWN_TERMS_LIMIT as usize)
2769            .map(|i| EncodedTerm::from(&NamedNode::new(format!("http://ex/t{i}")).unwrap()))
2770            .collect();
2771        assert_wire_budget(&terms);
2772    }
2773
2774    #[test]
2775    fn wire_budget_assert_passes_at_the_threshold() {
2776        let terms: Vec<EncodedTerm> = (0..PUSHDOWN_TERMS_LIMIT as usize)
2777            .map(|i| EncodedTerm::from(&NamedNode::new(format!("http://ex/t{i}")).unwrap()))
2778            .collect();
2779        assert_wire_budget(&terms);
2780    }
2781
2782    fn one_row() -> waratah_storage::EncodedQuad {
2783        waratah_storage::EncodedQuad::new(
2784            waratah_storage::EncodedTerm::DefaultGraph,
2785            waratah_storage::EncodedTerm::DefaultGraph,
2786            waratah_storage::EncodedTerm::DefaultGraph,
2787            waratah_storage::EncodedTerm::DefaultGraph,
2788        )
2789    }
2790
2791    /// Pin the wire frame shapes [`scan_page_as_wire_frames`] emits, so
2792    /// every unary-backed transport and test double speaks what the
2793    /// partition speaks: a terminal verdict moves to one EMPTY terminal
2794    /// frame behind a verdict-less data frame carrying the rows. The
2795    /// consumers' terminal-frame branches (the driver funnel's break,
2796    /// bounded drains' last-frame-wins) depend on exactly this shape.
2797    #[tokio::test]
2798    async fn terminal_verdict_moves_to_an_empty_terminal_frame() {
2799        let mut frames = scan_page_as_wire_frames(ScanPage {
2800            rows: vec![one_row()],
2801            exhausted: Some(ScanExhaustion::ExhaustedScan),
2802        });
2803        let data = frames.next().await.unwrap().unwrap();
2804        assert_eq!(data.rows.len(), 1, "the rows ride the data frame");
2805        assert_eq!(
2806            data.exhausted, None,
2807            "a completed walk's data frame carries no verdict"
2808        );
2809        let terminal = frames.next().await.unwrap().unwrap();
2810        assert!(terminal.rows.is_empty(), "the terminal frame is empty");
2811        assert_eq!(terminal.exhausted, Some(ScanExhaustion::ExhaustedScan));
2812        assert!(frames.next().await.is_none(), "exactly two frames");
2813    }
2814
2815    /// A limit stop and an unpurchased verdict keep the single-frame
2816    /// shape: `Limited` is the limit-stop flush's own verdict and `None`
2817    /// means no verdict was bought — neither invents a terminal frame.
2818    #[tokio::test]
2819    async fn limited_and_unpurchased_verdicts_stay_on_one_frame() {
2820        for exhausted in [Some(ScanExhaustion::Limited), None] {
2821            let mut frames = scan_page_as_wire_frames(ScanPage {
2822                rows: vec![one_row()],
2823                exhausted,
2824            });
2825            let only = frames.next().await.unwrap().unwrap();
2826            assert_eq!(only.rows.len(), 1);
2827            assert_eq!(only.exhausted, exhausted);
2828            assert!(frames.next().await.is_none(), "exactly one frame");
2829        }
2830    }
2831}
2832
2833#[cfg(test)]
2834mod register_chunk_tests {
2835    use super::*;
2836
2837    fn entry(raw_len: usize) -> (StrHash, String) {
2838        (
2839            StrHash::new(&"x".repeat(raw_len.min(64))),
2840            "y".repeat(raw_len),
2841        )
2842    }
2843
2844    #[test]
2845    fn small_batches_stay_whole() {
2846        let batch: Vec<(StrHash, String)> = (0..100).map(|_| entry(10)).collect();
2847        let chunks = register_byte_chunks(&batch);
2848        assert_eq!(chunks, vec![&batch[..]]);
2849    }
2850
2851    #[test]
2852    fn oversized_batches_split_under_the_budget() {
2853        // Three near-cap entries: only two fit GRPC_MAX_MESSAGE_SIZE / 2
2854        // together, so the third moves to its own (still valid) request.
2855        let cap = waratah_registry::MAX_REGISTERED_STRING_BYTES;
2856        let batch: Vec<(StrHash, String)> = (0..3).map(|_| entry(cap - 1024)).collect();
2857        let chunks = register_byte_chunks(&batch);
2858        assert_eq!(
2859            chunks.len(),
2860            2,
2861            "{:?} byte sizes",
2862            chunks.iter().map(|c| c.len()).collect::<Vec<_>>()
2863        );
2864        assert_eq!(chunks[0].len(), 2);
2865        assert_eq!(chunks[1].len(), 1);
2866        // No chunk's estimated payload exceeds the budget.
2867        for chunk in &chunks {
2868            let bytes: usize = chunk
2869                .iter()
2870                .map(|(_, raw)| 16 + std::mem::size_of::<StrHash>() + raw.len())
2871                .sum();
2872            assert!(bytes <= GRPC_MAX_MESSAGE_SIZE / 2);
2873        }
2874    }
2875
2876    #[test]
2877    fn a_single_max_entry_still_forms_a_chunk() {
2878        let cap = waratah_registry::MAX_REGISTERED_STRING_BYTES;
2879        let batch = vec![entry(cap), entry(cap), entry(cap), entry(8)];
2880        let chunks = register_byte_chunks(&batch);
2881        // max + max + tiny never share a frame; every entry is chunked.
2882        assert_eq!(
2883            chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
2884            vec![1, 1, 2]
2885        );
2886    }
2887}
2888
2889#[cfg(test)]
2890mod comparison_transport_tests {
2891    //! The trait-level contract of slot comparison pushdown: a transport
2892    //! that does not opt in accepts only the empty list, and every default
2893    //! path resolves to the existing unfiltered methods.
2894
2895    use std::sync::Arc;
2896    use std::sync::atomic::{AtomicUsize, Ordering};
2897
2898    use tokio_stream::StreamExt;
2899    use waratah_storage::{CompareOp, Literal, NamedNode, QuadSlot, ScanExhaustion};
2900
2901    use super::*;
2902
2903    /// A transport with one real method. Every other `HexastoreScan`
2904    /// method is unreachable from these tests (the trait's defaults never
2905    /// call them), so they are stubbed rather than implemented.
2906    #[derive(Clone, Default)]
2907    struct UnaryOnlyScan {
2908        scans: Arc<AtomicUsize>,
2909    }
2910
2911    impl HexastoreScan for UnaryOnlyScan {
2912        async fn scan_pattern(
2913            &self,
2914            _axis: PartitionAxis,
2915            _pattern: &EncodedTriplePattern,
2916            _snapshot: SnapshotId,
2917            _limit: u64,
2918            _permutation: Option<IndexPermutation>,
2919            _filter: Option<&BroadcastFilter>,
2920            _graph_filter: Option<&GraphFilter>,
2921            _start_after: Option<&EncodedQuad>,
2922            _merge_default_graph: bool,
2923            _iri_only: IriOnlyMask,
2924            _omitted: u8,
2925            _verdict_wanted: bool,
2926        ) -> Result<ScanPage, tonic::Status> {
2927            self.scans.fetch_add(1, Ordering::Relaxed);
2928            Ok(ScanPage {
2929                rows: vec![EncodedQuad::new(
2930                    EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()),
2931                    EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()),
2932                    EncodedTerm::from(&Literal::from(1967i64)),
2933                    EncodedTerm::DefaultGraph,
2934                )],
2935                exhausted: Some(ScanExhaustion::ExhaustedScan),
2936            })
2937        }
2938
2939        async fn count_pattern(
2940            &self,
2941            _axis: PartitionAxis,
2942            _pattern: &EncodedTriplePattern,
2943            _snapshot: SnapshotId,
2944            _limit: u64,
2945            _permutation: Option<IndexPermutation>,
2946            _filter: Option<&BroadcastFilter>,
2947            _graph_filter: Option<&GraphFilter>,
2948            _merge_default_graph: bool,
2949        ) -> Result<u64, tonic::Status> {
2950            unreachable!("count_pattern is not on a scan path")
2951        }
2952
2953        async fn scan_domain(
2954            &self,
2955            _permutation: IndexPermutation,
2956            _constraints: &[EncodedTerm],
2957            _snapshot: SnapshotId,
2958            _limit: u64,
2959            _start_after_constraint: Option<&EncodedTerm>,
2960            _start_after_term: Option<&EncodedTerm>,
2961            _graph_name: Option<&EncodedTerm>,
2962            _graph_filter: Option<&GraphFilter>,
2963            _iri_only_head: bool,
2964        ) -> Result<Vec<DomainScanHit>, tonic::Status> {
2965            unreachable!("scan_domain is not on a scan path")
2966        }
2967
2968        async fn scan_domain_counts(
2969            &self,
2970            _permutation: IndexPermutation,
2971            _constraints: &[EncodedTerm],
2972            _snapshot: SnapshotId,
2973            _limit: u64,
2974            _start_after_constraint: Option<&EncodedTerm>,
2975            _start_after_term: Option<&EncodedTerm>,
2976            _graph_name: Option<&EncodedTerm>,
2977            _graph_filter: Option<&GraphFilter>,
2978            _iri_only_head: bool,
2979            _merge_default_graph: bool,
2980            _mode: DomainCountMode,
2981        ) -> Result<Vec<DomainScanCountHit>, tonic::Status> {
2982            unreachable!("scan_domain_counts is not on a scan path")
2983        }
2984
2985        async fn scan_axis_head(
2986            &self,
2987            _permutation: IndexPermutation,
2988            _snapshot: SnapshotId,
2989            _limit: u64,
2990            _start_after_term: Option<&EncodedTerm>,
2991            _graph_name: Option<&EncodedTerm>,
2992            _graph_filter: Option<&GraphFilter>,
2993            _iri_only_head: bool,
2994            _head_prefixes: &[Vec<u8>],
2995        ) -> Result<Vec<EncodedTerm>, tonic::Status> {
2996            unreachable!("scan_axis_head is not on a scan path")
2997        }
2998
2999        async fn count_axis_heads(
3000            &self,
3001            _permutation: IndexPermutation,
3002            _snapshot: SnapshotId,
3003            _graph_name: Option<&EncodedTerm>,
3004            _graph_filter: Option<&GraphFilter>,
3005            _iri_only_head: bool,
3006        ) -> Result<u64, tonic::Status> {
3007            unreachable!("count_axis_heads is not on a scan path")
3008        }
3009
3010        async fn scan_axis_head_counts(
3011            &self,
3012            _permutation: IndexPermutation,
3013            _snapshot: SnapshotId,
3014            _limit: u64,
3015            _start_after_term: Option<&EncodedTerm>,
3016            _graph_name: Option<&EncodedTerm>,
3017            _graph_filter: Option<&GraphFilter>,
3018            _iri_only_head: bool,
3019        ) -> Result<Vec<AxisHeadCountHit>, tonic::Status> {
3020            unreachable!("scan_axis_head_counts is not on a scan path")
3021        }
3022    }
3023
3024    fn year_eq_1967() -> SlotComparison {
3025        SlotComparison {
3026            slot: QuadSlot::Object,
3027            op: CompareOp::Eq,
3028            term: EncodedTerm::from(&Literal::from(1967i64)),
3029        }
3030    }
3031
3032    async fn scan_with(
3033        store: &UnaryOnlyScan,
3034        comparisons: &[SlotComparison],
3035    ) -> Result<ScanPage, tonic::Status> {
3036        store
3037            .scan_pattern_with_comparisons(
3038                PartitionAxis::P,
3039                &EncodedTriplePattern::default(),
3040                SnapshotId::default(),
3041                0,
3042                None,
3043                None,
3044                None,
3045                None,
3046                false,
3047                IriOnlyMask::NONE,
3048                comparisons,
3049                0,
3050                false,
3051            )
3052            .await
3053    }
3054
3055    async fn stream_with(
3056        store: &UnaryOnlyScan,
3057        comparisons: &[SlotComparison],
3058    ) -> Result<QuadPageStream, tonic::Status> {
3059        store
3060            .scan_pattern_stream_with_comparisons(
3061                PartitionAxis::P,
3062                &EncodedTriplePattern::default(),
3063                SnapshotId::default(),
3064                0,
3065                None,
3066                None,
3067                None,
3068                None,
3069                false,
3070                IriOnlyMask::NONE,
3071                comparisons,
3072                0,
3073                false,
3074            )
3075            .await
3076    }
3077
3078    #[tokio::test]
3079    async fn empty_list_delegates_to_the_unfiltered_unary_scan() {
3080        let store = UnaryOnlyScan::default();
3081        let page = scan_with(&store, &[]).await.unwrap();
3082        assert_eq!(page.rows.len(), 1);
3083        assert_eq!(store.scans.load(Ordering::Relaxed), 1);
3084    }
3085
3086    #[tokio::test]
3087    async fn a_transport_that_ignores_the_list_still_returns_the_unfiltered_page() {
3088        // The FILTER stays in the plan and remains authoritative, so the
3089        // list is a read reduction: a transport that does not apply it must
3090        // still deliver correct rows rather than failing the query.
3091        let store = UnaryOnlyScan::default();
3092        let page = scan_with(&store, &[year_eq_1967()]).await.unwrap();
3093        assert_eq!(page.rows.len(), 1);
3094        assert_eq!(store.scans.load(Ordering::Relaxed), 1);
3095    }
3096
3097    #[tokio::test]
3098    async fn empty_list_stream_keeps_the_streaming_default() {
3099        let store = UnaryOnlyScan::default();
3100        let mut frames = stream_with(&store, &[]).await.unwrap();
3101        let mut rows = 0;
3102        let mut verdict = None;
3103        while let Some(frame) = frames.next().await {
3104            let frame = frame.unwrap();
3105            rows += frame.rows.len();
3106            verdict = frame.exhausted.or(verdict);
3107        }
3108        assert_eq!(rows, 1);
3109        assert_eq!(verdict, Some(ScanExhaustion::ExhaustedScan));
3110    }
3111
3112    #[tokio::test]
3113    async fn the_stream_fallback_keeps_the_unfiltered_rows_and_frames() {
3114        let store = UnaryOnlyScan::default();
3115        let mut frames = stream_with(&store, &[year_eq_1967()]).await.unwrap();
3116        let mut rows = 0;
3117        while let Some(frame) = frames.next().await {
3118            rows += frame.unwrap().rows.len();
3119        }
3120        assert_eq!(rows, 1);
3121    }
3122}
3123
3124#[cfg(test)]
3125mod text_subject_row_tests {
3126    use super::*;
3127    use waratah_storage::NamedNode;
3128
3129    #[test]
3130    fn the_default_graph_survives_the_wire_as_presence_not_a_length() {
3131        // The RDF default graph encodes to zero bytes, so the row's `graph`
3132        // field must distinguish "the default graph" from "not requested" by
3133        // presence alone. Getting this wrong silently drops the graph column
3134        // for every default-graph row.
3135        let subject = EncodedTerm::from(&NamedNode::new("http://ex/s1").unwrap());
3136        let subject_bytes = waratah_proto::term_to_bytes(&subject);
3137        let default_row = pb::TextSubjectRow {
3138            subject: subject_bytes.clone(),
3139            graph: Some(waratah_proto::term_to_bytes(&EncodedTerm::DefaultGraph)),
3140        };
3141        assert_eq!(
3142            default_row.graph.as_deref(),
3143            Some(&[][..]),
3144            "the default graph's encoded term is zero bytes"
3145        );
3146        let decoded = text_subject_row_from_proto(&default_row).unwrap();
3147        assert_eq!(decoded.subject, subject);
3148        assert!(
3149            matches!(decoded.graph, Some(EncodedTerm::DefaultGraph)),
3150            "an empty but PRESENT graph field is the default graph"
3151        );
3152
3153        let absent = pb::TextSubjectRow {
3154            subject: subject_bytes,
3155            graph: None,
3156        };
3157        let decoded = text_subject_row_from_proto(&absent).unwrap();
3158        assert!(
3159            decoded.graph.is_none(),
3160            "absence means the graph column was not requested"
3161        );
3162    }
3163}