nodedb 0.4.0

Local-first, real-time, edge-to-cloud hybrid database for multi-modal workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// SPDX-License-Identifier: BUSL-1.1

//! Graph operation plan builders.

use nodedb_types::protocol::TextFields;
use sonic_rs;

use crate::bridge::envelope::PhysicalPlan;
use crate::control::server::native::dispatch::DispatchCtx;
use crate::engine::graph::traversal_options::MAX_GRAPH_TRAVERSAL_DEPTH;
use nodedb_physical::physical_plan::GraphOp;

use super::parse_direction;

/// Clamp a depth parameter coming in over the native protocol,
/// rejecting out-of-range values rather than forwarding them to the
/// engine. Mirrors the pgwire ingress so no entry point can saturate
/// traversal with an unbounded fan-out.
fn clamped_depth(value: Option<u32>, default: usize, field: &str) -> crate::Result<usize> {
    let v = value.map(|v| v as usize).unwrap_or(default);
    if v > MAX_GRAPH_TRAVERSAL_DEPTH {
        return Err(crate::Error::BadRequest {
            detail: format!(
                "{field} {v} exceeds maximum allowed value {MAX_GRAPH_TRAVERSAL_DEPTH}"
            ),
        });
    }
    Ok(v)
}

pub(crate) fn build_rag_fusion(
    fields: &TextFields,
    collection: &str,
) -> crate::Result<PhysicalPlan> {
    let query_vector = fields
        .query_vector
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'query_vector'".to_string(),
        })?;
    Ok(PhysicalPlan::Graph(GraphOp::RagFusion {
        collection: collection.to_string(),
        query_vector: query_vector.clone(),
        vector_top_k: fields.vector_top_k.unwrap_or(20) as usize,
        edge_label: fields.edge_label.clone(),
        direction: parse_direction(fields.direction.as_deref()),
        expansion_depth: clamped_depth(fields.expansion_depth, 2, "expansion_depth")?,
        final_top_k: fields.final_top_k.unwrap_or(10) as usize,
        rrf_k: (
            fields.vector_k.unwrap_or(60.0),
            fields.graph_k.unwrap_or(10.0),
        ),
        rrf_k_triple: None,
        vector_field: fields.vector_field.clone().unwrap_or_default(),
        options: Default::default(),
        bm25_query: None,
        bm25_field: None,
    }))
}

pub(crate) fn build_hop(fields: &TextFields) -> crate::Result<PhysicalPlan> {
    let start = fields
        .start_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'start_node'".to_string(),
        })?;
    Ok(PhysicalPlan::Graph(GraphOp::Hop {
        start_nodes: vec![start.clone()],
        depth: clamped_depth(fields.depth, 2, "depth")?,
        edge_label: fields.edge_label.clone(),
        direction: parse_direction(fields.direction.as_deref()),
        options: Default::default(),
        rls_filters: Vec::new(),
        frontier_bitmap: None,
    }))
}

pub(crate) fn build_neighbors(fields: &TextFields) -> crate::Result<PhysicalPlan> {
    let start = fields
        .start_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'start_node'".to_string(),
        })?;
    Ok(PhysicalPlan::Graph(GraphOp::Neighbors {
        node_id: start.clone(),
        edge_label: fields.edge_label.clone(),
        direction: parse_direction(fields.direction.as_deref()),
        rls_filters: Vec::new(),
    }))
}

pub(crate) fn build_path(fields: &TextFields) -> crate::Result<PhysicalPlan> {
    let from = fields
        .start_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'start_node'".to_string(),
        })?;
    let to = fields
        .end_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'end_node'".to_string(),
        })?;
    Ok(PhysicalPlan::Graph(GraphOp::Path {
        src: from.clone(),
        dst: to.clone(),
        max_depth: clamped_depth(fields.depth, 10, "depth")?,
        edge_label: fields.edge_label.clone(),
        options: Default::default(),
        rls_filters: Vec::new(),
        frontier_bitmap: None,
    }))
}

pub(crate) fn build_subgraph(fields: &TextFields) -> crate::Result<PhysicalPlan> {
    let start = fields
        .start_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'start_node'".to_string(),
        })?;
    Ok(PhysicalPlan::Graph(GraphOp::Subgraph {
        start_nodes: vec![start.clone()],
        depth: clamped_depth(fields.depth, 2, "depth")?,
        edge_label: fields.edge_label.clone(),
        options: Default::default(),
        rls_filters: Vec::new(),
    }))
}

