Skip to main content

waratah_router/
route.rs

1//! Pattern → partition axis + index permutation + node selection.
2
3use waratah_storage::{
4    EncodedTerm, EncodedTriplePattern, IndexPermutation, PartitionAxis, RDF_TYPE,
5};
6
7use crate::hash::hash_term;
8use crate::ring::HashRing;
9use crate::table::RoutingTable;
10use crate::{NodeId, RouterError};
11
12/// Select partition axis and preferred index permutation for `pattern`.
13///
14/// Routing rules (MVP):
15/// - `P = rdf:type` and `O` bound → O + TSG
16/// - `S` and `O` bound, `P` unbound → S + SOPG (never OSP)
17/// - `O` bound otherwise → O + OPSG
18/// - `P` bound, `O` unbound → P + best of PSOG/POSG
19/// - `S` bound only → S + best of SPOG/SOPG
20///
21/// Phase 7 replaces heuristic choice with sketch-based selectivity.
22pub fn select_target(
23    pattern: &EncodedTriplePattern,
24) -> Result<(PartitionAxis, IndexPermutation), RouterError> {
25    if pattern.predicate.as_ref() == Some(&RDF_TYPE) && pattern.object.is_some() {
26        return Ok((PartitionAxis::O, IndexPermutation::Tsg));
27    }
28    if pattern.subject.is_some() && pattern.object.is_some() && pattern.predicate.is_none() {
29        return Ok((PartitionAxis::S, IndexPermutation::Sopg));
30    }
31    if pattern.object.is_some() {
32        return Ok((PartitionAxis::O, IndexPermutation::Opsg));
33    }
34    if pattern.predicate.is_some() {
35        return Ok((PartitionAxis::P, pattern.best_permutation(PartitionAxis::P)));
36    }
37    if pattern.subject.is_some() {
38        return Ok((PartitionAxis::S, pattern.best_permutation(PartitionAxis::S)));
39    }
40    Err(RouterError::UnboundPattern)
41}
42
43/// Axis half of [`select_target`].
44pub fn select_axis(pattern: &EncodedTriplePattern) -> Result<PartitionAxis, RouterError> {
45    Ok(select_target(pattern)?.0)
46}
47
48/// Bound term used as the routing key for `axis`.
49pub fn routing_term(
50    pattern: &EncodedTriplePattern,
51    axis: PartitionAxis,
52) -> Result<&EncodedTerm, RouterError> {
53    let term = match axis {
54        PartitionAxis::O => pattern.object.as_ref(),
55        PartitionAxis::P => pattern.predicate.as_ref(),
56        PartitionAxis::S => pattern.subject.as_ref(),
57    };
58    term.ok_or(RouterError::UnboundPattern)
59}
60
61/// Physical node on a hexastore ring or the registry table.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct RoutedNode {
64    /// Routing-table id (`s-0`, `registry-0`, …).
65    pub node_id: NodeId,
66    /// gRPC listen address.
67    pub grpc: std::net::SocketAddr,
68    /// Hexastore axis, or `None` for a registry node.
69    pub axis: Option<PartitionAxis>,
70}
71
72/// Dump of Murmur3 hexastore rings plus the registry address table.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct RoutingSnapshot {
75    /// One entry per physical hexastore node.
76    pub hexastore: Vec<RoutedNode>,
77    /// Configured string-registry processes.
78    pub registry: Vec<RoutedNode>,
79    /// Virtual nodes per physical node on each axis ring.
80    pub vnodes_per_node: u32,
81}
82
83/// Pattern routing result: axis, index permutation, and physical node.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct Route {
86    /// Selected hexastore partition axis.
87    pub axis: PartitionAxis,
88    /// Preferred index permutation on that axis.
89    pub permutation: IndexPermutation,
90    /// Physical node on that axis's consistent-hash ring.
91    pub node: NodeId,
92}
93
94/// Murmur3 ring router with a static address table (local-dev MVP).
95#[derive(Debug, Clone)]
96pub struct Router {
97    rings: [HashRing; 3],
98    table: RoutingTable,
99    vnodes_per_node: u32,
100}
101
102impl Router {
103    /// Build a router from per-axis node lists and a shared address table.
104    ///
105    /// `vnodes_per_node` controls virtual-node density on each axis ring.
106    pub fn new(
107        s_nodes: impl IntoIterator<Item = NodeId>,
108        p_nodes: impl IntoIterator<Item = NodeId>,
109        o_nodes: impl IntoIterator<Item = NodeId>,
110        vnodes_per_node: u32,
111        table: RoutingTable,
112    ) -> Self {
113        Self {
114            rings: [
115                HashRing::new(s_nodes, vnodes_per_node),
116                HashRing::new(p_nodes, vnodes_per_node),
117                HashRing::new(o_nodes, vnodes_per_node),
118            ],
119            table,
120            vnodes_per_node,
121        }
122    }
123
124    /// Shared routing table.
125    pub fn table(&self) -> &RoutingTable {
126        &self.table
127    }
128
129    /// Virtual nodes placed on each physical node of an axis ring.
130    pub fn vnodes_per_node(&self) -> u32 {
131        self.vnodes_per_node
132    }
133
134    /// Ring for `axis`.
135    pub fn ring(&self, axis: PartitionAxis) -> &HashRing {
136        &self.rings[axis_index(axis)]
137    }
138
139    /// Dump physical hexastore nodes and vnode density (registry is filled by [`ClusterConfig`]).
140    pub fn snapshot(&self) -> Result<RoutingSnapshot, RouterError> {
141        Ok(RoutingSnapshot {
142            hexastore: self.hexastore_nodes()?,
143            registry: Vec::new(),
144            vnodes_per_node: self.vnodes_per_node,
145        })
146    }
147
148    /// Hexastore nodes this router knows about (axis, node id, listen address).
149    pub fn hexastore_nodes(&self) -> Result<Vec<RoutedNode>, RouterError> {
150        let mut out = Vec::new();
151        for axis in PartitionAxis::ALL {
152            for node in self.ring(axis).physical_nodes() {
153                let grpc = self.table.lookup(&node)?;
154                out.push(RoutedNode {
155                    node_id: node,
156                    grpc,
157                    axis: Some(axis),
158                });
159            }
160        }
161        Ok(out)
162    }
163
164    /// Select `(PartitionAxis, IndexPermutation, NodeId)` for `pattern`.
165    pub fn route_pattern(&self, pattern: &EncodedTriplePattern) -> Result<Route, RouterError> {
166        let (axis, permutation) = select_target(pattern)?;
167        let term = routing_term(pattern, axis)?;
168        let key_hash = hash_term(term);
169        let node = self
170            .ring(axis)
171            .locate(key_hash)
172            .cloned()
173            .ok_or(RouterError::EmptyAxis(axis))?;
174        Ok(Route {
175            axis,
176            permutation,
177            node,
178        })
179    }
180
181    /// Route and resolve the listen address from the routing table.
182    pub fn route_and_resolve(
183        &self,
184        pattern: &EncodedTriplePattern,
185    ) -> Result<(Route, std::net::SocketAddr), RouterError> {
186        let route = self.route_pattern(pattern)?;
187        let addr = self.table.lookup(&route.node)?;
188        Ok((route, addr))
189    }
190}
191
192fn axis_index(axis: PartitionAxis) -> usize {
193    match axis {
194        PartitionAxis::S => 0,
195        PartitionAxis::P => 1,
196        PartitionAxis::O => 2,
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::ClusterConfig;
204    use pretty_assertions::assert_eq;
205    use waratah_storage::{Literal, NamedNode, Term};
206
207    fn local_dev_router() -> Router {
208        ClusterConfig::local_dev().router(16).unwrap()
209    }
210
211    fn named(iri: &str) -> EncodedTerm {
212        EncodedTerm::from(&NamedNode::new(iri).unwrap())
213    }
214
215    fn lit(s: &str) -> EncodedTerm {
216        EncodedTerm::from(&Term::from(Literal::from(s)))
217    }
218
219    #[test]
220    fn bound_object_routes_to_o_opsg() {
221        let router = local_dev_router();
222        let pattern = EncodedTriplePattern {
223            subject: None,
224            predicate: Some(named("http://ex/hasWeather")),
225            object: Some(lit("Sunny")),
226            graph_name: Some(EncodedTerm::DefaultGraph),
227        };
228        let route = router.route_pattern(&pattern).unwrap();
229        assert_eq!(route.axis, PartitionAxis::O);
230        assert_eq!(route.permutation, IndexPermutation::Opsg);
231        assert_eq!(route.node, NodeId::new("o-0"));
232    }
233
234    #[test]
235    fn bound_predicate_only_routes_to_p() {
236        let router = local_dev_router();
237        let pattern = EncodedTriplePattern {
238            subject: None,
239            predicate: Some(named("http://ex/livesIn")),
240            object: None,
241            graph_name: None,
242        };
243        let route = router.route_pattern(&pattern).unwrap();
244        assert_eq!(route.axis, PartitionAxis::P);
245        assert_eq!(route.node, NodeId::new("p-0"));
246    }
247
248    #[test]
249    fn bound_subject_only_routes_to_s() {
250        let router = local_dev_router();
251        let pattern = EncodedTriplePattern {
252            subject: Some(named("http://ex/alice")),
253            predicate: None,
254            object: None,
255            graph_name: None,
256        };
257        let route = router.route_pattern(&pattern).unwrap();
258        assert_eq!(route.axis, PartitionAxis::S);
259        assert_eq!(route.node, NodeId::new("s-0"));
260    }
261
262    #[test]
263    fn subject_and_object_unbound_predicate_routes_to_s_sopg() {
264        let router = local_dev_router();
265        let pattern = EncodedTriplePattern {
266            subject: Some(named("http://ex/alice")),
267            predicate: None,
268            object: Some(named("http://ex/brisbane")),
269            graph_name: Some(EncodedTerm::DefaultGraph),
270        };
271        let route = router.route_pattern(&pattern).unwrap();
272        assert_eq!(route.axis, PartitionAxis::S);
273        assert_eq!(route.permutation, IndexPermutation::Sopg);
274        assert_eq!(select_axis(&pattern).unwrap(), PartitionAxis::S);
275    }
276
277    #[test]
278    fn fully_bound_non_type_routes_to_o_opsg() {
279        let router = local_dev_router();
280        let pattern = EncodedTriplePattern {
281            subject: Some(named("http://ex/alice")),
282            predicate: Some(named("http://ex/livesIn")),
283            object: Some(named("http://ex/brisbane")),
284            graph_name: Some(EncodedTerm::DefaultGraph),
285        };
286        assert_eq!(select_axis(&pattern).unwrap(), PartitionAxis::O);
287        let route = router.route_pattern(&pattern).unwrap();
288        assert_eq!(route.axis, PartitionAxis::O);
289        assert_eq!(route.permutation, IndexPermutation::Opsg);
290    }
291
292    #[test]
293    fn precedence_p_over_s_when_object_unbound() {
294        let pattern = EncodedTriplePattern {
295            subject: Some(named("http://ex/alice")),
296            predicate: Some(named("http://ex/livesIn")),
297            object: None,
298            graph_name: None,
299        };
300        assert_eq!(select_axis(&pattern).unwrap(), PartitionAxis::P);
301    }
302
303    #[test]
304    fn unbound_pattern_errors() {
305        let router = local_dev_router();
306        let pattern = EncodedTriplePattern::default();
307        assert_eq!(
308            router.route_pattern(&pattern),
309            Err(RouterError::UnboundPattern)
310        );
311    }
312
313    #[test]
314    fn weather_city_example_routes_sunny_to_o() {
315        // (?city, :hasWeather, "Sunny") → O for Hash("Sunny")
316        let router = local_dev_router();
317        let pattern = EncodedTriplePattern {
318            subject: None,
319            predicate: Some(named("http://ex/hasWeather")),
320            object: Some(lit("Sunny")),
321            graph_name: Some(EncodedTerm::DefaultGraph),
322        };
323        let (route, addr) = router.route_and_resolve(&pattern).unwrap();
324        assert_eq!(route.axis, PartitionAxis::O);
325        assert_eq!(route.permutation, IndexPermutation::Opsg);
326        assert_eq!(addr.port(), 7003);
327    }
328
329    #[test]
330    fn rdf_type_bound_object_routes_to_o_tsg() {
331        let router = local_dev_router();
332        let pattern = EncodedTriplePattern {
333            subject: None,
334            predicate: Some(RDF_TYPE.clone()),
335            object: Some(named("http://ex/Person")),
336            graph_name: Some(EncodedTerm::DefaultGraph),
337        };
338        let route = router.route_pattern(&pattern).unwrap();
339        assert_eq!(route.axis, PartitionAxis::O);
340        assert_eq!(route.permutation, IndexPermutation::Tsg);
341    }
342
343    #[test]
344    fn rdf_type_ground_subject_routes_to_o_tsg() {
345        let router = local_dev_router();
346        let pattern = EncodedTriplePattern {
347            subject: Some(named("http://ex/alice")),
348            predicate: Some(RDF_TYPE.clone()),
349            object: Some(named("http://ex/Person")),
350            graph_name: Some(EncodedTerm::DefaultGraph),
351        };
352        let route = router.route_pattern(&pattern).unwrap();
353        assert_eq!(route.axis, PartitionAxis::O);
354        assert_eq!(route.permutation, IndexPermutation::Tsg);
355    }
356
357    #[test]
358    fn multi_node_o_axis_hashes_to_consistent_node() {
359        use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
360
361        let mut table = RoutingTable::new();
362        let o0 = NodeId::new("o-0");
363        let o1 = NodeId::new("o-1");
364        table.insert(
365            o0.clone(),
366            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 7100)),
367        );
368        table.insert(
369            o1.clone(),
370            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 7101)),
371        );
372        let router = Router::new(
373            [NodeId::new("s-0")],
374            [NodeId::new("p-0")],
375            [o0.clone(), o1.clone()],
376            32,
377            table,
378        );
379
380        let pattern = EncodedTriplePattern {
381            subject: None,
382            predicate: None,
383            object: Some(lit("Sunny")),
384            graph_name: None,
385        };
386        let first = router.route_pattern(&pattern).unwrap();
387        let second = router.route_pattern(&pattern).unwrap();
388        assert_eq!(first, second);
389        assert_eq!(first.axis, PartitionAxis::O);
390        assert_eq!(first.permutation, IndexPermutation::Opsg);
391        assert!(first.node == o0 || first.node == o1);
392    }
393}