Skip to main content

reddb_server/runtime/
graph_dsl.rs

1use super::*;
2
3pub(super) fn materialize_graph(store: &UnifiedStore) -> RedDBResult<GraphStore> {
4    materialize_graph_with_projection(store, None)
5}
6
7pub(super) fn materialize_graph_with_projection(
8    store: &UnifiedStore,
9    projection: Option<&RuntimeGraphProjection>,
10) -> RedDBResult<GraphStore> {
11    let graph = GraphStore::new();
12    // Phase 1.2 MVCC universal: capture the current connection's
13    // snapshot before `query_all` spawns parallel scan threads — the
14    // thread-local CURRENT_SNAPSHOT does not propagate into spawned
15    // workers, so we hand the context to the filter closure by move.
16    let snap_ctx = crate::runtime::impl_core::capture_current_snapshot();
17    let entities = store.query_all(move |e| {
18        crate::runtime::impl_core::entity_visible_with_context(snap_ctx.as_ref(), e)
19    });
20    let node_label_filters = projection
21        .and_then(|projection| normalize_token_filter_list(projection.node_labels.clone()));
22    let node_type_filters = projection
23        .and_then(|projection| normalize_token_filter_list(projection.node_types.clone()));
24    let edge_label_filters = projection
25        .and_then(|projection| normalize_token_filter_list(projection.edge_labels.clone()));
26    let mut allowed_nodes = HashSet::new();
27
28    for (_, entity) in &entities {
29        if let EntityKind::GraphNode(ref node) = &entity.kind {
30            if !matches_graph_node_projection(
31                &node.label,
32                &node.node_type,
33                node_label_filters.as_ref(),
34                node_type_filters.as_ref(),
35            ) {
36                continue;
37            }
38            graph
39                .add_node_with_label(
40                    &entity.id.raw().to_string(),
41                    &node.label,
42                    &graph_node_label(&node.node_type),
43                )
44                .map_err(|err| RedDBError::Query(err.to_string()))?;
45            allowed_nodes.insert(entity.id.raw().to_string());
46        }
47    }
48
49    for (_, entity) in &entities {
50        if let EntityKind::GraphEdge(ref edge) = &entity.kind {
51            if !allowed_nodes.contains(&edge.from_node) || !allowed_nodes.contains(&edge.to_node) {
52                continue;
53            }
54            if !matches_graph_edge_projection(&edge.label, edge_label_filters.as_ref()) {
55                continue;
56            }
57            let resolved_weight = match &entity.data {
58                EntityData::Edge(e) => e.weight,
59                _ => edge.weight as f32 / 1000.0,
60            };
61
62            graph
63                .add_edge_with_label(
64                    &edge.from_node,
65                    &edge.to_node,
66                    &graph_edge_label(&edge.label),
67                    resolved_weight,
68                )
69                .map_err(|err| RedDBError::Query(err.to_string()))?;
70        }
71    }
72
73    Ok(graph)
74}
75
76/// Lazy graph materialization — only loads nodes reachable from seed IDs via BFS.
77/// Much faster than materialize_graph() when you only need a subgraph.
78pub(super) fn materialize_graph_lazy(
79    store: &UnifiedStore,
80    seed_entity_ids: &[u64],
81    max_depth: usize,
82) -> RedDBResult<GraphStore> {
83    let graph = GraphStore::new();
84    let mut visited_nodes: HashSet<String> = HashSet::new();
85    let mut queue: VecDeque<(String, usize)> = VecDeque::new();
86
87    // Phase 1: Load seed nodes
88    for &id in seed_entity_ids {
89        let id_str = id.to_string();
90        if visited_nodes.contains(&id_str) {
91            continue;
92        }
93        if let Some((_, entity)) = store.get_any(EntityId::new(id)) {
94            if let EntityKind::GraphNode(ref node) = &entity.kind {
95                let _ = graph.add_node_with_label(
96                    &id_str,
97                    &node.label,
98                    &graph_node_label(&node.node_type),
99                );
100                visited_nodes.insert(id_str.clone());
101                queue.push_back((id_str, 0));
102            }
103        }
104    }
105
106    // Phase 2: BFS — load neighbors on demand
107    // Collect edges from all collections in parallel
108    let collections = store.list_collections();
109    let use_parallel = collections.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
110    let all_edges: Vec<UnifiedEntity> = if use_parallel {
111        let store_ref = &store;
112        let edge_batches: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
113            collections
114                .iter()
115                .map(|col| {
116                    s.spawn(move || {
117                        store_ref
118                            .get_collection(col)
119                            .map(|m| m.query_all(|e| matches!(e.kind, EntityKind::GraphEdge(_))))
120                            .unwrap_or_default()
121                    })
122                })
123                .collect::<Vec<_>>()
124                .into_iter()
125                .map(|h| h.join().unwrap_or_default())
126                .collect()
127        });
128        edge_batches.into_iter().flatten().collect()
129    } else {
130        collections
131            .iter()
132            .flat_map(|col| {
133                store
134                    .get_collection(col)
135                    .map(|m| m.query_all(|e| matches!(e.kind, EntityKind::GraphEdge(_))))
136                    .unwrap_or_default()
137            })
138            .collect()
139    };
140
141    // Build adjacency from edges
142    let mut adjacency: HashMap<String, Vec<(String, String, String, f32)>> = HashMap::new();
143    for entity in &all_edges {
144        if let EntityKind::GraphEdge(ref edge) = &entity.kind {
145            let w = match &entity.data {
146                EntityData::Edge(e) => e.weight,
147                _ => edge.weight as f32 / 1000.0,
148            };
149            adjacency.entry(edge.from_node.clone()).or_default().push((
150                edge.to_node.clone(),
151                edge.label.clone(),
152                entity.id.raw().to_string(),
153                w,
154            ));
155            adjacency.entry(edge.to_node.clone()).or_default().push((
156                edge.from_node.clone(),
157                edge.label.clone(),
158                entity.id.raw().to_string(),
159                w,
160            ));
161        }
162    }
163
164    while let Some((node_id, depth)) = queue.pop_front() {
165        if depth >= max_depth {
166            continue;
167        }
168        if let Some(neighbors) = adjacency.get(&node_id) {
169            for (neighbor_id, label, _edge_id, weight) in neighbors {
170                // Add neighbor node if not visited
171                if !visited_nodes.contains(neighbor_id) {
172                    if let Ok(parsed) = neighbor_id.parse::<u64>() {
173                        if let Some((_, entity)) = store.get_any(EntityId::new(parsed)) {
174                            if let EntityKind::GraphNode(ref node) = &entity.kind {
175                                let _ = graph.add_node_with_label(
176                                    neighbor_id,
177                                    &node.label,
178                                    &graph_node_label(&node.node_type),
179                                );
180                                visited_nodes.insert(neighbor_id.clone());
181                                queue.push_back((neighbor_id.clone(), depth + 1));
182                            }
183                        }
184                    }
185                }
186                // Add edge
187                if visited_nodes.contains(neighbor_id) {
188                    let _ = graph.add_edge_with_label(
189                        &node_id,
190                        neighbor_id,
191                        &graph_edge_label(label),
192                        *weight,
193                    );
194                }
195            }
196        }
197    }
198
199    Ok(graph)
200}
201
202pub(super) fn materialize_graph_node_properties(
203    store: &UnifiedStore,
204) -> RedDBResult<HashMap<String, HashMap<String, Value>>> {
205    let mut node_properties = HashMap::new();
206
207    for (_, entity) in store.query_all(|_| true) {
208        if let (EntityKind::GraphNode(_), EntityData::Node(node)) = (&entity.kind, &entity.data) {
209            node_properties.insert(entity.id.raw().to_string(), node.properties.clone());
210        }
211    }
212
213    Ok(node_properties)
214}
215
216pub(super) fn normalize_token_filter_list(values: Option<Vec<String>>) -> Option<BTreeSet<String>> {
217    values
218        .map(|values| {
219            values
220                .into_iter()
221                .map(|value| normalize_graph_token(&value))
222                .filter(|value| !value.is_empty())
223                .collect::<BTreeSet<_>>()
224        })
225        .filter(|set| !set.is_empty())
226}
227
228pub(super) fn matches_graph_node_projection(
229    label: &str,
230    node_type: &str,
231    label_filters: Option<&BTreeSet<String>>,
232    node_type_filters: Option<&BTreeSet<String>>,
233) -> bool {
234    let label_ok =
235        label_filters.is_none_or(|filters| filters.contains(&normalize_graph_token(label)));
236    let node_type_ok =
237        node_type_filters.is_none_or(|filters| filters.contains(&normalize_graph_token(node_type)));
238    label_ok && node_type_ok
239}
240
241pub(super) fn matches_graph_edge_projection(
242    label: &str,
243    edge_filters: Option<&BTreeSet<String>>,
244) -> bool {
245    edge_filters.is_none_or(|filters| filters.contains(&normalize_graph_token(label)))
246}
247
248pub(super) fn ensure_graph_node(graph: &GraphStore, id: &str) -> RedDBResult<()> {
249    if graph.has_node(id) {
250        Ok(())
251    } else {
252        Err(RedDBError::NotFound(id.to_string()))
253    }
254}
255
256/// Resolve a user-supplied graph node reference to its canonical entity id.
257///
258/// Accepts either a numeric entity id (e.g. `"177"`) — returned as-is when the
259/// node exists — or a node label (e.g. `"cinderella"`) resolved via the label
260/// secondary index. Errors when the label resolves to more than one node, so
261/// callers can fall back to the numeric id form.
262pub(super) fn resolve_graph_node_id(graph: &GraphStore, input: &str) -> RedDBResult<String> {
263    if graph.has_node(input) {
264        return Ok(input.to_string());
265    }
266    let matches = graph.nodes_by_label(input);
267    match matches.len() {
268        0 => Err(RedDBError::NotFound(input.to_string())),
269        1 => Ok(matches.into_iter().next().unwrap().id),
270        n => Err(RedDBError::Query(format!(
271            "ambiguous graph node reference '{input}': matches {n} nodes by label; use the numeric id"
272        ))),
273    }
274}
275
276pub(super) fn stored_node_to_runtime(node: StoredNode) -> RuntimeGraphNode {
277    RuntimeGraphNode {
278        id: node.id,
279        label: node.label,
280        node_type: node.node_type.as_str().to_string(),
281        out_edge_count: node.out_edge_count,
282        in_edge_count: node.in_edge_count,
283    }
284}
285
286pub(super) fn path_to_runtime(
287    graph: &GraphStore,
288    path: &crate::storage::engine::pathfinding::Path,
289) -> RuntimeGraphPath {
290    let nodes = path
291        .nodes
292        .iter()
293        .filter_map(|id| graph.get_node(id))
294        .map(stored_node_to_runtime)
295        .collect();
296
297    let mut edges = Vec::new();
298    for index in 0..path.edge_types.len() {
299        let Some(source) = path.nodes.get(index) else {
300            continue;
301        };
302        let Some(target) = path.nodes.get(index + 1) else {
303            continue;
304        };
305        let Some(edge_type) = path.edge_types.get(index) else {
306            continue;
307        };
308        let weight = graph
309            .outgoing_edges(source)
310            .into_iter()
311            .find(|(candidate_type, candidate_target, _)| {
312                candidate_type.as_str() == edge_type.as_str() && candidate_target == target
313            })
314            .map(|(_, _, weight)| weight)
315            .unwrap_or(0.0);
316        edges.push(RuntimeGraphEdge {
317            source: source.clone(),
318            target: target.clone(),
319            edge_type: edge_type.as_str().to_string(),
320            weight,
321        });
322    }
323
324    RuntimeGraphPath {
325        hop_count: path.len(),
326        total_weight: path.total_weight,
327        nodes,
328        edges,
329    }
330}
331
332pub(super) fn cycle_to_runtime(
333    graph: &GraphStore,
334    cycle: crate::storage::engine::Cycle,
335) -> RuntimeGraphPath {
336    let nodes = cycle
337        .nodes
338        .iter()
339        .filter_map(|id| graph.get_node(id))
340        .map(stored_node_to_runtime)
341        .collect::<Vec<_>>();
342    let mut edges = Vec::new();
343    let mut total_weight = 0.0;
344
345    for window in cycle.nodes.windows(2) {
346        let Some(source) = window.first() else {
347            continue;
348        };
349        let Some(target) = window.get(1) else {
350            continue;
351        };
352        if let Some((edge_type, _, weight)) = graph
353            .outgoing_edges(source)
354            .into_iter()
355            .find(|(_, candidate_target, _)| candidate_target == target)
356        {
357            total_weight += weight as f64;
358            edges.push(RuntimeGraphEdge {
359                source: source.clone(),
360                target: target.clone(),
361                edge_type: edge_type.as_str().to_string(),
362                weight,
363            });
364        }
365    }
366
367    RuntimeGraphPath {
368        hop_count: cycle.length,
369        total_weight,
370        nodes,
371        edges,
372    }
373}
374
375pub(super) fn normalize_edge_filters(edge_labels: Option<Vec<String>>) -> Option<BTreeSet<String>> {
376    edge_labels
377        .map(|labels| {
378            labels
379                .into_iter()
380                .map(|label| normalize_graph_token(&label))
381                .filter(|label| !label.is_empty())
382                .collect()
383        })
384        .filter(|set: &BTreeSet<String>| !set.is_empty())
385}
386
387pub(super) fn merge_edge_filters(
388    edge_labels: Option<Vec<String>>,
389    projection: Option<&RuntimeGraphProjection>,
390) -> Option<BTreeSet<String>> {
391    let mut merged = BTreeSet::new();
392
393    if let Some(filters) = normalize_edge_filters(edge_labels) {
394        merged.extend(filters);
395    }
396
397    if let Some(filters) = projection
398        .and_then(|projection| normalize_token_filter_list(projection.edge_labels.clone()))
399    {
400        merged.extend(filters);
401    }
402
403    if merged.is_empty() {
404        None
405    } else {
406        Some(merged)
407    }
408}
409
410pub(super) fn merge_runtime_projection(
411    base: Option<RuntimeGraphProjection>,
412    overlay: Option<RuntimeGraphProjection>,
413) -> Option<RuntimeGraphProjection> {
414    let merge_list =
415        |left: Option<Vec<String>>, right: Option<Vec<String>>| -> Option<Vec<String>> {
416            let mut values = BTreeSet::new();
417            if let Some(left) = left {
418                values.extend(left);
419            }
420            if let Some(right) = right {
421                values.extend(right);
422            }
423            if values.is_empty() {
424                None
425            } else {
426                Some(values.into_iter().collect())
427            }
428        };
429
430    let _ = base.clone().or(overlay.clone())?;
431
432    Some(RuntimeGraphProjection {
433        node_labels: merge_list(
434            base.as_ref()
435                .and_then(|projection| projection.node_labels.clone()),
436            overlay
437                .as_ref()
438                .and_then(|projection| projection.node_labels.clone()),
439        ),
440        node_types: merge_list(
441            base.as_ref()
442                .and_then(|projection| projection.node_types.clone()),
443            overlay
444                .as_ref()
445                .and_then(|projection| projection.node_types.clone()),
446        ),
447        edge_labels: merge_list(
448            base.as_ref()
449                .and_then(|projection| projection.edge_labels.clone()),
450            overlay
451                .as_ref()
452                .and_then(|projection| projection.edge_labels.clone()),
453        ),
454    })
455}
456
457pub(super) fn edge_allowed(edge_label: &str, filters: Option<&BTreeSet<String>>) -> bool {
458    filters.is_none_or(|filters| filters.contains(&normalize_graph_token(edge_label)))
459}
460
461pub(super) fn graph_adjacent_edges(
462    graph: &GraphStore,
463    node: &str,
464    direction: RuntimeGraphDirection,
465    edge_filters: Option<&BTreeSet<String>>,
466) -> Vec<(String, RuntimeGraphEdge)> {
467    let mut adjacent = Vec::new();
468
469    if matches!(
470        direction,
471        RuntimeGraphDirection::Outgoing | RuntimeGraphDirection::Both
472    ) {
473        for (edge_type, target, weight) in graph.outgoing_edges(node) {
474            if edge_allowed(edge_type.as_str(), edge_filters) {
475                adjacent.push((
476                    target.clone(),
477                    RuntimeGraphEdge {
478                        source: node.to_string(),
479                        target,
480                        edge_type: edge_type.as_str().to_string(),
481                        weight,
482                    },
483                ));
484            }
485        }
486    }
487
488    if matches!(
489        direction,
490        RuntimeGraphDirection::Incoming | RuntimeGraphDirection::Both
491    ) {
492        for (edge_type, source, weight) in graph.incoming_edges(node) {
493            if edge_allowed(edge_type.as_str(), edge_filters) {
494                adjacent.push((
495                    source.clone(),
496                    RuntimeGraphEdge {
497                        source,
498                        target: node.to_string(),
499                        edge_type: edge_type.as_str().to_string(),
500                        weight,
501                    },
502                ));
503            }
504        }
505    }
506
507    adjacent
508}
509
510pub(super) fn push_runtime_edge(
511    edges: &mut Vec<RuntimeGraphEdge>,
512    seen_edges: &mut HashSet<(String, String, String, u32)>,
513    edge: RuntimeGraphEdge,
514) {
515    let key = (
516        edge.source.clone(),
517        edge.target.clone(),
518        edge.edge_type.clone(),
519        edge.weight.to_bits(),
520    );
521    if seen_edges.insert(key) {
522        edges.push(edge);
523    }
524}
525
526#[derive(Clone)]
527pub(super) struct RuntimeDijkstraState {
528    node: String,
529    cost: f64,
530}
531
532impl PartialEq for RuntimeDijkstraState {
533    fn eq(&self, other: &Self) -> bool {
534        self.node == other.node && self.cost == other.cost
535    }
536}
537
538impl Eq for RuntimeDijkstraState {}
539
540impl Ord for RuntimeDijkstraState {
541    fn cmp(&self, other: &Self) -> Ordering {
542        other
543            .cost
544            .partial_cmp(&self.cost)
545            .unwrap_or(Ordering::Equal)
546    }
547}
548
549impl PartialOrd for RuntimeDijkstraState {
550    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
551        Some(self.cmp(other))
552    }
553}
554
555pub(super) fn shortest_path_runtime(
556    graph: &GraphStore,
557    source: &str,
558    target: &str,
559    direction: RuntimeGraphDirection,
560    algorithm: RuntimeGraphPathAlgorithm,
561    edge_filters: Option<&BTreeSet<String>>,
562) -> RedDBResult<RuntimeGraphPathResult> {
563    let mut nodes_visited = 0;
564    let (path, negative_cycle_detected) = match algorithm {
565        RuntimeGraphPathAlgorithm::Bfs => {
566            let mut queue = VecDeque::new();
567            let mut visited = HashSet::new();
568            let mut previous: HashMap<String, (String, RuntimeGraphEdge)> = HashMap::new();
569
570            queue.push_back(source.to_string());
571            visited.insert(source.to_string());
572
573            while let Some(current) = queue.pop_front() {
574                nodes_visited += 1;
575                if current == target {
576                    break;
577                }
578                let mut adjacent = graph_adjacent_edges(graph, &current, direction, edge_filters);
579                adjacent.sort_by(|left, right| left.0.cmp(&right.0));
580                for (neighbor, edge) in adjacent {
581                    if visited.insert(neighbor.clone()) {
582                        previous.insert(neighbor.clone(), (current.clone(), edge));
583                        queue.push_back(neighbor);
584                    }
585                }
586            }
587
588            (rebuild_runtime_path(graph, source, target, &previous), None)
589        }
590        RuntimeGraphPathAlgorithm::Dijkstra | RuntimeGraphPathAlgorithm::AStar => {
591            let mut dist: HashMap<String, f64> = HashMap::new();
592            let mut previous: HashMap<String, (String, RuntimeGraphEdge)> = HashMap::new();
593            let mut heap = BinaryHeap::new();
594
595            dist.insert(source.to_string(), 0.0);
596            heap.push(RuntimeDijkstraState {
597                node: source.to_string(),
598                cost: 0.0,
599            });
600
601            while let Some(RuntimeDijkstraState { node, cost }) = heap.pop() {
602                nodes_visited += 1;
603                if node == target {
604                    break;
605                }
606                if let Some(best) = dist.get(&node) {
607                    if cost > *best {
608                        continue;
609                    }
610                }
611
612                let mut adjacent = graph_adjacent_edges(graph, &node, direction, edge_filters);
613                adjacent.sort_by(|left, right| left.0.cmp(&right.0));
614                for (neighbor, edge) in adjacent {
615                    let next_cost = cost + edge.weight as f64;
616                    if dist.get(&neighbor).is_none_or(|best| next_cost < *best) {
617                        dist.insert(neighbor.clone(), next_cost);
618                        previous.insert(neighbor.clone(), (node.clone(), edge));
619                        heap.push(RuntimeDijkstraState {
620                            node: neighbor,
621                            cost: next_cost,
622                        });
623                    }
624                }
625            }
626
627            (rebuild_runtime_path(graph, source, target, &previous), None)
628        }
629        RuntimeGraphPathAlgorithm::BellmanFord => {
630            let nodes: Vec<String> = graph.iter_nodes().map(|node| node.id.clone()).collect();
631            let mut dist: HashMap<String, f64> = nodes
632                .iter()
633                .map(|node| (node.clone(), f64::INFINITY))
634                .collect();
635            let mut previous: HashMap<String, (String, RuntimeGraphEdge)> = HashMap::new();
636
637            dist.insert(source.to_string(), 0.0);
638
639            for _ in 0..nodes.len().saturating_sub(1) {
640                let mut changed = false;
641
642                for node in &nodes {
643                    nodes_visited += 1;
644                    let Some(current_dist) = dist.get(node).copied() else {
645                        continue;
646                    };
647                    if !current_dist.is_finite() {
648                        continue;
649                    }
650
651                    let mut adjacent = graph_adjacent_edges(graph, node, direction, edge_filters);
652                    adjacent.sort_by(|left, right| left.0.cmp(&right.0));
653                    for (neighbor, edge) in adjacent {
654                        let next_cost = current_dist + edge.weight as f64;
655                        if dist.get(&neighbor).is_none_or(|best| next_cost < *best) {
656                            dist.insert(neighbor.clone(), next_cost);
657                            previous.insert(neighbor, (node.clone(), edge));
658                            changed = true;
659                        }
660                    }
661                }
662
663                if !changed {
664                    break;
665                }
666            }
667
668            let mut has_negative_cycle = false;
669            for node in &nodes {
670                let Some(current_dist) = dist.get(node).copied() else {
671                    continue;
672                };
673                if !current_dist.is_finite() {
674                    continue;
675                }
676
677                let adjacent = graph_adjacent_edges(graph, node, direction, edge_filters);
678                for (neighbor, edge) in adjacent {
679                    let next_cost = current_dist + edge.weight as f64;
680                    if dist.get(&neighbor).is_none_or(|best| next_cost < *best) {
681                        has_negative_cycle = true;
682                        break;
683                    }
684                }
685
686                if has_negative_cycle {
687                    break;
688                }
689            }
690
691            let path = if has_negative_cycle {
692                None
693            } else {
694                rebuild_runtime_path(graph, source, target, &previous)
695            };
696            (path, Some(has_negative_cycle))
697        }
698    };
699
700    Ok(RuntimeGraphPathResult {
701        source: source.to_string(),
702        target: target.to_string(),
703        direction,
704        algorithm,
705        nodes_visited,
706        negative_cycle_detected,
707        path,
708    })
709}
710
711pub(super) fn rebuild_runtime_path(
712    graph: &GraphStore,
713    source: &str,
714    target: &str,
715    previous: &HashMap<String, (String, RuntimeGraphEdge)>,
716) -> Option<RuntimeGraphPath> {
717    if source != target && !previous.contains_key(target) {
718        return None;
719    }
720
721    let mut node_ids = vec![target.to_string()];
722    let mut edges = Vec::new();
723    let mut current = target.to_string();
724
725    while current != source {
726        let (parent, edge) = previous.get(&current)?.clone();
727        edges.push(edge);
728        node_ids.push(parent.clone());
729        current = parent;
730    }
731
732    node_ids.reverse();
733    edges.reverse();
734
735    let total_weight = edges.iter().map(|edge| edge.weight as f64).sum();
736    let nodes = node_ids
737        .iter()
738        .filter_map(|id| graph.get_node(id))
739        .map(stored_node_to_runtime)
740        .collect();
741
742    Some(RuntimeGraphPath {
743        hop_count: node_ids.len().saturating_sub(1),
744        total_weight,
745        nodes,
746        edges,
747    })
748}
749
750pub(super) fn top_runtime_scores(
751    graph: &GraphStore,
752    scores: HashMap<String, f64>,
753    top_k: usize,
754) -> Vec<RuntimeGraphCentralityScore> {
755    let mut pairs: Vec<_> = scores.into_iter().collect();
756    pairs.sort_by(|left, right| {
757        right
758            .1
759            .partial_cmp(&left.1)
760            .unwrap_or(Ordering::Equal)
761            .then_with(|| left.0.cmp(&right.0))
762    });
763    pairs.truncate(top_k.max(1));
764    pairs
765        .into_iter()
766        .filter_map(|(node_id, score)| {
767            graph
768                .get_node(&node_id)
769                .map(|node| RuntimeGraphCentralityScore {
770                    node: stored_node_to_runtime(node),
771                    score,
772                })
773        })
774        .collect()
775}
776
777/// Normalise a user-supplied node-type token to its canonical lower-snake-case
778/// form. Pentest-flavoured aliases (`tech`, `cert`) are kept as a courtesy
779/// but the result is just a label string the caller can intern into the
780/// [`crate::storage::engine::graph_store::LabelRegistry`].
781pub(super) fn graph_node_label(input: &str) -> String {
782    let token = normalize_graph_token(input);
783    match token.as_str() {
784        "host" | "service" | "credential" | "vulnerability" | "endpoint" | "technology"
785        | "user" | "domain" | "certificate" => token,
786        "tech" => "technology".to_string(),
787        "cert" => "certificate".to_string(),
788        // Unknown token: pass through so callers can register new labels.
789        _ if !token.is_empty() => token,
790        _ => "endpoint".to_string(),
791    }
792}
793
794/// Edge-label counterpart to [`graph_node_label`].
795pub(super) fn graph_edge_label(input: &str) -> String {
796    let token = normalize_graph_token(input);
797    match token.as_str() {
798        "hasservice" => "has_service".to_string(),
799        "hasendpoint" => "has_endpoint".to_string(),
800        "usestech" | "usestechnology" => "uses_tech".to_string(),
801        "authaccess" | "hascredential" => "auth_access".to_string(),
802        "affectedby" => "affected_by".to_string(),
803        "contains" => "contains".to_string(),
804        "connectsto" | "connects" => "connects_to".to_string(),
805        "relatedto" | "related" => "related_to".to_string(),
806        "hasuser" => "has_user".to_string(),
807        "hascert" | "hascertificate" => "has_cert".to_string(),
808        _ if !token.is_empty() => token,
809        _ => "related_to".to_string(),
810    }
811}
812
813pub(super) fn normalize_graph_token(input: &str) -> String {
814    input
815        .chars()
816        .filter(|ch| ch.is_ascii_alphanumeric())
817        .flat_map(|ch| ch.to_lowercase())
818        .collect()
819}
820
821#[derive(Debug, Clone)]
822pub struct RuntimeGraphPattern {
823    pub node_label: Option<String>,
824    pub node_type: Option<String>,
825    pub edge_labels: Vec<String>,
826}
827
828#[derive(Debug, Clone, Default)]
829pub struct RuntimeGraphProjection {
830    pub node_labels: Option<Vec<String>>,
831    pub node_types: Option<Vec<String>>,
832    pub edge_labels: Option<Vec<String>>,
833}
834
835#[derive(Debug, Clone, Copy)]
836pub struct RuntimeQueryWeights {
837    pub vector: f32,
838    pub graph: f32,
839    pub filter: f32,
840}
841
842#[derive(Debug, Clone)]
843pub struct RuntimeFilter {
844    pub field: String,
845    pub op: String,
846    pub value: Option<RuntimeFilterValue>,
847}
848
849#[derive(Debug, Clone)]
850pub enum RuntimeFilterValue {
851    String(String),
852    Int(i64),
853    Float(f64),
854    Bool(bool),
855    Null,
856    List(Vec<RuntimeFilterValue>),
857    Range(Box<RuntimeFilterValue>, Box<RuntimeFilterValue>),
858}
859
860pub(super) fn runtime_filter_to_dsl(filter: RuntimeFilter) -> RedDBResult<DslFilter> {
861    Ok(DslFilter {
862        field: filter.field,
863        op: parse_runtime_filter_op(&filter.op)?,
864        value: match filter.value {
865            Some(value) => runtime_filter_value_to_dsl(value),
866            None => DslFilterValue::Null,
867        },
868    })
869}
870
871pub(super) fn parse_runtime_filter_op(op: &str) -> RedDBResult<DslFilterOp> {
872    match op.trim().to_ascii_lowercase().as_str() {
873        "eq" | "equals" => Ok(DslFilterOp::Equals),
874        "ne" | "not_equals" | "not-equals" => Ok(DslFilterOp::NotEquals),
875        "gt" | "greater_than" | "greater-than" => Ok(DslFilterOp::GreaterThan),
876        "gte" | "greater_than_or_equals" | "greater-than-or-equals" => {
877            Ok(DslFilterOp::GreaterThanOrEquals)
878        }
879        "lt" | "less_than" | "less-than" => Ok(DslFilterOp::LessThan),
880        "lte" | "less_than_or_equals" | "less-than-or-equals" => Ok(DslFilterOp::LessThanOrEquals),
881        "contains" => Ok(DslFilterOp::Contains),
882        "starts_with" | "starts-with" => Ok(DslFilterOp::StartsWith),
883        "ends_with" | "ends-with" => Ok(DslFilterOp::EndsWith),
884        "in" | "in_list" | "in-list" => Ok(DslFilterOp::In),
885        "between" => Ok(DslFilterOp::Between),
886        "is_null" | "is-null" => Ok(DslFilterOp::IsNull),
887        "is_not_null" | "is-not-null" => Ok(DslFilterOp::IsNotNull),
888        other => Err(RedDBError::Query(format!(
889            "unsupported hybrid filter op: {other}"
890        ))),
891    }
892}
893
894pub(super) fn runtime_filter_value_to_dsl(value: RuntimeFilterValue) -> DslFilterValue {
895    match value {
896        RuntimeFilterValue::String(value) => DslFilterValue::String(value),
897        RuntimeFilterValue::Int(value) => DslFilterValue::Int(value),
898        RuntimeFilterValue::Float(value) => DslFilterValue::Float(value),
899        RuntimeFilterValue::Bool(value) => DslFilterValue::Bool(value),
900        RuntimeFilterValue::Null => DslFilterValue::Null,
901        RuntimeFilterValue::List(values) => DslFilterValue::List(
902            values
903                .into_iter()
904                .map(runtime_filter_value_to_dsl)
905                .collect(),
906        ),
907        RuntimeFilterValue::Range(start, end) => DslFilterValue::Range(
908            Box::new(runtime_filter_value_to_dsl(*start)),
909            Box::new(runtime_filter_value_to_dsl(*end)),
910        ),
911    }
912}