pub(crate) fn build_edge_put(
    ctx: &DispatchCtx<'_>,
    fields: &TextFields,
    collection: &str,
) -> crate::Result<PhysicalPlan> {
    if collection.is_empty() {
        return Err(crate::Error::BadRequest {
            detail: "edge PUT requires a non-empty collection".to_string(),
        });
    }
    let src = fields
        .from_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'from_node'".to_string(),
        })?;
    let dst = fields
        .to_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'to_node'".to_string(),
        })?;
    let label = fields
        .edge_type
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'edge_type'".to_string(),
        })?;
    let props = match fields.properties.as_ref() {
        Some(v) => sonic_rs::to_string(v).map_err(|e| crate::Error::BadRequest {
            detail: format!("edge properties are not serializable to JSON: {e}"),
        })?,
        None => String::new(),
    };
    let src_surrogate = ctx.state.surrogate_assigner.assign(
        ctx.database_id(),
        ctx.tenant_id(),
        collection,
        src.as_bytes(),
    )?;
    let dst_surrogate = ctx.state.surrogate_assigner.assign(
        ctx.database_id(),
        ctx.tenant_id(),
        collection,
        dst.as_bytes(),
    )?;
    Ok(PhysicalPlan::Graph(GraphOp::EdgePut {
        collection: collection.to_string(),
        src_id: src.clone(),
        label: label.clone(),
        dst_id: dst.clone(),
        properties: props.into_bytes(),
        src_surrogate,
        dst_surrogate,
    }))
}

pub(crate) fn build_edge_delete(
    ctx: &DispatchCtx<'_>,
    fields: &TextFields,
    collection: &str,
) -> crate::Result<PhysicalPlan> {
    if collection.is_empty() {
        return Err(crate::Error::BadRequest {
            detail: "edge DELETE requires a non-empty collection".to_string(),
        });
    }
    let src = fields
        .from_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'from_node'".to_string(),
        })?;
    let dst = fields
        .to_node
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'to_node'".to_string(),
        })?;
    let label = fields
        .edge_type
        .as_ref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'edge_type'".to_string(),
        })?;
    // Resolve endpoint surrogates exactly as `build_edge_put` does (get-or-assign
    // returns the existing node identities) so a cross-shard delete dual-homes
    // and locks against a concurrent insert of the same edge.
    let src_surrogate = ctx.state.surrogate_assigner.assign(
        ctx.database_id(),
        ctx.tenant_id(),
        collection,
        src.as_bytes(),
    )?;
    let dst_surrogate = ctx.state.surrogate_assigner.assign(
        ctx.database_id(),
        ctx.tenant_id(),
        collection,
        dst.as_bytes(),
    )?;
    Ok(PhysicalPlan::Graph(GraphOp::EdgeDelete {
        collection: collection.to_string(),
        src_id: src.clone(),
        label: label.clone(),
        dst_id: dst.clone(),
        src_surrogate,
        dst_surrogate,
    }))
}

pub(crate) fn build_algo(fields: &TextFields, collection: &str) -> crate::Result<PhysicalPlan> {
    let algo_name = fields
        .algorithm
        .as_deref()
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'algorithm'".to_string(),
        })?;

    let algorithm = match algo_name.to_lowercase().as_str() {
        "pagerank" => crate::engine::graph::algo::params::GraphAlgorithm::PageRank,
        "wcc" => crate::engine::graph::algo::params::GraphAlgorithm::Wcc,
        "label_propagation" => crate::engine::graph::algo::params::GraphAlgorithm::LabelPropagation,
        "lcc" => crate::engine::graph::algo::params::GraphAlgorithm::Lcc,
        "sssp" => crate::engine::graph::algo::params::GraphAlgorithm::Sssp,
        "betweenness" => crate::engine::graph::algo::params::GraphAlgorithm::Betweenness,
        "closeness" => crate::engine::graph::algo::params::GraphAlgorithm::Closeness,
        "harmonic" => crate::engine::graph::algo::params::GraphAlgorithm::Harmonic,
        "degree" => crate::engine::graph::algo::params::GraphAlgorithm::Degree,
        "louvain" => crate::engine::graph::algo::params::GraphAlgorithm::Louvain,
        "triangles" => crate::engine::graph::algo::params::GraphAlgorithm::Triangles,
        "diameter" => crate::engine::graph::algo::params::GraphAlgorithm::Diameter,
        "kcore" => crate::engine::graph::algo::params::GraphAlgorithm::KCore,
        other => {
            return Err(crate::Error::BadRequest {
                detail: format!("unknown graph algorithm: {other}"),
            });
        }
    };

    let personalization_vector = parse_algo_personalization(fields.algo_params.as_ref())?;

    let params = crate::engine::graph::algo::params::AlgoParams {
        collection: collection.to_string(),
        edge_label: None,
        source_node: fields.start_node.clone(),
        max_iterations: fields.depth.map(|d| d as usize),
        tolerance: None,
        damping: None,
        sample_size: None,
        direction: fields.direction.clone(),
        resolution: None,
        mode: None,
        personalization_vector,
    };

    Ok(PhysicalPlan::Graph(GraphOp::Algo { algorithm, params }))
}

