graph-explorer-core 0.1.0

Graph data model, neighbourhood cache and provisional preview layer for graph-explorer.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
use std::collections::HashMap;
use serde_json::Value;

pub type NodeId = String;
pub type EdgeId = String;

pub mod cache;
pub use cache::*;

pub mod preview;
pub use preview::*;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
    pub id: NodeId,
    pub label: Option<String>,
    pub attrs: HashMap<String, Value>,
}

impl Node {
    pub fn new(id: impl Into<NodeId>) -> Self {
        Self { id: id.into(), label: None, attrs: HashMap::new() }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Edge {
    pub id: EdgeId,
    pub source: NodeId,
    pub target: NodeId,
    pub attrs: HashMap<String, Value>,
}

impl Edge {
    pub fn new(id: impl Into<EdgeId>, source: impl Into<NodeId>, target: impl Into<NodeId>) -> Self {
        Self { id: id.into(), source: source.into(), target: target.into(), attrs: HashMap::new() }
    }
}

#[derive(Debug, Clone, Default)]
pub struct Graph {
    nodes: HashMap<NodeId, Node>,
    edges: HashMap<EdgeId, Edge>,
    adjacency: HashMap<NodeId, Vec<EdgeId>>,
}

impl Graph {
    pub fn add_node(&mut self, node: Node) {
        self.adjacency.entry(node.id.clone()).or_default();
        self.nodes.insert(node.id.clone(), node);
    }

    pub fn add_edge(&mut self, edge: Edge) {
        self.link_adjacency(&edge);
        self.edges.insert(edge.id.clone(), edge);
    }

    /// Record `edge` under both endpoints. A self-loop is recorded once, so
    /// `degree()` counts it as one incident edge rather than two.
    fn link_adjacency(&mut self, edge: &Edge) {
        self.adjacency.entry(edge.source.clone()).or_default().push(edge.id.clone());
        if edge.source != edge.target {
            self.adjacency.entry(edge.target.clone()).or_default().push(edge.id.clone());
        }
    }

    /// Remove `id` from both endpoints' adjacency lists.
    fn unlink_adjacency(&mut self, id: &EdgeId, source: &NodeId, target: &NodeId) {
        for endpoint in [source, target] {
            if let Some(list) = self.adjacency.get_mut(endpoint) {
                list.retain(|e| e != id);
            }
        }
    }

    pub fn node(&self, id: &str) -> Option<&Node> { self.nodes.get(id) }
    pub fn edge(&self, id: &str) -> Option<&Edge> { self.edges.get(id) }
    pub fn node_count(&self) -> usize { self.nodes.len() }
    pub fn edge_count(&self) -> usize { self.edges.len() }
    pub fn nodes(&self) -> impl Iterator<Item = &Node> { self.nodes.values() }
    pub fn edges(&self) -> impl Iterator<Item = &Edge> { self.edges.values() }

    /// Undirected neighbors: every node reachable by one edge, either direction.
    pub fn neighbors(&self, id: &str) -> Vec<NodeId> {
        let mut out = Vec::new();
        if let Some(edge_ids) = self.adjacency.get(id) {
            for eid in edge_ids {
                if let Some(e) = self.edges.get(eid) {
                    let other = if e.source == id { &e.target } else { &e.source };
                    out.push(other.clone());
                }
            }
        }
        out
    }

    pub fn degree(&self, id: &str) -> usize {
        self.adjacency.get(id).map_or(0, Vec::len)
    }

    /// Insert or replace a node by id.
    pub fn upsert_node(&mut self, n: Node) {
        self.adjacency.entry(n.id.clone()).or_default();
        self.nodes.insert(n.id.clone(), n);
    }

    /// Insert or replace an edge by id. Replacing an edge whose endpoints
    /// changed unlinks the OLD endpoints first — otherwise the id would linger
    /// in adjacency lists it no longer belongs to and be missing from the ones
    /// it does, so `degree()`/`most_central()` would disagree with `edges`.
    pub fn upsert_edge(&mut self, e: Edge) {
        if let Some(old) = self.edges.get(&e.id) {
            if old.source == e.source && old.target == e.target {
                // same endpoints: adjacency is already correct, don't duplicate
                self.edges.insert(e.id.clone(), e);
                return;
            }
            let (os, ot) = (old.source.clone(), old.target.clone());
            self.unlink_adjacency(&e.id, &os, &ot);
        }
        self.link_adjacency(&e);
        self.edges.insert(e.id.clone(), e);
    }

    /// The highest-degree node, ties broken by smallest id (deterministic).
    /// `None` for an empty graph.
    pub fn most_central(&self) -> Option<NodeId> {
        let mut ids: Vec<&NodeId> = self.nodes.keys().collect();
        ids.sort();
        let mut best: Option<(&NodeId, usize)> = None;
        for id in ids {
            let d = self.degree(id);
            // strictly-greater keeps the first (smallest-id) node on ties
            if best.is_none_or(|(_, bd)| d > bd) {
                best = Some((id, d));
            }
        }
        best.map(|(id, _)| id.clone())
    }
}

#[derive(Debug, Clone, Default)]
pub struct NavState {
    pub current: Option<NodeId>,
    pub history: Vec<NodeId>,
}

impl NavState {
    /// Move focus to `id`, pushing the previous current node onto history.
    pub fn focus(&mut self, id: NodeId) {
        if let Some(prev) = self.current.take() {
            self.history.push(prev);
        }
        self.current = Some(id);
    }

    /// Return to the previous node, if any.
    pub fn back(&mut self) -> Option<NodeId> {
        let prev = self.history.pop()?;
        self.current = Some(prev.clone());
        Some(prev)
    }
}

use serde::{Deserialize, Serialize};

/// Opaque paging token, meaning defined by the provider.
///
/// `Eq + Hash` so `CacheKey` can index a map directly — `graph-explorer-wasm` keys its
/// in-flight `AbortController`s by cache key.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Cursor(pub String);

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QueryParams {
    pub limit: usize,
    pub cursor: Option<Cursor>,
}

/// What dimension a group of neighbors was formed along. Mirrors the proxy's
/// `AggStrategy`, which already ships all three.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GroupBy {
    Relationship,
    Label,
    Property(String),
}

/// A group of neighbors collapsed into one summary. Descending it is a host
/// decision, not an engine one — see `DescendOutcome::Subsearch`.
///
/// Deliberately carries no pre-rendered display string: `value` and `count` are
/// data, and `display()` composes them so a host can phrase or localize it
/// differently (via the `label_text` style rule) without parsing anything back
/// out.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Aggregate {
    /// Stable handle. The radial view renders these as `__agg:<id>`.
    pub id: NodeId,
    /// The node this group hangs off. Derived on receipt and never trusted from
    /// the wire — whoever ran the query knows which node it asked about, so a
    /// derived value cannot be wrong and no provider can forget to set it.
    /// Same rule as `NeighborResult::pending`.
    #[serde(default)]
    pub parent: NodeId,
    pub group_by: GroupBy,
    /// The shared value along that dimension: "OF_TYPE", "Sorcery", "rare".
    pub value: String,
    /// Optional sub-data: distinct relationship types the members are reached
    /// through. **Empty means UNSTATED, never "no relationships"** — a node
    /// always reaches its neighbors through something, so an empty list can
    /// only mean the provider declined the extra aggregation. Advisory only:
    /// never branch on emptiness to conclude anything about the graph.
    #[serde(default)]
    pub relationships: Vec<String>,
    pub count: u64,
    /// Opaque paging token that makes the group fetchable. Without it a host
    /// knows N things exist but cannot reach them, and cannot reconstruct the
    /// cursor because its encoding is provider-defined.
    pub query: QueryParams,
}

