1use std::cmp::Ordering;
11use std::collections::HashMap;
12
13use omgbase_search::EmbeddingProvider;
14use omgbase_store::Store;
15use oqx::ast::{BinaryOp, Consumer, FollowDestination, SelectItem, Where};
16use oqx::{build, print_query};
17use serde_json::{Map, Value as Json, json};
18
19use crate::error::{Result, SurfaceError};
20use crate::query::{QueryOptions, query};
21use crate::read::find_doc_by_ref;
22
23const DEFAULT_DEGREES: i64 = 1;
24const DEFAULT_MAX_DOCUMENTS: i64 = 200;
25const MAX_DEPTH: i64 = 8;
26
27#[derive(Clone, Debug, Default)]
29pub struct GraphArgs {
30 pub roots: Vec<String>,
31 pub degrees: Option<i64>,
32 pub direction: Option<String>,
34 pub predicate: Option<String>,
35 pub select: Vec<String>,
36 pub max_documents: Option<i64>,
37}
38
39const EDGE_FIELDS: [&str; 12] = [
45 "id",
46 "doc_id",
47 "block_id",
48 "via_id",
49 "dst_id",
50 "dst_path",
51 "uri",
52 "dst_kind",
53 "predicate",
54 "provenance",
55 "anchor",
56 "field",
57];
58
59fn build_user_select(select: &[String]) -> Result<(Vec<SelectItem>, Vec<Option<String>>)> {
66 let mut items = Vec::new();
67 let mut out_names: Vec<Option<String>> = vec![None; select.len()];
68 let mut used: Vec<String> = Vec::new();
69 for (i, expr) in select.iter().enumerate() {
70 let trimmed = expr.trim();
71 if trimmed.is_empty() {
72 continue;
73 }
74 let ident = trimmed.strip_prefix('$').unwrap_or(trimmed);
79 let is_ident = ident
80 .chars()
81 .next()
82 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
83 && ident.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
84 let mut name = if is_ident {
85 trimmed.to_owned()
86 } else {
87 format!("sel_{i}")
88 };
89 if name != "id" && name != "path" {
93 while used.contains(&name) {
94 name = format!("{name}_{i}");
95 }
96 used.push(name.clone());
97 }
98 out_names[i] = Some(name);
99 let parsed = oqx::parse_string(&format!("select _u{i}: {trimmed} from docs"))?;
100 items.extend(parsed.select);
101 }
102 Ok((items, out_names))
103}
104
105fn build_query(root_ids: &[String], dir: &str, depth: u32, user_select: &[SelectItem]) -> String {
114 let mut edges_body = build::subquery();
115 edges_body.select = EDGE_FIELDS
116 .iter()
117 .map(|name| build::field(name, build::ident(name)))
118 .collect();
119 let edges = build::op(
120 build::path(&["doc", &format!("{dir}_links")]),
121 Consumer::Collect,
122 edges_body,
123 );
124 let mut seed: Vec<Where> = root_ids
125 .iter()
126 .map(|id| {
127 build::scalar(build::binary(
128 BinaryOp::Eq,
129 build::ident("id"),
130 build::lit(id.as_str()),
131 ))
132 })
133 .collect();
134 let mut q = build::query(build::ident("docs"));
135 q.select = vec![
136 build::field("_depth", build::ident("$depth")),
137 build::field("_stop", build::ident("$stop")),
138 build::collect("_links", edges),
139 ];
140 q.select.extend(user_select.iter().cloned());
141 q.r#where = Some(if seed.len() == 1 {
142 seed.pop().expect("one seed")
143 } else {
144 build::or(seed)
145 });
146 let mut step = build::subquery();
148 step.from = vec![build::ident(if dir == "out" { "dst" } else { "doc" })];
149 step.depth = Some(depth);
150 let mut walk = build::follow(vec![FollowDestination::Block(Box::new(build::op(
151 build::ident(&format!("{dir}_links")),
152 Consumer::Collect,
153 step,
154 )))]);
155 walk.distinct = true;
156 q.follow = Some(walk);
157 print_query(&q).expect("a built query has no bindings")
158}
159
160fn locale_compare(a: &str, b: &str) -> Ordering {
162 a.cmp(b)
163}
164
165struct Doc {
166 id: String,
167 path: String,
168 degree: i64,
169 extra: Vec<(String, Json)>,
170}
171
172pub fn graph_neighborhood(
174 store: &Store,
175 repo_id: &str,
176 args: &GraphArgs,
177 provider: Option<&dyn EmbeddingProvider>,
178) -> Result<Json> {
179 if args.roots.is_empty() {
180 return Err(SurfaceError::new(
181 "target_missing",
182 "graph requires at least one root (path or id)",
183 ));
184 }
185 let mut root_ids: Vec<String> = Vec::new();
186 for r in &args.roots {
187 let Some(info) = find_doc_by_ref(store.conn(), repo_id, r)? else {
188 return Err(SurfaceError::with_data(
189 "doc_missing",
190 format!("no document for {}", Json::String(r.clone())),
191 json!({ "root": r }),
192 ));
193 };
194 if !root_ids.contains(&info.doc_id) {
195 root_ids.push(info.doc_id);
196 }
197 }
198 let degrees = args.degrees.unwrap_or(DEFAULT_DEGREES).max(0);
199 let depth = MAX_DEPTH.min(degrees + 1);
200 let walk_depth = u32::try_from(depth).expect("1..=8");
201 let effective_degrees = depth - 1;
202 let direction = args.direction.clone().unwrap_or_else(|| "both".to_owned());
203 let max_documents =
204 usize::try_from(args.max_documents.unwrap_or(DEFAULT_MAX_DOCUMENTS).max(1)).unwrap_or(1);
205 let dirs: Vec<&str> = match direction.as_str() {
206 "both" => vec!["out", "in"],
207 "in" => vec!["in"],
208 _ => vec!["out"],
209 };
210 let (user_select, out_names) = build_user_select(&args.select)?;
211
212 let mut queries = Vec::new();
213 let mut docs: Vec<Doc> = Vec::new();
214 let mut edges: Vec<Json> = Vec::new();
215 let mut query_truncated = false;
216 for dir in &dirs {
217 let q = build_query(&root_ids, dir, walk_depth, &user_select);
218 queries.push(q.clone());
219 let res = query(
220 store,
221 repo_id,
222 &q,
223 QueryOptions {
224 limit: Some(max_documents + 1),
225 cursor: None,
226 provider,
227 in_memory: false,
228 },
229 )?;
230 if res.truncated {
231 query_truncated = true;
232 }
233 for hit in &res.hits {
234 let id = hit["id"].as_str().unwrap_or_default().to_owned();
237 let path = hit["path"].as_str().unwrap_or_default().to_owned();
238 let hop = hit["_depth"].as_f64().unwrap_or(f64::NAN);
239 let degree = (hop - 1.0) as i64;
240 let replace = docs
241 .iter()
242 .position(|d| d.id == id)
243 .map(|i| (i, degree < docs[i].degree));
244 match replace {
245 Some((_, false)) => {}
246 found => {
247 let extra: Vec<(String, Json)> = out_names
248 .iter()
249 .enumerate()
250 .filter_map(|(i, n)| {
251 n.as_ref().map(|name| {
252 (
253 name.clone(),
254 hit.get(format!("_u{i}")).cloned().unwrap_or(Json::Null),
255 )
256 })
257 })
258 .collect();
259 let doc = Doc {
260 id: id.clone(),
261 path,
262 degree,
263 extra,
264 };
265 match found {
266 Some((i, true)) => docs[i] = doc,
267 _ => docs.push(doc),
268 }
269 }
270 }
271 if let Some(raw) = hit["_links"].as_array() {
272 for e in raw {
273 let eid = e["id"].as_str().unwrap_or_default();
274 if !edges.iter().any(|x| x["id"].as_str() == Some(eid)) {
275 edges.push(e.clone());
276 }
277 }
278 }
279 }
280 }
281
282 if let Some(p) = &args.predicate {
283 let mut adj: HashMap<String, Vec<String>> = HashMap::new();
284 for e in &edges {
285 if e["predicate"].as_str() != Some(p.as_str()) {
286 continue;
287 }
288 let src = e["doc_id"].as_str().unwrap_or_default().to_owned();
289 let dst = e["dst_id"].as_str().unwrap_or_default().to_owned();
290 if dirs.contains(&"out") {
291 adj.entry(src.clone()).or_default().push(dst.clone());
292 }
293 if dirs.contains(&"in") {
294 adj.entry(dst).or_default().push(src);
295 }
296 }
297 let mut depth_of: Vec<(String, i64)> = root_ids.iter().map(|id| (id.clone(), 0)).collect();
298 let mut wave: Vec<String> = root_ids.clone();
299 let mut lvl = 1;
300 while lvl <= effective_degrees && !wave.is_empty() {
301 let mut next = Vec::new();
302 for from in &wave {
303 for to in adj.get(from).map_or(&[][..], Vec::as_slice) {
304 if docs.iter().any(|d| &d.id == to) && !depth_of.iter().any(|(id, _)| id == to)
305 {
306 depth_of.push((to.clone(), lvl));
307 next.push(to.clone());
308 }
309 }
310 }
311 wave = next;
312 lvl += 1;
313 }
314 let mut restricted: Vec<Doc> = Vec::new();
315 for (id, d) in depth_of {
316 if let Some(orig) = docs.iter().find(|x| x.id == id) {
317 restricted.push(Doc {
318 id: orig.id.clone(),
319 path: orig.path.clone(),
320 degree: d,
321 extra: orig.extra.clone(),
322 });
323 }
324 }
325 docs = restricted;
326 }
327
328 docs.sort_by(|a, b| {
329 a.degree
330 .cmp(&b.degree)
331 .then_with(|| locale_compare(&a.path, &b.path))
332 });
333 let capped = docs.len() > max_documents;
334 docs.truncate(max_documents);
335 let truncated = query_truncated || capped;
336
337 let mut frontier = Vec::new();
338 let documents: Vec<Json> = docs
339 .iter()
340 .map(|d| {
341 let is_frontier = d.degree == effective_degrees;
342 if is_frontier {
343 frontier.push(json!({ "id": d.id, "path": d.path, "degree": d.degree }));
344 }
345 let mut m = Map::new();
346 m.insert("id".to_owned(), json!(d.id));
347 m.insert("path".to_owned(), json!(d.path));
348 m.insert("degree".to_owned(), json!(d.degree));
349 m.insert("frontier".to_owned(), json!(is_frontier));
350 for (k, v) in &d.extra {
351 m.insert(k.clone(), v.clone());
352 }
353 Json::Object(m)
354 })
355 .collect();
356
357 let reached = |id: &str| docs.iter().any(|d| d.id == id);
358 let mut kept: Vec<Json> = edges
359 .into_iter()
360 .filter(|e| {
361 if let Some(p) = &args.predicate {
362 if e["predicate"].as_str() != Some(p.as_str()) {
363 return false;
364 }
365 }
366 let src_in = reached(e["doc_id"].as_str().unwrap_or_default());
367 let dst_kind = e["dst_kind"].as_str().unwrap_or_default();
368 let dst_dangling =
369 dst_kind == "external" || (dst_kind == "document" && e["dst_path"].is_null());
370 let dst_in = reached(e["dst_id"].as_str().unwrap_or_default()) || dst_dangling;
371 src_in && dst_in
372 })
373 .collect();
374 kept.sort_by(|a, b| {
375 let (sa, sb) = (
376 a["doc_id"].as_str().unwrap_or_default(),
377 b["doc_id"].as_str().unwrap_or_default(),
378 );
379 if sa == sb {
380 locale_compare(
381 a["id"].as_str().unwrap_or_default(),
382 b["id"].as_str().unwrap_or_default(),
383 )
384 } else {
385 locale_compare(sa, sb)
386 }
387 });
388
389 Ok(json!({
390 "roots": root_ids,
391 "degrees": effective_degrees,
392 "direction": direction,
393 "documents": documents,
394 "links": kept,
395 "frontier": frontier,
396 "truncated": truncated,
397 "queries": queries,
398 }))
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 #[test]
406 fn user_select_aliases() {
407 let (items, names) = build_user_select(&[
408 "layer".into(),
409 "path".into(),
410 "a + 1".into(),
411 "layer".into(),
412 ])
413 .unwrap();
414 let printed: Vec<String> = items
415 .iter()
416 .map(|it| oqx::print(oqx::Node::Select(it)).unwrap())
417 .collect();
418 assert_eq!(
419 printed,
420 ["_u0: layer", "_u1: path", "_u2: a + 1", "_u3: layer"]
421 );
422 assert_eq!(
423 names,
424 [
425 Some("layer".into()),
426 Some("path".into()),
427 Some("sel_2".into()),
428 Some("layer_3".into())
429 ]
430 );
431 assert!(build_user_select(&[]).unwrap().0.is_empty());
432 let e = build_user_select(&["a +".into()]).unwrap_err();
433 assert_eq!(e.code, "filter_invalid");
434 }
435
436 #[test]
437 fn query_shape() {
438 let q = build_query(&["d_0".to_owned()], "out", 2, &[]);
439 assert!(
440 q.starts_with("select _depth: $depth, _stop: $stop, _links: doc.out_links collect {")
441 );
442 assert!(q.ends_with(
443 "from docs where id == \"d_0\" follow distinct out_links collect { from dst depth 2 }"
444 ));
445 assert!(oqx::parse_string(&q).is_ok());
446 let q = build_query(&["d_14".to_owned(), "d_15".to_owned()], "in", 8, &[]);
450 assert_eq!(
451 q,
452 "select _depth: $depth, _stop: $stop, _links: doc.in_links collect { id: id, doc_id: doc_id, block_id: block_id, via_id: via_id, dst_id: dst_id, dst_path: dst_path, uri: uri, dst_kind: dst_kind, predicate: predicate, provenance: provenance, anchor: anchor, field: field } from docs where id == \"d_14\" or id == \"d_15\" follow distinct in_links collect { from doc depth 8 }"
453 );
454 }
455
456 #[test]
457 fn order_is_bytewise() {
458 assert_eq!(locale_compare("B", "a"), Ordering::Less);
459 assert_eq!(locale_compare("a", "b"), Ordering::Less);
460 }
461}