/// Extract the Personalized PageRank seed map from the raw-protocol
/// `algo_params` object (`{"personalization_vector": {"alice": 1.0, …}}`).
///
/// Returns `Ok(None)` when absent or empty. A present-but-malformed value
/// (not an object, or a non-numeric weight) surfaces a structured
/// `BadRequest` rather than being silently dropped. Parses the JSON object
/// directly (no runtime JSON de/serialization functions).
fn parse_algo_personalization(
    algo_params: Option<&serde_json::Value>,
) -> crate::Result<Option<std::collections::HashMap<String, f64>>> {
    let Some(pv) = algo_params.and_then(|p| p.get("personalization_vector")) else {
        return Ok(None);
    };
    if pv.is_null() {
        return Ok(None);
    }
    let obj = pv.as_object().ok_or_else(|| crate::Error::BadRequest {
        detail: "personalization_vector must be a JSON object of node_id → weight".to_string(),
    })?;
    let mut map = std::collections::HashMap::with_capacity(obj.len());
    for (node, weight) in obj {
        let w = weight.as_f64().ok_or_else(|| crate::Error::BadRequest {
            detail: format!("personalization_vector weight for '{node}' must be a number"),
        })?;
        map.insert(node.clone(), w);
    }
    if map.is_empty() {
        return Ok(None);
    }
    Ok(Some(map))
}

pub(crate) fn build_match(fields: &TextFields, _collection: &str) -> crate::Result<PhysicalPlan> {
    let query_str = fields
        .match_query
        .as_ref()
        .or(fields.sql.as_ref())
        .ok_or_else(|| crate::Error::BadRequest {
            detail: "missing 'match_query'".to_string(),
        })?;

    // Serialize the MATCH query string as MessagePack for the Data Plane.
    let query = zerompk::to_msgpack_vec(query_str).map_err(|e| crate::Error::Serialization {
        format: "msgpack".into(),
        detail: format!("match query serialization: {e}"),
    })?;

    Ok(PhysicalPlan::Graph(GraphOp::Match {
        query,
        frontier_bitmap: None,
        // B1: native MATCH stays single-node; B2 wires cluster orchestration.
        cluster_mode: false,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn algo_fields(algo_params: Option<serde_json::Value>) -> TextFields {
        TextFields {
            algorithm: Some("pagerank".to_string()),
            algo_params,
            ..Default::default()
        }
    }

    fn params_of(plan: PhysicalPlan) -> crate::engine::graph::algo::params::AlgoParams {
        let PhysicalPlan::Graph(GraphOp::Algo { params, .. }) = plan else {
            panic!("expected GraphOp::Algo");
        };
        params
    }

    #[test]
    fn build_algo_parses_personalization_from_algo_params() {
        let fields = algo_fields(Some(json!({
            "personalization_vector": { "alice": 1.0, "bob": 0.5 }
        })));
        let pv = params_of(build_algo(&fields, "social").unwrap())
            .personalization_vector
            .expect("personalization present");
        assert_eq!(pv.get("alice"), Some(&1.0));
        assert_eq!(pv.get("bob"), Some(&0.5));
    }

    #[test]
    fn build_algo_without_personalization_is_none() {
        assert!(
            params_of(build_algo(&algo_fields(None), "social").unwrap())
                .personalization_vector
                .is_none()
        );
        // An algo_params object that omits the key is also None.
        let fields = algo_fields(Some(json!({ "other": 1 })));
        assert!(
            params_of(build_algo(&fields, "social").unwrap())
                .personalization_vector
                .is_none()
        );
    }

    #[test]
    fn build_algo_rejects_non_numeric_weight() {
        let fields = algo_fields(Some(
            json!({ "personalization_vector": { "alice": "high" } }),
        ));
        assert!(build_algo(&fields, "social").is_err());
    }

    #[test]
    fn build_algo_rejects_non_object_personalization() {
        let fields = algo_fields(Some(json!({ "personalization_vector": [1, 2, 3] })));
        assert!(build_algo(&fields, "social").is_err());
    }
}