impl Aggregate {
    /// Default display text, e.g. "32 Sorcery". Composed rather than
    /// transmitted so presentation stays overridable in the styling layer.
    pub fn display(&self) -> String {
        format!("{} {}", self.count, self.value)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NeighborResult {
    #[serde(default)]
    pub nodes: Vec<Node>,
    /// Real relationships among/into the returned nodes. The radial view
    /// synthesizes its own focus->candidate edges, but the traditional view
    /// draws real ones, so remote results carry them. Defaults empty.
    #[serde(default)]
    pub edges: Vec<Edge>,
    #[serde(default)]
    pub aggregates: Vec<Aggregate>,
    #[serde(default)]
    pub next: Option<Cursor>,
    /// True when this is a placeholder standing in for an in-flight fetch.
    #[serde(default)]
    pub pending: bool,
}

pub trait DataProvider {
    fn load(&self) -> Graph;
    fn neighbors(&self, focus: &NodeId, params: &QueryParams) -> NeighborResult;
}

#[derive(Deserialize)]
struct JsonNode {
    id: String,
    #[serde(default)]
    label: Option<String>,
    #[serde(default)]
    attrs: HashMap<String, Value>,
}

#[derive(Deserialize)]
struct JsonEdge {
    #[serde(default)]
    id: Option<String>,
    source: String,
    target: String,
    #[serde(default)]
    attrs: HashMap<String, Value>,
}

#[derive(Deserialize)]
struct JsonGraph {
    nodes: Vec<JsonNode>,
    edges: Vec<JsonEdge>,
}

pub struct InMemoryProvider {
    graph: Graph,
}

impl InMemoryProvider {
    pub fn from_json(s: &str) -> Result<Self, String> {
        use std::collections::HashSet;
        let jg: JsonGraph = serde_json::from_str(s).map_err(|e| format!("parse: {e}"))?;
        let mut g = Graph::default();

        let mut node_ids: HashSet<String> = HashSet::new();
        for n in jg.nodes {
            if !node_ids.insert(n.id.clone()) {
                return Err(format!("duplicate node id: {}", n.id));
            }
            g.add_node(Node { id: n.id, label: n.label, attrs: n.attrs });
        }

        let explicit_ids: HashSet<String> = jg.edges.iter().filter_map(|e| e.id.clone()).collect();
        let mut seen_edge_ids: HashSet<String> = HashSet::new();
        let mut auto = 0usize;
        for e in jg.edges {
            if !node_ids.contains(&e.source) {
                return Err(format!("edge source not a declared node: {}", e.source));
            }
            if !node_ids.contains(&e.target) {
                return Err(format!("edge target not a declared node: {}", e.target));
            }
            let id = match e.id {
                Some(id) => {
                    if !seen_edge_ids.insert(id.clone()) {
                        return Err(format!("duplicate edge id: {id}"));
                    }
                    id
                }
                None => loop {
                    let cand = format!("e{auto}");
                    auto += 1;
                    if !explicit_ids.contains(&cand) && !seen_edge_ids.contains(&cand) {
                        seen_edge_ids.insert(cand.clone());
                        break cand;
                    }
                },
            };
            g.add_edge(Edge { id, source: e.source, target: e.target, attrs: e.attrs });
        }
        Ok(Self { graph: g })
    }

    pub fn from_graph(graph: Graph) -> Self {
        Self { graph }
    }
}

impl DataProvider for InMemoryProvider {
    fn load(&self) -> Graph {
        self.graph.clone()
    }

    fn neighbors(&self, focus: &NodeId, params: &QueryParams) -> NeighborResult {
        let mut ids = self.graph.neighbors(focus);
        ids.sort();
        ids.dedup();
        let offset = params
            .cursor
            .as_ref()
            .and_then(|c| c.0.parse::<usize>().ok())
            .unwrap_or(0);
        let limit = params.limit.max(1);
        let nodes: Vec<Node> = ids
            .iter()
            .skip(offset)
            .take(limit)
            .filter_map(|id| self.graph.node(id).cloned())
            .collect();
        let consumed = (offset + limit).min(ids.len());
        let next = if consumed < ids.len() {
            Some(Cursor(consumed.to_string()))
        } else {
            None
        };
        NeighborResult { nodes, edges: Vec::new(), aggregates: Vec::new(), next, pending: false }
    }
}

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

    #[test]
    fn add_and_get_nodes_and_edges() {
        let mut g = Graph::default();
        g.add_node(Node::new("a"));
        g.add_node(Node::new("b"));
        g.add_edge(Edge::new("e1", "a", "b"));
        assert_eq!(g.node("a").unwrap().id, "a");
        assert_eq!(g.edge("e1").unwrap().source, "a");
        assert_eq!(g.node_count(), 2);
        assert_eq!(g.edge_count(), 1);
    }

    #[test]
    fn neighbors_are_undirected() {
        let mut g = Graph::default();
        g.add_node(Node::new("a"));
        g.add_node(Node::new("b"));
        g.add_node(Node::new("c"));
        g.add_edge(Edge::new("e1", "a", "b"));
        g.add_edge(Edge::new("e2", "c", "a"));
        let mut n = g.neighbors("a");
        n.sort();
        assert_eq!(n, vec!["b".to_string(), "c".to_string()]);
    }

    #[test]
    fn focus_pushes_previous_onto_history() {
        let mut nav = NavState::default();
        nav.focus("a".into());
        nav.focus("b".into());
        assert_eq!(nav.current.as_deref(), Some("b"));
        assert_eq!(nav.history, vec!["a".to_string()]);
    }

    #[test]
    fn back_pops_history() {
        let mut nav = NavState::default();
        nav.focus("a".into());
        nav.focus("b".into());
        assert_eq!(nav.back(), Some("a".to_string()));
        assert_eq!(nav.current.as_deref(), Some("a"));
        assert!(nav.history.is_empty());
        assert_eq!(nav.back(), None);
    }

    #[test]
    fn parses_json_graph() {
        let json = r#"{
            "nodes": [{"id":"a","label":"A"},{"id":"b"}],
            "edges": [{"source":"a","target":"b"}]
        }"#;
        let p = InMemoryProvider::from_json(json).unwrap();
        let g = p.load();
        assert_eq!(g.node_count(), 2);
        assert_eq!(g.node("a").unwrap().label.as_deref(), Some("A"));
        assert_eq!(g.edge_count(), 1);
        // edge id auto-generated when absent
        assert_eq!(g.edge("e0").unwrap().target, "b");
    }

