Skip to main content

waratah_compute/
node.rs

1//! The compute process: one set of connections behind the write and read paths.
2//!
3//! A compute node is stateless. It holds clients for the three hexastore
4//! partitions and the string registry, a [`WriteFanout`] for inserts, and a
5//! [`QueryEngine`] for `SELECT` / `ASK` / `CONSTRUCT` / `DESCRIBE`. Restarting it loses
6//! nothing. Production dials those clients over gRPC; `waratah standalone`
7//! injects in-process adapters instead.
8
9use waratah_router::{ClusterConfig, Router};
10use waratah_storage::{CommitTs, EncodedTerm, Quad, SnapshotId, StorageOp, VisibilityLabel};
11
12use crate::clients::{
13    BlobStoreClient, GrpcHexastoreClients, GrpcRegistryClients, HexastoreAdmin, HexastoreCatalog,
14    HexastoreCompact, HexastoreFlush, HexastoreGeo, HexastoreInsert, HexastoreScan, HexastoreStats,
15    RegistryAdmin, StringRegister, StringRegistryCompact, StringRegistryFlush, StringResolve,
16};
17use crate::context::QueryContext;
18use crate::describe::DescribeMode;
19use crate::error::{ComputeError, RetryPolicy, with_retry};
20use crate::fanout::{InsertResult, WriteFanout};
21use crate::query::QueryEngine;
22use crate::solutions::{QueryOutput, QueryResults};
23
24/// Connected compute coordinator.
25///
26/// Default type parameters are the gRPC adapters used by the spawned-cluster
27/// path. [`ComputeNode::from_clients`] accepts any types that implement the
28/// hexastore / registry client traits (in-process adapters in `waratah_bin`).
29#[derive(Debug, Clone)]
30pub struct ComputeNode<H = GrpcHexastoreClients, R = GrpcRegistryClients> {
31    fanout: WriteFanout<H, R>,
32    queries: QueryEngine<H, R>,
33    cluster: Option<std::sync::Arc<ClusterConfig>>,
34    standalone: bool,
35}
36
37impl<H, R> ComputeNode<H, R> {
38    /// Wire write fan-out and query execution over already-built clients, sharing them.
39    pub fn from_clients(hexastore: H, registry: R, router: Router, retry: RetryPolicy) -> Self
40    where
41        H: Clone,
42        R: Clone,
43    {
44        Self {
45            fanout: WriteFanout::new(hexastore.clone(), registry.clone(), retry),
46            queries: QueryEngine::new(hexastore, registry, router, retry),
47            cluster: None,
48            standalone: false,
49        }
50    }
51
52    /// Write fan-out coordinator.
53    pub fn fanout(&self) -> &WriteFanout<H, R> {
54        &self.fanout
55    }
56
57    /// SELECT / ASK / CONSTRUCT / DESCRIBE execution engine.
58    pub fn queries(&self) -> &QueryEngine<H, R> {
59        &self.queries
60    }
61
62    /// Set the DESCRIBE algorithm (`star` default).
63    pub fn with_describe_mode(mut self, mode: DescribeMode) -> Self {
64        self.queries.set_describe_mode(mode);
65        self
66    }
67
68    /// Distinct-pair circuit breaker for bound / one-end property paths.
69    pub fn set_path_pair_budget(&mut self, budget: u64) {
70        self.queries.set_path_pair_budget(budget);
71    }
72
73    /// Distinct-pair circuit breaker for `*` / `+` with no LIMIT.
74    pub fn set_open_star_pair_budget(&mut self, budget: u64) {
75        self.queries.set_open_star_pair_budget(budget);
76    }
77
78    /// Builder: set the bound / one-end path pair budget.
79    pub fn with_path_pair_budget(mut self, budget: u64) -> Self {
80        self.set_path_pair_budget(budget);
81        self
82    }
83
84    /// Builder: set the open-`*` / `+` pair budget.
85    pub fn with_open_star_pair_budget(mut self, budget: u64) -> Self {
86        self.set_open_star_pair_budget(budget);
87        self
88    }
89
90    /// SPARQL default-graph fallback (`false` = RDF unnamed graph only).
91    pub fn set_default_union(&mut self, default_union: bool) {
92        self.queries.set_default_union(default_union);
93    }
94
95    /// Builder: SPARQL default-graph fallback.
96    pub fn with_default_union(mut self, default_union: bool) -> Self {
97        self.set_default_union(default_union);
98        self
99    }
100
101    /// Inner-join seating comparator currently configured (`false` = legacy
102    /// `driver_cost` decision). Read by the EXPLAIN route so HTTP explain
103    /// shows the seat the server will run.
104    pub fn seat_by_total_cost(&self) -> bool {
105        self.queries.seat_by_total_cost()
106    }
107
108    /// Seat inner joins by the total seating cost (the `join-seat-shadow`
109    /// comparator promoted to decision).
110    pub fn set_seat_by_total_cost(&mut self, seat_by_total_cost: bool) {
111        self.queries.set_seat_by_total_cost(seat_by_total_cost);
112    }
113
114    /// Builder: seat inner joins by the total seating cost.
115    pub fn with_seat_by_total_cost(mut self, seat_by_total_cost: bool) -> Self {
116        self.set_seat_by_total_cost(seat_by_total_cost);
117        self
118    }
119
120    /// Benchmark switch: force `Semi` past a `PerPage` cost verdict. The
121    /// semantic semi gates still refuse.
122    pub fn set_force_semi(&mut self, force_semi: bool) {
123        self.queries.set_force_semi(force_semi);
124    }
125
126    /// Builder: force `Semi` past a `PerPage` cost verdict.
127    pub fn with_force_semi(mut self, force_semi: bool) -> Self {
128        self.set_force_semi(force_semi);
129        self
130    }
131
132    /// Whether scans stamp and apply slot comparisons (`true` by default).
133    pub fn eager_scan_filter(&self) -> bool {
134        self.queries.eager_scan_filter()
135    }
136
137    /// Toggle slot comparison pushdown and the eager scan filter. The
138    /// equivalence battery turns it off to prove the answers match the plain
139    /// plan `FILTER`; off is the pre-feature path (nothing stamped).
140    pub fn set_eager_scan_filter(&mut self, enabled: bool) {
141        self.queries.set_eager_scan_filter(enabled);
142    }
143
144    /// Builder: toggle the compute-side eager scan filter.
145    pub fn with_eager_scan_filter(mut self, enabled: bool) -> Self {
146        self.set_eager_scan_filter(enabled);
147        self
148    }
149
150    /// Geo-index rebuild epoch copied onto each [`QueryContext`] (`None` =
151    /// trusted). Set at startup from the O partition's `Describe` payload.
152    pub fn set_geo_index_epoch(&mut self, geo_index_epoch: Option<u64>) {
153        self.queries.set_geo_index_epoch(geo_index_epoch);
154    }
155
156    /// Set the temporal-index rebuild epoch (copied onto every query
157    /// context; `None` = untrusted).
158    pub fn set_temporal_index_epoch(&mut self, temporal_index_epoch: Option<u64>) {
159        self.queries.set_temporal_index_epoch(temporal_index_epoch);
160    }
161
162    /// Set the text-index rebuild epoch and config fingerprint (copied onto
163    /// every query context; `None` epoch = untrusted, both text rewrites off).
164    pub fn set_text_index_state(
165        &mut self,
166        epoch: Option<u64>,
167        fingerprint: impl Into<std::sync::Arc<str>>,
168    ) {
169        self.queries.set_text_index_state(epoch, fingerprint);
170    }
171
172    /// Builder: geo-index rebuild epoch (`None` = trusted).
173    pub fn with_geo_index_epoch(mut self, geo_index_epoch: Option<u64>) -> Self {
174        self.set_geo_index_epoch(geo_index_epoch);
175        self
176    }
177
178    /// Spill root for per-query spill files (`None` = `std::env::temp_dir`).
179    pub fn spill_root(&self) -> Option<&std::path::Path> {
180        self.queries.spill_root()
181    }
182
183    /// Set the spill root copied onto each [`QueryContext`] this node builds.
184    pub fn set_spill_root(&mut self, spill_root: Option<std::path::PathBuf>) {
185        self.queries.set_spill_root(spill_root);
186    }
187
188    /// Builder: spill root copied onto each [`QueryContext`] this node builds.
189    pub fn with_spill_root(mut self, spill_root: Option<std::path::PathBuf>) -> Self {
190        self.set_spill_root(spill_root);
191        self
192    }
193
194    /// Attach the static cluster membership this process uses for Describe/HTTP.
195    pub fn with_cluster_config(mut self, config: ClusterConfig) -> Self {
196        self.cluster = Some(std::sync::Arc::new(config));
197        self
198    }
199
200    /// Static cluster config when this node was constructed with one.
201    pub fn cluster_config(&self) -> Option<&ClusterConfig> {
202        self.cluster.as_deref()
203    }
204
205    /// In-process S/P/O + registry (`waratah standalone`).
206    pub fn standalone(&self) -> bool {
207        self.standalone
208    }
209
210    /// Builder: in-process storage (no hexastore/registry gRPC).
211    pub fn with_standalone(mut self, standalone: bool) -> Self {
212        self.standalone = standalone;
213        self
214    }
215}
216
217impl ComputeNode<GrpcHexastoreClients, GrpcRegistryClients> {
218    /// Dial every address in `config`, sharing channels between both paths.
219    pub async fn connect(config: &ClusterConfig, retry: RetryPolicy) -> Result<Self, ComputeError> {
220        let hexastore = GrpcHexastoreClients::connect(config).await?;
221        let registry = GrpcRegistryClients::connect(config).await?;
222        Ok(
223            Self::from_clients(hexastore, registry, config.router(16)?, retry)
224                .with_cluster_config(config.clone()),
225        )
226    }
227}
228
229impl<H: HexastoreInsert + HexastoreGeo, R: StringRegister + BlobStoreClient> ComputeNode<H, R> {
230    /// Write path: encode once, register strings, fan out to S/P/O.
231    pub async fn insert_quads(
232        &self,
233        quads: &[Quad],
234        commit_ts: CommitTs,
235    ) -> Result<InsertResult, ComputeError> {
236        self.fanout
237            .insert_quads(quads, commit_ts, StorageOp::Put, VisibilityLabel::default())
238            .await
239    }
240}
241
242impl<H: HexastoreScan + HexastoreCatalog + HexastoreGeo, R: StringResolve + BlobStoreClient>
243    ComputeNode<H, R>
244{
245    /// Read path: SPARQL `SELECT` / `ASK` / `CONSTRUCT` / `DESCRIBE` as of `snapshot`.
246    ///
247    /// Builds a default [`QueryContext`] from this node's engine knobs. Prefer
248    /// [`Self::query_with`] when the caller already has a context (API query id,
249    /// debug sinks).
250    pub async fn query(
251        &self,
252        sparql: &str,
253        snapshot: SnapshotId,
254    ) -> Result<QueryResults, ComputeError> {
255        let ctx = self.queries.context(snapshot);
256        self.queries.query(sparql, &ctx).await
257    }
258
259    /// Same as [`Self::query`] with a caller-supplied [`QueryContext`].
260    pub async fn query_with(
261        &self,
262        sparql: &str,
263        ctx: &QueryContext,
264    ) -> Result<QueryResults, ComputeError> {
265        self.queries.query(sparql, ctx).await
266    }
267
268    /// SELECT as encoded rows plus a resolved string map; ASK / graph as [`QueryResults`].
269    pub async fn query_output(
270        &self,
271        sparql: &str,
272        ctx: &QueryContext,
273    ) -> Result<QueryOutput, ComputeError> {
274        self.queries.query_output(sparql, ctx).await
275    }
276
277    /// Default [`QueryContext`] for this node's engine knobs (query id 0).
278    ///
279    /// Customize with `QueryContext::with_*` builders and run through
280    /// [`Self::query_with`] — e.g. `with_base_iri` to resolve relative IRIs
281    /// in the query text.
282    pub fn context(&self, snapshot: SnapshotId) -> QueryContext {
283        self.queries.context(snapshot)
284    }
285
286    /// Count quads visible as of `snapshot` (unbound S/SPOG prefix count).
287    pub async fn quad_count(&self, snapshot: SnapshotId) -> Result<u64, ComputeError> {
288        self.queries.quad_count(snapshot).await
289    }
290}
291
292impl<H: HexastoreFlush, R: StringRegistryFlush> ComputeNode<H, R> {
293    /// Flush MemTables to SST on S, P, O, and the registry (no-op on memory).
294    pub async fn flush_memtables(&self) -> Result<(), ComputeError> {
295        self.fanout.flush_memtables().await
296    }
297}
298
299impl<H: HexastoreCompact, R: StringRegistryCompact> ComputeNode<H, R> {
300    /// Compact S, P, O, and the registry (no-op on memory backends).
301    pub async fn compact_range(&self) -> Result<(), ComputeError> {
302        self.fanout.compact_range().await
303    }
304}
305
306impl<H: HexastoreAdmin, R: RegistryAdmin> ComputeNode<H, R> {
307    /// Probe storage + peer computes and return a cluster snapshot.
308    pub async fn cluster_snapshot(
309        &self,
310        knobs: crate::cluster::ClusterKnobs,
311    ) -> Option<crate::cluster::ClusterSnapshot> {
312        let config = self.cluster.as_deref()?;
313        Some(
314            crate::cluster::assemble_cluster_snapshot(
315                config,
316                &knobs,
317                self.queries.hexastore(),
318                self.queries.registry(),
319                &self.queries.profile(),
320            )
321            .await,
322        )
323    }
324}
325
326impl<H: HexastoreStats, R> ComputeNode<H, R> {
327    /// Pull shard sketch profiles into the local planner cache (Phase 7).
328    ///
329    /// `waratah start` always calls this after connect so SST `waratah.stats`
330    /// from an existing data-dir reach the planner (not only `--load-demo`).
331    pub async fn refresh_stats(&self) -> Result<waratah_stats::StatsProfile, ComputeError> {
332        self.queries.refresh_stats().await
333    }
334}
335
336impl<H: HexastoreCatalog, R> ComputeNode<H, R> {
337    /// List S-axis named graphs visible at `snapshot` (empty graphs included).
338    pub async fn list_named_graphs(
339        &self,
340        snapshot: SnapshotId,
341    ) -> Result<Vec<EncodedTerm>, ComputeError> {
342        with_retry(
343            self.fanout.retry_policy(),
344            || self.fanout.hexastore().list_named_graphs(snapshot),
345            |attempts, message| ComputeError::NamedGraphCatalog { attempts, message },
346        )
347        .await
348    }
349
350    /// Insert an empty named graph on the S-axis catalog (no-op if already Present).
351    pub async fn add_named_graph(
352        &self,
353        graph: &EncodedTerm,
354        commit_ts: CommitTs,
355    ) -> Result<(), ComputeError> {
356        with_retry(
357            self.fanout.retry_policy(),
358            || self.fanout.hexastore().add_named_graph(graph, commit_ts),
359            |attempts, message| ComputeError::NamedGraphCatalog { attempts, message },
360        )
361        .await
362    }
363}