Skip to main content

omgbase_surface/
graph.rs

1//! The `graph` neighborhood macro (`spec/surface/README.md` §4): compiled to
2//! an OQX `follow doc.out` / `doc.in` walk run through the shared runner and
3//! shaped into `{ documents, edges, frontier }`. Port of
4//! `packages/core/src/mcp/graph.ts`; nothing here walks the graph itself.
5
6use std::cmp::Ordering;
7use std::collections::HashMap;
8
9use omgbase_search::EmbeddingProvider;
10use omgbase_store::Store;
11use serde_json::{Map, Value as Json, json};
12
13use crate::error::{Result, SurfaceError};
14use crate::query::{QueryOptions, query};
15use crate::read::find_doc_by_ref;
16
17const DEFAULT_DEGREES: i64 = 1;
18const DEFAULT_MAX_DOCUMENTS: i64 = 200;
19const MAX_DEPTH: i64 = 8;
20
21/// `graph`'s arguments.
22#[derive(Clone, Debug, Default)]
23pub struct GraphArgs {
24    pub roots: Vec<String>,
25    pub degrees: Option<i64>,
26    /// `in` | `out` | `both` (default).
27    pub direction: Option<String>,
28    pub predicate: Option<String>,
29    pub select: Vec<String>,
30    pub max_documents: Option<i64>,
31}
32
33const EDGE_COLLECT: &str = "{ id: $id, src: $src, dst: $dst, dst_path: $dst_path, dst_uri: $dst_uri, dst_kind: dst_kind, predicate: predicate, provenance: provenance, anchor: anchor, src_field: src_field }";
34
35fn build_user_select(select: &[String]) -> (String, Vec<Option<String>>) {
36    let mut items = Vec::new();
37    let mut out_names: Vec<Option<String>> = vec![None; select.len()];
38    let mut used: Vec<String> = Vec::new();
39    for (i, expr) in select.iter().enumerate() {
40        let trimmed = expr.trim();
41        if trimmed.is_empty() {
42            continue;
43        }
44        let ident = trimmed.strip_prefix('$').unwrap_or(trimmed);
45        let is_ident = ident
46            .chars()
47            .next()
48            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
49            && ident.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
50        let mut name = if is_ident {
51            ident.to_owned()
52        } else {
53            format!("sel_{i}")
54        };
55        while used.contains(&name) {
56            name = format!("{name}_{i}");
57        }
58        used.push(name.clone());
59        out_names[i] = Some(name);
60        items.push(format!("_u{i}: {trimmed}"));
61    }
62    let clause = if items.is_empty() {
63        String::new()
64    } else {
65        format!(", {}", items.join(", "))
66    };
67    (clause, out_names)
68}
69
70fn build_query(seed: &str, dir: &str, depth: i64, user_select: &str) -> String {
71    format!(
72        "select _depth: $depth, _stop: $stop, _edges: doc.{dir}_edges collect {EDGE_COLLECT}{user_select} from docs where {seed} follow distinct doc.{dir} {{ depth {depth} }}"
73    )
74}
75
76/// Bytewise order (§9: the reference's `localeCompare` was replaced).
77fn locale_compare(a: &str, b: &str) -> Ordering {
78    a.cmp(b)
79}
80
81struct Doc {
82    id: String,
83    path: String,
84    degree: i64,
85    extra: Vec<(String, Json)>,
86}
87
88/// Run the macro.
89pub fn graph_neighborhood(
90    store: &Store,
91    repo_id: &str,
92    args: &GraphArgs,
93    provider: Option<&dyn EmbeddingProvider>,
94) -> Result<Json> {
95    if args.roots.is_empty() {
96        return Err(SurfaceError::new(
97            "target_missing",
98            "graph requires at least one root (path or id)",
99        ));
100    }
101    let mut root_ids: Vec<String> = Vec::new();
102    for r in &args.roots {
103        let Some(info) = find_doc_by_ref(store.conn(), repo_id, r)? else {
104            return Err(SurfaceError::with_data(
105                "doc_missing",
106                format!("no document for {}", Json::String(r.clone())),
107                json!({ "root": r }),
108            ));
109        };
110        if !root_ids.contains(&info.doc_id) {
111            root_ids.push(info.doc_id);
112        }
113    }
114    let degrees = args.degrees.unwrap_or(DEFAULT_DEGREES).max(0);
115    let depth = MAX_DEPTH.min(degrees + 1);
116    let effective_degrees = depth - 1;
117    let direction = args.direction.clone().unwrap_or_else(|| "both".to_owned());
118    let max_documents =
119        usize::try_from(args.max_documents.unwrap_or(DEFAULT_MAX_DOCUMENTS).max(1)).unwrap_or(1);
120    let dirs: Vec<&str> = match direction.as_str() {
121        "both" => vec!["out", "in"],
122        "in" => vec!["in"],
123        _ => vec!["out"],
124    };
125    let seed = root_ids
126        .iter()
127        .map(|id| format!("$id == {}", Json::String(id.clone())))
128        .collect::<Vec<_>>()
129        .join(" || ");
130    let (user_select, out_names) = build_user_select(&args.select);
131
132    let mut queries = Vec::new();
133    let mut docs: Vec<Doc> = Vec::new();
134    let mut edges: Vec<Json> = Vec::new();
135    let mut query_truncated = false;
136    for dir in &dirs {
137        let q = build_query(&seed, dir, depth, &user_select);
138        queries.push(q.clone());
139        let res = query(
140            store,
141            repo_id,
142            &q,
143            QueryOptions {
144                limit: Some(max_documents + 1),
145                cursor: None,
146                provider,
147            },
148        )?;
149        if res.truncated {
150            query_truncated = true;
151        }
152        for hit in &res.hits {
153            let id = hit["id"].as_str().unwrap_or_default().to_owned();
154            let path = hit["path"].as_str().unwrap_or_default().to_owned();
155            let hop = hit["_depth"].as_f64().unwrap_or(f64::NAN);
156            let degree = (hop - 1.0) as i64;
157            let replace = docs
158                .iter()
159                .position(|d| d.id == id)
160                .map(|i| (i, degree < docs[i].degree));
161            match replace {
162                Some((_, false)) => {}
163                found => {
164                    let extra: Vec<(String, Json)> = out_names
165                        .iter()
166                        .enumerate()
167                        .filter_map(|(i, n)| {
168                            n.as_ref().map(|name| {
169                                (
170                                    name.clone(),
171                                    hit.get(format!("_u{i}")).cloned().unwrap_or(Json::Null),
172                                )
173                            })
174                        })
175                        .collect();
176                    let doc = Doc {
177                        id: id.clone(),
178                        path,
179                        degree,
180                        extra,
181                    };
182                    match found {
183                        Some((i, true)) => docs[i] = doc,
184                        _ => docs.push(doc),
185                    }
186                }
187            }
188            if let Some(raw) = hit["_edges"].as_array() {
189                for e in raw {
190                    let eid = e["id"].as_str().unwrap_or_default();
191                    if !edges.iter().any(|x| x["id"].as_str() == Some(eid)) {
192                        edges.push(e.clone());
193                    }
194                }
195            }
196        }
197    }
198
199    if let Some(p) = &args.predicate {
200        let mut adj: HashMap<String, Vec<String>> = HashMap::new();
201        for e in &edges {
202            if e["predicate"].as_str() != Some(p.as_str()) {
203                continue;
204            }
205            let src = e["src"].as_str().unwrap_or_default().to_owned();
206            let dst = e["dst"].as_str().unwrap_or_default().to_owned();
207            if dirs.contains(&"out") {
208                adj.entry(src.clone()).or_default().push(dst.clone());
209            }
210            if dirs.contains(&"in") {
211                adj.entry(dst).or_default().push(src);
212            }
213        }
214        let mut depth_of: Vec<(String, i64)> = root_ids.iter().map(|id| (id.clone(), 0)).collect();
215        let mut wave: Vec<String> = root_ids.clone();
216        let mut lvl = 1;
217        while lvl <= effective_degrees && !wave.is_empty() {
218            let mut next = Vec::new();
219            for from in &wave {
220                for to in adj.get(from).map_or(&[][..], Vec::as_slice) {
221                    if docs.iter().any(|d| &d.id == to) && !depth_of.iter().any(|(id, _)| id == to)
222                    {
223                        depth_of.push((to.clone(), lvl));
224                        next.push(to.clone());
225                    }
226                }
227            }
228            wave = next;
229            lvl += 1;
230        }
231        let mut restricted: Vec<Doc> = Vec::new();
232        for (id, d) in depth_of {
233            if let Some(orig) = docs.iter().find(|x| x.id == id) {
234                restricted.push(Doc {
235                    id: orig.id.clone(),
236                    path: orig.path.clone(),
237                    degree: d,
238                    extra: orig.extra.clone(),
239                });
240            }
241        }
242        docs = restricted;
243    }
244
245    docs.sort_by(|a, b| {
246        a.degree
247            .cmp(&b.degree)
248            .then_with(|| locale_compare(&a.path, &b.path))
249    });
250    let capped = docs.len() > max_documents;
251    docs.truncate(max_documents);
252    let truncated = query_truncated || capped;
253
254    let mut frontier = Vec::new();
255    let documents: Vec<Json> = docs
256        .iter()
257        .map(|d| {
258            let is_frontier = d.degree == effective_degrees;
259            if is_frontier {
260                frontier.push(json!({ "id": d.id, "path": d.path, "degree": d.degree }));
261            }
262            let mut m = Map::new();
263            m.insert("id".to_owned(), json!(d.id));
264            m.insert("path".to_owned(), json!(d.path));
265            m.insert("degree".to_owned(), json!(d.degree));
266            m.insert("frontier".to_owned(), json!(is_frontier));
267            for (k, v) in &d.extra {
268                m.insert(k.clone(), v.clone());
269            }
270            Json::Object(m)
271        })
272        .collect();
273
274    let reached = |id: &str| docs.iter().any(|d| d.id == id);
275    let mut kept: Vec<Json> = edges
276        .into_iter()
277        .filter(|e| {
278            if let Some(p) = &args.predicate {
279                if e["predicate"].as_str() != Some(p.as_str()) {
280                    return false;
281                }
282            }
283            let src_in = reached(e["src"].as_str().unwrap_or_default());
284            let dst_kind = e["dst_kind"].as_str().unwrap_or_default();
285            let dst_dangling =
286                dst_kind == "external" || (dst_kind == "document" && e["dst_path"].is_null());
287            let dst_in = reached(e["dst"].as_str().unwrap_or_default()) || dst_dangling;
288            src_in && dst_in
289        })
290        .collect();
291    kept.sort_by(|a, b| {
292        let (sa, sb) = (
293            a["src"].as_str().unwrap_or_default(),
294            b["src"].as_str().unwrap_or_default(),
295        );
296        if sa == sb {
297            locale_compare(
298                a["id"].as_str().unwrap_or_default(),
299                b["id"].as_str().unwrap_or_default(),
300            )
301        } else {
302            locale_compare(sa, sb)
303        }
304    });
305
306    Ok(json!({
307        "roots": root_ids,
308        "degrees": effective_degrees,
309        "direction": direction,
310        "documents": documents,
311        "edges": kept,
312        "frontier": frontier,
313        "truncated": truncated,
314        "queries": queries,
315    }))
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn user_select_aliases() {
324        let (clause, names) = build_user_select(&[
325            "layer".into(),
326            "$path".into(),
327            "a + 1".into(),
328            "layer".into(),
329        ]);
330        assert_eq!(clause, ", _u0: layer, _u1: $path, _u2: a + 1, _u3: layer");
331        assert_eq!(
332            names,
333            [
334                Some("layer".into()),
335                Some("path".into()),
336                Some("sel_2".into()),
337                Some("layer_3".into())
338            ]
339        );
340        assert_eq!(build_user_select(&[]).0, "");
341    }
342
343    #[test]
344    fn query_shape() {
345        let q = build_query("$id == \"d_0\"", "out", 2, "");
346        assert!(
347            q.starts_with("select _depth: $depth, _stop: $stop, _edges: doc.out_edges collect {")
348        );
349        assert!(q.ends_with("from docs where $id == \"d_0\" follow distinct doc.out { depth 2 }"));
350        assert!(oqx::parse_string(&q).is_ok());
351    }
352
353    #[test]
354    fn order_is_bytewise() {
355        assert_eq!(locale_compare("B", "a"), Ordering::Less);
356        assert_eq!(locale_compare("a", "b"), Ordering::Less);
357    }
358}