    fn star(center: &str, leaves: &[&str]) -> Graph {
        let mut g = Graph::default();
        g.add_node(Node::new(center));
        for (i, l) in leaves.iter().enumerate() {
            g.add_node(Node::new(*l));
            g.add_edge(Edge::new(format!("e{i}"), center, *l));
        }
        g
    }

    #[test]
    fn neighbors_pages_with_cursor_no_gaps() {
        // center connected to 5 leaves: b,c,d,e,f
        let g = star("a", &["b", "c", "d", "e", "f"]);
        let p = InMemoryProvider::from_graph(g);

        let page1 = p.neighbors(&"a".into(), &QueryParams { limit: 2, cursor: None });
        assert_eq!(page1.nodes.iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), vec!["b", "c"]);
        assert!(page1.aggregates.is_empty());
        let c1 = page1.next.clone().expect("more remain after page1");

        let page2 = p.neighbors(&"a".into(), &QueryParams { limit: 2, cursor: Some(c1) });
        assert_eq!(page2.nodes.iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), vec!["d", "e"]);
        let c2 = page2.next.clone().expect("more remain after page2");

        let page3 = p.neighbors(&"a".into(), &QueryParams { limit: 2, cursor: Some(c2) });
        assert_eq!(page3.nodes.iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), vec!["f"]);
        assert!(page3.next.is_none(), "no more after the last page");
    }

    #[test]
    fn neighbors_all_fit_no_cursor() {
        let g = star("a", &["b", "c"]);
        let p = InMemoryProvider::from_graph(g);
        let res = p.neighbors(&"a".into(), &QueryParams { limit: 10, cursor: None });
        assert_eq!(res.nodes.len(), 2);
        assert!(res.next.is_none());
    }

    #[test]
    fn most_central_picks_highest_degree() {
        // hub "h" has degree 3; others degree 1
        let g = star("h", &["a", "b", "c"]);
        assert_eq!(g.degree("h"), 3);
        assert_eq!(g.most_central(), Some("h".to_string()));
    }

    #[test]
    fn most_central_breaks_ties_by_smallest_id() {
        // two degree-1 nodes "x","y" connected to each other -> both degree 1; smallest id wins
        let mut g = Graph::default();
        g.add_node(Node::new("y"));
        g.add_node(Node::new("x"));
        g.add_edge(Edge::new("e", "x", "y"));
        assert_eq!(g.most_central(), Some("x".to_string()));
    }

    #[test]
    fn most_central_empty_is_none() {
        assert_eq!(Graph::default().most_central(), None);
    }

    #[test]
    fn neighbors_paging_survives_dangling_edges() {
        let mut g = Graph::default();
        for id in ["a", "n1", "n3"] { g.add_node(Node::new(id)); }
        g.add_edge(Edge::new("e1", "a", "n1"));
        g.add_edge(Edge::new("e2", "a", "ghost")); // dangling: "ghost" never added
        g.add_edge(Edge::new("e3", "a", "n3"));
        let p = InMemoryProvider::from_graph(g);
        let mut seen = Vec::new();
        let mut cursor = None;
        for _ in 0..10 { // bounded to prove no infinite loop
            let res = p.neighbors(&"a".into(), &QueryParams { limit: 1, cursor });
            for n in &res.nodes { seen.push(n.id.clone()); }
            cursor = res.next.clone();
            if cursor.is_none() { break; }
        }
        seen.sort();
        assert_eq!(seen, vec!["n1".to_string(), "n3".to_string()]); // each once, no dupes
    }

    #[test]
    fn from_json_rejects_dangling_edge_endpoints() {
        let j = r#"{ "nodes": [{"id":"a"}], "edges": [{"source":"a","target":"ghost"}] }"#;
        assert!(InMemoryProvider::from_json(j).is_err());
    }

    #[test]
    fn from_json_rejects_duplicate_edge_ids() {
        let j = r#"{ "nodes":[{"id":"a"},{"id":"b"},{"id":"c"}],
                     "edges":[{"id":"e","source":"a","target":"b"},{"id":"e","source":"b","target":"c"}] }"#;
        assert!(InMemoryProvider::from_json(j).is_err());
    }

    #[test]
    fn from_json_rejects_duplicate_node_ids() {
        let j = r#"{ "nodes":[{"id":"a"},{"id":"a"}], "edges":[] }"#;
        assert!(InMemoryProvider::from_json(j).is_err());
    }

    #[test]
    fn auto_edge_ids_avoid_colliding_with_explicit_ids() {
        // explicit "e0" plus one anonymous edge -> anonymous must NOT reuse "e0"
        let j = r#"{ "nodes":[{"id":"a"},{"id":"b"},{"id":"c"}],
                     "edges":[{"id":"e0","source":"a","target":"b"},{"source":"b","target":"c"}] }"#;
        let g = InMemoryProvider::from_json(j).unwrap().load();
        assert_eq!(g.edge_count(), 2);
        assert_eq!(g.edge("e0").unwrap().target, "b"); // explicit one preserved
        // the anonymous edge exists under some other id connecting b->c
        assert_eq!(g.neighbors("c"), vec!["b".to_string()]);
    }

    #[test]
    fn auto_edge_ids_avoid_explicit_id_declared_later() {
        // anonymous edge listed BEFORE the explicit "e0" it must avoid (pre-collection design)
        let j = r#"{ "nodes":[{"id":"a"},{"id":"b"},{"id":"c"}],
                     "edges":[{"source":"a","target":"b"},{"id":"e0","source":"b","target":"c"}] }"#;
        let g = InMemoryProvider::from_json(j).unwrap().load();
        assert_eq!(g.edge_count(), 2);
        // "e0" belongs to the explicit (b->c) edge; the anonymous a->b edge must NOT have claimed it
        assert_eq!(g.edge("e0").unwrap().source, "b");
        assert_eq!(g.edge("e0").unwrap().target, "c");
    }

    #[test]
    fn neighbor_result_round_trips_as_json() {
        let r = NeighborResult {
            nodes: vec![Node { id: "a".into(), label: Some("A".into()), attrs: HashMap::new() }],
            edges: vec![Edge { id: "e1".into(), source: "a".into(), target: "b".into(), attrs: HashMap::new() }],
            aggregates: vec![Aggregate {
                id: "agg:X".into(),
                parent: "a".into(),
                group_by: GroupBy::Label,
                value: "X".into(),
                relationships: vec![],
                count: 12,
                query: QueryParams { limit: 8, cursor: Some(Cursor("grp:X".into())) },
            }],
            next: Some(Cursor("off:8".into())),
            pending: false,
        };
        let s = serde_json::to_string(&r).unwrap();
        let back: NeighborResult = serde_json::from_str(&s).unwrap();
        assert_eq!(back.nodes.len(), 1);
        assert_eq!(back.edges.len(), 1);
        assert_eq!(back.aggregates[0].count, 12);
        assert_eq!(back.aggregates[0].query.cursor, Some(Cursor("grp:X".into())));
        assert_eq!(back.next, Some(Cursor("off:8".into())));
        assert!(!back.pending);
    }

    #[test]
    fn neighbor_result_defaults_edges_and_pending() {
        // A proxy payload that omits both fields must still parse.
        let back: NeighborResult =
            serde_json::from_str(r#"{"nodes":[],"aggregates":[],"next":null}"#).unwrap();
        assert!(back.edges.is_empty());
        assert!(!back.pending);
    }

    #[test]
    fn upsert_edge_with_new_endpoints_moves_its_adjacency() {
        let mut g = Graph::default();
        for id in ["a", "b", "c", "d"] { g.add_node(Node::new(id)); }
        g.add_edge(Edge::new("e1", "a", "b"));
        assert_eq!((g.degree("a"), g.degree("b")), (1, 1));

        // same id, different endpoints
        g.upsert_edge(Edge::new("e1", "c", "d"));
        assert_eq!(g.edge_count(), 1);
        assert_eq!(g.degree("a"), 0, "stale adjacency left on the old source");
        assert_eq!(g.degree("b"), 0, "stale adjacency left on the old target");
        assert_eq!(g.degree("c"), 1);
        assert_eq!(g.degree("d"), 1);
        assert_eq!(g.neighbors("a"), Vec::<String>::new());
        assert_eq!(g.neighbors("c"), vec!["d".to_string()]);
    }

    #[test]
    fn upsert_edge_with_the_same_endpoints_does_not_duplicate_adjacency() {
        let mut g = Graph::default();
        for id in ["a", "b"] { g.add_node(Node::new(id)); }
        g.add_edge(Edge::new("e1", "a", "b"));
        g.upsert_edge(Edge::new("e1", "a", "b"));
        g.upsert_edge(Edge::new("e1", "a", "b"));
        assert_eq!(g.degree("a"), 1);
        assert_eq!(g.degree("b"), 1);
    }

    #[test]
    fn self_loop_counts_once_toward_degree() {
        let mut g = Graph::default();
        g.add_node(Node::new("a"));
        g.add_edge(Edge::new("loop", "a", "a"));
        assert_eq!(g.degree("a"), 1, "a self-loop is one incident edge, not two");

        // repeated arrivals of the same self-loop must not inflate it
        for _ in 0..3 { g.upsert_edge(Edge::new("loop", "a", "a")); }
        assert_eq!(g.degree("a"), 1);
        assert_eq!(g.edge_count(), 1);
    }

    #[test]
    fn upsert_edge_can_turn_an_edge_into_a_self_loop_and_back() {
        let mut g = Graph::default();
        for id in ["a", "b"] { g.add_node(Node::new(id)); }
        g.add_edge(Edge::new("e1", "a", "b"));
        g.upsert_edge(Edge::new("e1", "a", "a"));
        assert_eq!(g.degree("a"), 1);
        assert_eq!(g.degree("b"), 0);
        g.upsert_edge(Edge::new("e1", "a", "b"));
        assert_eq!(g.degree("a"), 1);
        assert_eq!(g.degree("b"), 1);
    }

    #[test]
    fn neighbors_handles_bad_and_past_end_cursors() {
        let g = star("a", &["b", "c"]);
        let p = InMemoryProvider::from_graph(g);
        let garbage = p.neighbors(&"a".into(), &QueryParams { limit: 5, cursor: Some(Cursor("xyz".into())) });
        assert_eq!(garbage.nodes.len(), 2); // treated as offset 0
        let past = p.neighbors(&"a".into(), &QueryParams { limit: 5, cursor: Some(Cursor("99".into())) });
        assert!(past.nodes.is_empty());
        assert!(past.next.is_none());
    }

    #[test]
    fn aggregate_display_reads_naturally_for_each_grouping() {
        let agg = |gb: GroupBy, value: &str, count: u64| Aggregate {
            id: "agg:x".into(),
            parent: String::new(),
            group_by: gb,
            value: value.into(),
            relationships: vec![],
            count,
            query: QueryParams { limit: 8, cursor: None },
        };
        assert_eq!(agg(GroupBy::Label, "Sorcery", 32).display(), "32 Sorcery");
        assert_eq!(agg(GroupBy::Relationship, "OF_TYPE", 4).display(), "4 OF_TYPE");
        assert_eq!(agg(GroupBy::Property("rarity".into()), "rare", 1).display(), "1 rare");
    }

    #[test]
    fn aggregate_deserializes_without_parent_or_relationships() {
        // Both are `#[serde(default)]`: `parent` because it is stamped
        // client-side and never trusted from the wire, `relationships`
        // because a provider may decline the extra aggregation.
        let json = r#"{
            "id": "agg:Sorcery",
            "group_by": "label",
            "value": "Sorcery",
            "count": 32,
            "query": { "limit": 8, "cursor": "grp:Sorcery:0" }
        }"#;
        let a: Aggregate = serde_json::from_str(json).unwrap();
        assert_eq!(a.parent, "", "absent parent defaults empty, to be stamped on receipt");
        assert!(a.relationships.is_empty(), "empty means UNSTATED, never 'no relationships'");
        assert_eq!(a.group_by, GroupBy::Label);
        assert_eq!(a.value, "Sorcery");
        assert_eq!(a.query.cursor.as_ref().unwrap().0, "grp:Sorcery:0");
    }

    #[test]
    fn group_by_round_trips_including_the_property_variant() {
        for gb in [GroupBy::Relationship, GroupBy::Label, GroupBy::Property("rarity".into())] {
            let s = serde_json::to_string(&gb).unwrap();
            let back: GroupBy = serde_json::from_str(&s).unwrap();
            assert_eq!(back, gb, "round-trip failed for {s}");
        }
        // unit variants are bare strings; the newtype is externally tagged
        assert_eq!(serde_json::to_string(&GroupBy::Label).unwrap(), r#""label""#);
        assert_eq!(serde_json::to_string(&GroupBy::Relationship).unwrap(), r#""relationship""#);
        assert_eq!(
            serde_json::to_string(&GroupBy::Property("rarity".into())).unwrap(),
            r#"{"property":"rarity"}"#
        );
    }

    #[test]
    fn a_wire_aggregate_cannot_forge_its_parent() {
        // `parent` is derived on receipt. A provider that sends one is simply
        // overwritten later; this test pins that it deserializes into the
        // field rather than being rejected, so stamping is the only guard.
        let json = r#"{
            "id": "agg:x", "parent": "lies", "group_by": "label",
            "value": "X", "count": 1, "query": { "limit": 8, "cursor": null }
        }"#;
        let a: Aggregate = serde_json::from_str(json).unwrap();
        assert_eq!(a.parent, "lies", "deserializes; callers MUST stamp over it");
    }

    #[test]
    fn neighbor_result_tolerates_a_partial_host_payload() {
        // A host staging nodes via `preview_nodes` should not have to spell out
        // every field. Only `nodes` is interesting for that call; the rest are
        // engine-side concerns.
        let r: NeighborResult = serde_json::from_str(r#"{"nodes":[]}"#).unwrap();
        assert!(r.nodes.is_empty());
        assert!(r.edges.is_empty());
        assert!(r.aggregates.is_empty());
        assert!(r.next.is_none());
        assert!(!r.pending, "pending is client-side and must never arrive true");

        let empty: NeighborResult = serde_json::from_str("{}").unwrap();
        assert!(empty.nodes.is_empty());
    }
}