Skip to main content

adam_web_ui/graph/
data.rs

1//! Serialization bridge from [`adam_rs::Sheet`] to D3-ready JSON, for `GraphView`.
2
3use crate::labels::Labels;
4use adam_rs::{CellId, ConditionalId, RelationshipId, Sheet};
5use serde::Serialize;
6use slotmap::Key;
7
8/// Node kind tag used in the D3 graph.
9#[derive(Serialize, Clone, PartialEq, Eq)]
10///
11/// # Examples
12///
13/// A cell snapshot carries `NodeKind::Cell`; a multi-relationship branch junction
14/// carries `NodeKind::Branch`.
15pub enum NodeKind {
16    /// A value cell — rendered as a `<rect>`.
17    Cell,
18    /// A multi-way constraint — rendered as a `<circle>`.
19    Relationship,
20    /// A conditional switch — rendered as a diamond (rotated `<rect>`).
21    Conditional,
22    /// An invisible junction node grouping a branch's relationships when a
23    /// branch (or the default) holds more than one; rendered as a zero-size point.
24    Branch,
25}
26
27/// A single node in the D3 graph.
28#[derive(Serialize, Clone, PartialEq)]
29///
30/// # Examples
31///
32/// Inspect a cell entry in `to_graph_data(&sheet, &labels).nodes` to display its
33/// registered label and formatted value alongside its stable graph ID.
34pub struct NodeData {
35    /// Stable string ID: `"c{ffi}"` for cells, `"r{ffi}"` for relationships, `"cond{ffi}"` for
36    /// conditionals, `"br{ffi}_{branch}"` for a named branch's junction node, `"br{ffi}_def"`
37    /// for the default's junction node.
38    pub id: String,
39    /// The kind of node, determining its visual rendering.
40    pub kind: NodeKind,
41    /// Cell label (e.g. `"a"`); empty string for relationships, conditionals, and branch junction nodes.
42    pub label: String,
43    /// Current cell value as a display string; empty string for relationships, conditionals, and
44    /// branch junction nodes.
45    pub value: String,
46}
47
48/// Link kind tag used in the D3 graph.
49#[derive(Serialize, Clone, PartialEq, Eq)]
50///
51/// # Examples
52///
53/// Conditional activation links use `LinkKind::Control`; data dependencies use
54/// `LinkKind::Constraint`.
55pub enum LinkKind {
56    /// A regular constraint edge (cell ↔ relationship, or match cell → conditional node).
57    Constraint,
58    /// A control edge from a conditional node toward a branch's relationship(s): a direct edge
59    /// to the relationship when the branch has at most one, or, when it has more than one, a
60    /// two-hop path through an intermediate `Branch` junction node (see [`LinkData`]'s doc for
61    /// the full two-hop description).
62    Control,
63}
64
65/// A single edge in the D3 graph.
66///
67/// `directed` is `true` when this specific link's direction is known and should render
68/// with an arrowhead from `source` to `target`; `false` renders it as a plain undirected
69/// line. This is a per-link fact, not a sheet-wide one: a cell ↔ relationship link is
70/// directed only once *that relationship* has a selected method, so one relationship
71/// having a cached plan says nothing about another relationship (or a currently-inactive
72/// conditional branch's relationship) that doesn't. A match cell → conditional link is
73/// always directed — evaluating a conditional's match expression doesn't depend on any
74/// relationship ever being planned. Control edges are always directed too — from a
75/// conditional node to a relationship, or, when a branch has more than one relationship, from
76/// the conditional to an intermediate `Branch` node and from that node to each relationship —
77/// and styled by `branch_index` and `branch_active`.
78#[derive(Serialize, Clone, PartialEq)]
79///
80/// # Examples
81///
82/// A control link whose `branch_active` is `None` represents an unknown conditional
83/// evaluation, not a successfully selected default branch.
84pub struct LinkData {
85    /// Stable string ID of the source node.
86    pub source: String,
87    /// Stable string ID of the target node.
88    pub target: String,
89    /// The kind of link, determining its visual rendering.
90    pub kind: LinkKind,
91    /// `true` if this link's direction is known and should render with an arrowhead.
92    pub directed: bool,
93    /// Branch index for `Control` links; `None` for `Constraint` links and default-branch control links.
94    pub branch_index: Option<usize>,
95    /// `true` if active, `false` if inactive; `None` for constraints or failed evaluation.
96    pub branch_active: Option<bool>,
97}
98
99/// Complete graph snapshot ready for JSON serialization and delivery to D3.
100#[derive(Serialize, Clone, PartialEq)]
101///
102/// # Examples
103///
104/// `to_graph_data(&sheet, &labels)` returns a serializable snapshot whose `changed`
105/// IDs identify the runtime's changed cells.
106pub struct GraphData {
107    /// All nodes in the graph snapshot.
108    pub nodes: Vec<NodeData>,
109    /// All links (constraint and control) in the graph snapshot.
110    pub links: Vec<LinkData>,
111    /// Stable IDs of cells that changed during the last `propagate()` call.
112    pub changed: Vec<String>,
113    /// Stable IDs of cells forced by an active relationship (see
114    /// [`adam_rs::Sheet::is_forced`]); consumers should disable input for these
115    /// cells and may render them distinctly.
116    pub forced: Vec<String>,
117    /// Stable IDs of relationships forced by the planner (see
118    /// [`adam_rs::Sheet::is_relationship_forced`]); consumers may render them
119    /// distinctly, along with their constraint edges.
120    pub forced_relationships: Vec<String>,
121}
122
123/// Returns the cell's stable, kind-prefixed graph ID.
124fn cell_node_id(id: CellId) -> String {
125    format!("c{}", id.data().as_ffi())
126}
127
128/// Returns the relationship's stable, kind-prefixed graph ID.
129fn rel_node_id(id: RelationshipId) -> String {
130    format!("r{}", id.data().as_ffi())
131}
132
133/// Returns the conditional's stable, kind-prefixed graph ID.
134fn cond_node_id(id: ConditionalId) -> String {
135    format!("cond{}", id.data().as_ffi())
136}
137
138/// Returns the stable node ID for the junction node of one branch (or the default) of a
139/// conditional: `"br{ffi}_{branch}"` for a named branch, `"br{ffi}_def"` for the default.
140fn branch_node_id(id: ConditionalId, branch: Option<usize>) -> String {
141    match branch {
142        Some(b) => format!("br{}_{}", id.data().as_ffi(), b),
143        None => format!("br{}_def", id.data().as_ffi()),
144    }
145}
146
147/// Pushes control links (and, when needed, a junction node) for one branch — named or
148/// default — of a conditional.
149///
150/// - Postcondition: when `rels.len() >= 2`, pushes one `Branch` node, one
151///   `conditional → branch` control link, and one `branch → relationship` control link per
152///   entry in `rels`, all sharing `branch_index`/`branch_active`. When `rels.len() <= 1`,
153///   pushes at most one direct `conditional → relationship` control link (none if `rels` is
154///   empty), matching the pre-junction-node behavior.
155/// - Complexity: O(k) where k = `rels.len()` (the number of relationships in this branch or default).
156fn push_branch_links(
157    nodes: &mut Vec<NodeData>,
158    links: &mut Vec<LinkData>,
159    cond_id_str: &str,
160    cond_id: ConditionalId,
161    branch_index: Option<usize>,
162    branch_active: Option<bool>,
163    rels: &[RelationshipId],
164) {
165    if rels.len() >= 2 {
166        let bnode_id = branch_node_id(cond_id, branch_index);
167        nodes.push(NodeData {
168            id: bnode_id.clone(),
169            kind: NodeKind::Branch,
170            label: String::new(),
171            value: String::new(),
172        });
173        links.push(LinkData {
174            source: cond_id_str.to_string(),
175            target: bnode_id.clone(),
176            kind: LinkKind::Control,
177            directed: true,
178            branch_index,
179            branch_active,
180        });
181        for &rel_id in rels {
182            links.push(LinkData {
183                source: bnode_id.clone(),
184                target: rel_node_id(rel_id),
185                kind: LinkKind::Control,
186                directed: true,
187                branch_index,
188                branch_active,
189            });
190        }
191    } else {
192        for &rel_id in rels {
193            links.push(LinkData {
194                source: cond_id_str.to_string(),
195                target: rel_node_id(rel_id),
196                kind: LinkKind::Control,
197                directed: true,
198                branch_index,
199                branch_active,
200            });
201        }
202    }
203}
204
205/// Serializes `sheet` and `labels` into a [`GraphData`] snapshot for D3.
206///
207/// Constraint links: when `sheet.selected_method` supplies a relationship method,
208/// its links are directed (inputs → relationship → outputs, [`LinkData::directed`]
209/// `true`). Otherwise all cells adjacent to that relationship are emitted as undirected
210/// source→relationship edges (`directed` `false`) — this is decided per relationship, so one
211/// relationship having a plan never marks another relationship's links as directed.
212///
213/// Conditional nodes: for each conditional, emits one `Conditional` node, one always-directed
214/// `Constraint` link from the match cell to the conditional node, and one `Control` link per
215/// relationship in each branch/default. When a branch (or the default) holds more than one
216/// relationship, its control links route through an intermediate `Branch` junction node
217/// (`conditional → branch →
218/// relationship`) instead of a direct edge, so the branch's relationships visually group
219/// together; branches with 0 or 1 relationships keep a direct edge. Control links carry
220/// `branch_index` and `branch_active` for rendering, shared identically across both hops of a
221/// junction-routed branch.
222///
223/// - Complexity: O(c + r + e + t) traversal/copy work for cells, relationships,
224///   emitted links, and copied text; cell formatting, conditional matching/evaluation,
225///   and sheet classification queries add their own costs.
226///
227/// # Examples
228///
229/// ```
230/// let sheet = adam_rs::Sheet::new();
231/// let data = adam_web_ui::to_graph_data(&sheet, &adam_web_ui::Labels::new());
232/// assert!(data.nodes.is_empty());
233/// ```
234pub fn to_graph_data(sheet: &Sheet, labels: &Labels) -> GraphData {
235    let mut nodes = Vec::new();
236    let mut links = Vec::new();
237
238    // Cell nodes
239    for id in sheet.cells() {
240        let (label, value) = labels
241            .cells
242            .get(&id)
243            .map(|m| (m.label.clone(), (m.display)(sheet)))
244            .unwrap_or_default();
245        nodes.push(NodeData {
246            id: cell_node_id(id),
247            kind: NodeKind::Cell,
248            label,
249            value,
250        });
251    }
252
253    // Relationship nodes and constraint links
254    for id in sheet.relationships() {
255        nodes.push(NodeData {
256            id: rel_node_id(id),
257            kind: NodeKind::Relationship,
258            label: String::new(),
259            value: String::new(),
260        });
261
262        if let Some(method_idx) = sheet.selected_method(id) {
263            if let Some(inputs) = sheet.method_inputs(id, method_idx) {
264                for &cell_id in inputs {
265                    links.push(LinkData {
266                        source: cell_node_id(cell_id),
267                        target: rel_node_id(id),
268                        kind: LinkKind::Constraint,
269                        directed: true,
270                        branch_index: None,
271                        branch_active: None,
272                    });
273                }
274            }
275            if let Some(outputs) = sheet.method_outputs(id, method_idx) {
276                for &cell_id in outputs {
277                    links.push(LinkData {
278                        source: rel_node_id(id),
279                        target: cell_node_id(cell_id),
280                        kind: LinkKind::Constraint,
281                        directed: true,
282                        branch_index: None,
283                        branch_active: None,
284                    });
285                }
286            }
287        } else if let Some(adj) = sheet.relationship_adj(id) {
288            for &cell_id in adj {
289                links.push(LinkData {
290                    source: cell_node_id(cell_id),
291                    target: rel_node_id(id),
292                    kind: LinkKind::Constraint,
293                    directed: false,
294                    branch_index: None,
295                    branch_active: None,
296                });
297            }
298        }
299    }
300
301    // Conditional nodes and control links
302    for cond_id in sheet.conditionals() {
303        let node_id = cond_node_id(cond_id);
304        nodes.push(NodeData {
305            id: node_id.clone(),
306            kind: NodeKind::Conditional,
307            label: String::new(),
308            value: String::new(),
309        });
310
311        // Constraint links: every match cell → conditional node. Always directed --
312        // evaluating a conditional's match expression doesn't depend on any relationship
313        // (in this branch or any other) ever having a selected method, so this must not
314        // be gated on relationship planning the way cell ↔ relationship links are.
315        if let Some(match_cells) = sheet.conditional_match_cells(cond_id) {
316            for &match_cell in match_cells {
317                links.push(LinkData {
318                    source: cell_node_id(match_cell),
319                    target: node_id.clone(),
320                    kind: LinkKind::Constraint,
321                    directed: true,
322                    branch_index: None,
323                    branch_active: None,
324                });
325            }
326        }
327
328        let active_branch = sheet.conditional_active_branch(cond_id).ok();
329
330        // Control links for named branches
331        let branch_count = sheet.conditional_branch_count(cond_id).unwrap_or(0);
332        for branch in 0..branch_count {
333            let is_active = active_branch.map(|active| active == Some(branch));
334            if let Some(rels) = sheet.conditional_branch_relationships(cond_id, branch) {
335                push_branch_links(
336                    &mut nodes,
337                    &mut links,
338                    &node_id,
339                    cond_id,
340                    Some(branch),
341                    is_active,
342                    rels,
343                );
344            }
345        }
346
347        // Control links for default relationships
348        let default_active = active_branch.map(|active| active.is_none());
349        if let Some(default_rels) = sheet.conditional_default_relationships(cond_id) {
350            push_branch_links(
351                &mut nodes,
352                &mut links,
353                &node_id,
354                cond_id,
355                None,
356                default_active,
357                default_rels,
358            );
359        }
360    }
361
362    let changed = sheet.changed().map(cell_node_id).collect();
363    let forced = sheet.forced_cells().map(cell_node_id).collect();
364    let forced_relationships = sheet.forced_relationships().map(rel_node_id).collect();
365
366    GraphData {
367        nodes,
368        links,
369        changed,
370        forced,
371        forced_relationships,
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    /// Evaluation failure retains source diagnostics after the candidate is dropped.
380    #[test]
381    fn conditional_evaluation_failure_retains_owned_diagnostics() {
382        let source = r#"sheet s {
383            source divisor: i64 = 1i64;
384            cell a: i64;
385            cell b: i64;
386            conditional 1i64 / divisor {
387                1i64 => { relationship { a := b; } }
388                _ => { relationship { b := a; } }
389            }
390        }"#;
391        let built = crate::build_sheet(source, "s.adm2").unwrap();
392        let mut sheet = built.parsed;
393        let divisor = sheet.cell_names["divisor"].0;
394        sheet.write(divisor, 0i64).unwrap();
395        let diagnostics = sheet.diagnostics();
396        let error = sheet.propagate().unwrap_err();
397        drop(sheet);
398        assert!(!diagnostics.locate_error(&error).is_empty());
399    }
400    use adam_rs::{MatchExpr, Method};
401
402    /// Builds an unpropagated three-cell product relationship and scalar labels.
403    fn demo_sheet() -> (Sheet, Labels) {
404        let mut sheet = Sheet::new();
405        let mut labels = Labels::new();
406
407        let a = sheet.add_cell(2.0_f64);
408        labels.add_cell::<f64>(a, "a");
409        let b = sheet.add_cell(3.0_f64);
410        labels.add_cell::<f64>(b, "b");
411        let c = sheet.add_cell(0.0_f64);
412        labels.add_cell::<f64>(c, "c");
413
414        sheet
415            .add_relationship(vec![Method::from_fn_2_1([a, b], c, |x: &f64, y: &f64| {
416                Ok(x * y)
417            })])
418            .unwrap();
419
420        (sheet, labels)
421    }
422
423    /// Builds an unpropagated product sheet with its output cell inserted first.
424    fn demo_sheet_with_plan() -> (Sheet, Labels) {
425        let mut sheet = Sheet::new();
426        let mut labels = Labels::new();
427
428        // c added first → lowest strength (output by default).
429        let c = sheet.add_cell(0.0_f64);
430        labels.add_cell::<f64>(c, "c");
431        let a = sheet.add_cell(2.0_f64);
432        labels.add_cell::<f64>(a, "a");
433        let b = sheet.add_cell(3.0_f64);
434        labels.add_cell::<f64>(b, "b");
435
436        sheet
437            .add_relationship(vec![Method::from_fn_2_1([a, b], c, |x: &f64, y: &f64| {
438                Ok(x * y)
439            })])
440            .unwrap();
441
442        (sheet, labels)
443    }
444
445    /// Builds one reversible relationship enabled by an integer selector's zero branch.
446    fn sheet_with_conditional() -> (Sheet, Labels) {
447        let mut sheet = Sheet::new();
448        let mut labels = Labels::new();
449
450        let a = sheet.add_cell(2.0_f64);
451        labels.add_cell::<f64>(a, "a");
452        let b = sheet.add_cell(0.0_f64);
453        labels.add_cell::<f64>(b, "b");
454        let p = sheet.add_cell(0_i32);
455        labels.add_cell::<i32>(p, "p");
456
457        let rel = sheet
458            .add_relationship(vec![
459                Method::from_fn_1_1(a, b, |v: &f64| Ok(*v)),
460                Method::from_fn_1_1(b, a, |v: &f64| Ok(*v)),
461            ])
462            .unwrap();
463
464        sheet
465            .add_conditional(MatchExpr::cell(p), vec![(vec![0_i32], vec![rel])], vec![])
466            .unwrap();
467
468        (sheet, labels)
469    }
470
471    /// Builds one one-way relationship enabled by an integer selector's zero branch.
472    fn sheet_with_forced_conditional() -> (Sheet, Labels) {
473        let mut sheet = Sheet::new();
474        let mut labels = Labels::new();
475
476        let a = sheet.add_cell(2.0_f64);
477        labels.add_cell::<f64>(a, "a");
478        let b = sheet.add_cell(0.0_f64);
479        labels.add_cell::<f64>(b, "b");
480        let p = sheet.add_cell(0_i32);
481        labels.add_cell::<i32>(p, "p");
482
483        let rel = sheet
484            .add_relationship(vec![Method::from_fn_1_1(a, b, |v: &f64| Ok(*v))])
485            .unwrap();
486
487        sheet
488            .add_conditional(MatchExpr::cell(p), vec![(vec![0_i32], vec![rel])], vec![])
489            .unwrap();
490
491        (sheet, labels)
492    }
493
494    /// Builds two one-way relationships sharing a named conditional branch.
495    fn sheet_with_multi_relationship_branch() -> (Sheet, Labels) {
496        let mut sheet = Sheet::new();
497        let mut labels = Labels::new();
498
499        let a = sheet.add_cell(2.0_f64);
500        labels.add_cell::<f64>(a, "a");
501        let b = sheet.add_cell(0.0_f64);
502        labels.add_cell::<f64>(b, "b");
503        let c = sheet.add_cell(0.0_f64);
504        labels.add_cell::<f64>(c, "c");
505        let p = sheet.add_cell(0_i32);
506        labels.add_cell::<i32>(p, "p");
507
508        let rel1 = sheet
509            .add_relationship(vec![Method::from_fn_1_1(a, b, |v: &f64| Ok(*v))])
510            .unwrap();
511        let rel2 = sheet
512            .add_relationship(vec![Method::from_fn_1_1(a, c, |v: &f64| Ok(*v))])
513            .unwrap();
514
515        sheet
516            .add_conditional(
517                MatchExpr::cell(p),
518                vec![(vec![0_i32], vec![rel1, rel2])],
519                vec![],
520            )
521            .unwrap();
522
523        (sheet, labels)
524    }
525
526    /// Builds two one-way relationships sharing an unconditional default branch.
527    fn sheet_with_multi_relationship_default() -> (Sheet, Labels) {
528        let mut sheet = Sheet::new();
529        let mut labels = Labels::new();
530
531        let a = sheet.add_cell(2.0_f64);
532        labels.add_cell::<f64>(a, "a");
533        let b = sheet.add_cell(0.0_f64);
534        labels.add_cell::<f64>(b, "b");
535        let c = sheet.add_cell(0.0_f64);
536        labels.add_cell::<f64>(c, "c");
537        let p = sheet.add_cell(0_i32);
538        labels.add_cell::<i32>(p, "p");
539
540        let rel1 = sheet
541            .add_relationship(vec![Method::from_fn_1_1(a, b, |v: &f64| Ok(*v))])
542            .unwrap();
543        let rel2 = sheet
544            .add_relationship(vec![Method::from_fn_1_1(a, c, |v: &f64| Ok(*v))])
545            .unwrap();
546
547        sheet
548            .add_conditional::<i32>(MatchExpr::cell(p), vec![], vec![rel1, rel2])
549            .unwrap();
550
551        (sheet, labels)
552    }
553
554    #[test]
555    /// Single-relationship branches connect directly without a junction node.
556    fn to_graph_data_omits_branch_node_for_single_relationship_branch() {
557        let (sheet, labels) = sheet_with_conditional();
558        let data = to_graph_data(&sheet, &labels);
559        assert!(
560            !data.nodes.iter().any(|n| n.kind == NodeKind::Branch),
561            "expected no Branch node when every branch has at most one relationship"
562        );
563    }
564
565    #[test]
566    /// Multi-relationship named branches route both control hops through a junction.
567    fn to_graph_data_routes_multi_relationship_branch_through_branch_node() {
568        let (sheet, labels) = sheet_with_multi_relationship_branch();
569        let data = to_graph_data(&sheet, &labels);
570
571        let cond_id = data
572            .nodes
573            .iter()
574            .find(|n| n.kind == NodeKind::Conditional)
575            .map(|n| n.id.clone())
576            .unwrap();
577        let branch_id = data
578            .nodes
579            .iter()
580            .find(|n| n.kind == NodeKind::Branch)
581            .map(|n| n.id.clone())
582            .expect("expected a Branch node");
583
584        assert!(
585            data.links
586                .iter()
587                .any(|l| matches!(l.kind, LinkKind::Control)
588                    && l.source == cond_id
589                    && l.target == branch_id
590                    && l.branch_index == Some(0)
591                    && l.branch_active == Some(true)),
592            "expected a Control link from the conditional to the branch node"
593        );
594
595        let rel_ids: Vec<_> = data
596            .nodes
597            .iter()
598            .filter(|n| n.kind == NodeKind::Relationship)
599            .map(|n| n.id.clone())
600            .collect();
601        assert_eq!(rel_ids.len(), 2);
602        for rel_id in rel_ids {
603            assert!(
604                data.links
605                    .iter()
606                    .any(|l| matches!(l.kind, LinkKind::Control)
607                        && l.source == branch_id
608                        && l.target == rel_id
609                        && l.branch_index == Some(0)
610                        && l.branch_active == Some(true)),
611                "expected a Control link from the branch node to relationship {rel_id}"
612            );
613        }
614    }
615
616    #[test]
617    /// Multi-relationship defaults route both control hops through a junction.
618    fn to_graph_data_routes_multi_relationship_default_through_branch_node() {
619        let (sheet, labels) = sheet_with_multi_relationship_default();
620        let data = to_graph_data(&sheet, &labels);
621
622        let cond_id = data
623            .nodes
624            .iter()
625            .find(|n| n.kind == NodeKind::Conditional)
626            .map(|n| n.id.clone())
627            .unwrap();
628        let branch_id = data
629            .nodes
630            .iter()
631            .find(|n| n.kind == NodeKind::Branch)
632            .map(|n| n.id.clone())
633            .expect("expected a Branch node for the default relationships");
634
635        assert!(
636            data.links
637                .iter()
638                .any(|l| matches!(l.kind, LinkKind::Control)
639                    && l.source == cond_id
640                    && l.target == branch_id
641                    && l.branch_index.is_none()
642                    && l.branch_active == Some(true)),
643            "expected a Control link from the conditional to the default branch node"
644        );
645
646        let rel_ids: Vec<_> = data
647            .nodes
648            .iter()
649            .filter(|n| n.kind == NodeKind::Relationship)
650            .map(|n| n.id.clone())
651            .collect();
652        assert_eq!(rel_ids.len(), 2);
653        for rel_id in rel_ids {
654            assert!(
655                data.links
656                    .iter()
657                    .any(|l| matches!(l.kind, LinkKind::Control)
658                        && l.source == branch_id
659                        && l.target == rel_id
660                        && l.branch_index.is_none()
661                        && l.branch_active == Some(true)),
662                "expected a Control link from the default branch node to relationship {rel_id}"
663            );
664        }
665    }
666
667    #[test]
668    /// Serialization emits one node per cell and relationship in the fixture.
669    fn to_graph_data_produces_correct_node_counts() {
670        let (sheet, labels) = demo_sheet();
671        let data = to_graph_data(&sheet, &labels);
672        assert_eq!(
673            data.nodes
674                .iter()
675                .filter(|n| n.kind == NodeKind::Cell)
676                .count(),
677            3
678        );
679        assert_eq!(
680            data.nodes
681                .iter()
682                .filter(|n| n.kind == NodeKind::Relationship)
683                .count(),
684            1
685        );
686    }
687
688    #[test]
689    /// Serialization emits every relationship membership link.
690    fn to_graph_data_produces_correct_link_count() {
691        let (sheet, labels) = demo_sheet();
692        let data = to_graph_data(&sheet, &labels);
693        assert_eq!(data.links.len(), 3);
694    }
695
696    #[test]
697    /// Cell graph nodes preserve registered labels.
698    fn to_graph_data_cell_nodes_have_labels() {
699        let (sheet, labels) = demo_sheet();
700        let data = to_graph_data(&sheet, &labels);
701        let cell_labels: Vec<_> = data
702            .nodes
703            .iter()
704            .filter(|n| n.kind == NodeKind::Cell)
705            .map(|n| n.label.as_str())
706            .collect();
707        assert!(cell_labels.contains(&"a"));
708        assert!(cell_labels.contains(&"b"));
709        assert!(cell_labels.contains(&"c"));
710    }
711
712    #[test]
713    /// Anonymous relationship graph nodes have empty labels.
714    fn to_graph_data_relationship_nodes_have_empty_labels() {
715        let (sheet, labels) = demo_sheet();
716        let data = to_graph_data(&sheet, &labels);
717        for node in data
718            .nodes
719            .iter()
720            .filter(|n| n.kind == NodeKind::Relationship)
721        {
722            assert!(node.label.is_empty());
723        }
724    }
725
726    #[test]
727    /// Changed graph IDs exactly represent the runtime's changed-cell set without duplicates.
728    fn to_graph_data_changed_contains_changed_cell_ids() {
729        let (mut sheet, labels) = demo_sheet();
730        let a_id = sheet
731            .cells()
732            .find(|&id| labels.cells.get(&id).map(|m| m.label.as_str()) == Some("a"))
733            .unwrap();
734        let b_id = sheet
735            .cells()
736            .find(|&id| labels.cells.get(&id).map(|m| m.label.as_str()) == Some("b"))
737            .unwrap();
738        sheet.write(a_id, 2.0_f64).unwrap();
739        sheet.write(b_id, 3.0_f64).unwrap();
740        sheet.propagate().unwrap();
741
742        let data = to_graph_data(&sheet, &labels);
743        let expected: std::collections::HashSet<_> = sheet.changed().map(cell_node_id).collect();
744        assert_eq!(
745            data.changed
746                .iter()
747                .cloned()
748                .collect::<std::collections::HashSet<_>>(),
749            expected
750        );
751        assert_eq!(data.changed.len(), expected.len());
752    }
753
754    #[test]
755    /// Relationships without a selected plan render undirected membership links.
756    fn to_graph_data_constraint_links_undirected_before_propagate() {
757        let (sheet, labels) = demo_sheet_with_plan();
758        let data = to_graph_data(&sheet, &labels);
759        assert!(
760            data.links
761                .iter()
762                .filter(|l| matches!(l.kind, LinkKind::Constraint))
763                .all(|l| !l.directed),
764            "no relationship has a cached plan yet, so every constraint link must be undirected"
765        );
766    }
767
768    #[test]
769    /// Selected relationship methods produce directed dependency links.
770    fn to_graph_data_constraint_links_directed_after_propagate() {
771        let (mut sheet, labels) = demo_sheet_with_plan();
772        sheet.propagate().unwrap();
773        let data = to_graph_data(&sheet, &labels);
774        assert!(
775            data.links
776                .iter()
777                .filter(|l| matches!(l.kind, LinkKind::Constraint))
778                .any(|l| l.directed),
779            "the relationship's cached plan should make its constraint links directed"
780        );
781    }
782
783    #[test]
784    /// Selector dependencies remain directed when their conditional branch is inactive.
785    fn to_graph_data_match_cell_link_is_directed_even_when_conditional_branch_is_inactive() {
786        // Reproduces adam-lang-book's constrain.adm2: a sheet whose only relationship
787        // lives inside a conditional, currently not matching any branch. No relationship
788        // anywhere in the sheet has a cached plan, but the match cell -> conditional link
789        // must still render directed -- evaluating the conditional's match expression
790        // doesn't depend on any relationship ever being planned.
791        let (mut sheet, labels) = sheet_with_conditional();
792        sheet.propagate().unwrap();
793        let data = to_graph_data(&sheet, &labels);
794
795        let cond_id = data
796            .nodes
797            .iter()
798            .find(|n| n.kind == NodeKind::Conditional)
799            .map(|n| n.id.clone())
800            .unwrap();
801        let match_link = data
802            .links
803            .iter()
804            .find(|l| matches!(l.kind, LinkKind::Constraint) && l.target == cond_id)
805            .expect("expected a Constraint link targeting the conditional node");
806        assert!(
807            match_link.directed,
808            "the match cell -> conditional link must be directed regardless of whether \
809             the conditional's own relationship currently has a plan"
810        );
811    }
812
813    #[test]
814    /// One relationship's selected plan does not direct another unplanned relationship's links.
815    fn to_graph_data_undirected_relationship_link_is_independent_of_other_relationships() {
816        // R1 (a -> b) is unconditional and always planned; R2 (x <-> y, two methods) lives
817        // in a conditional that currently doesn't match any branch, so R2 has no plan. R1
818        // having a plan must not make R2's fallback adjacency links directed too -- each
819        // relationship's `directed` flag is its own fact, not a sheet-wide one.
820        let mut sheet = Sheet::new();
821        let mut labels = Labels::new();
822        let a = sheet.add_cell(2.0_f64);
823        labels.add_cell::<f64>(a, "a");
824        let b = sheet.add_cell(0.0_f64);
825        labels.add_cell::<f64>(b, "b");
826        sheet
827            .add_relationship(vec![Method::from_fn_1_1(a, b, |v: &f64| Ok(*v))])
828            .unwrap();
829
830        let x = sheet.add_cell(1.0_f64);
831        labels.add_cell::<f64>(x, "x");
832        let y = sheet.add_cell(2.0_f64);
833        labels.add_cell::<f64>(y, "y");
834        let p = sheet.add_cell(0_i32);
835        labels.add_cell::<i32>(p, "p");
836        let rel_xy = sheet
837            .add_relationship(vec![
838                Method::from_fn_1_1(x, y, |v: &f64| Ok(*v)),
839                Method::from_fn_1_1(y, x, |v: &f64| Ok(*v)),
840            ])
841            .unwrap();
842        sheet
843            .add_conditional(
844                MatchExpr::cell(p),
845                vec![(vec![1_i32], vec![rel_xy])],
846                vec![],
847            )
848            .unwrap();
849
850        sheet.propagate().unwrap();
851        let data = to_graph_data(&sheet, &labels);
852
853        let rel_xy_id = rel_node_id(rel_xy);
854        assert!(
855            data.links
856                .iter()
857                .filter(|l| matches!(l.kind, LinkKind::Constraint)
858                    && (l.source == rel_xy_id || l.target == rel_xy_id))
859                .all(|l| !l.directed),
860            "R2's links must stay undirected even though R1 elsewhere has a cached plan"
861        );
862    }
863
864    #[test]
865    /// Selected input dependencies point toward the relationship.
866    fn to_graph_data_directed_input_links_target_relationship() {
867        let (mut sheet, labels) = demo_sheet_with_plan();
868        sheet.propagate().unwrap();
869        let data = to_graph_data(&sheet, &labels);
870
871        let rel_id = data
872            .nodes
873            .iter()
874            .find(|n| n.kind == NodeKind::Relationship)
875            .map(|n| n.id.clone())
876            .unwrap();
877
878        let to_rel: Vec<_> = data
879            .links
880            .iter()
881            .filter(|l| matches!(l.kind, LinkKind::Constraint) && l.target == rel_id)
882            .collect();
883        assert_eq!(to_rel.len(), 2);
884    }
885
886    #[test]
887    /// Selected output dependencies point away from the relationship.
888    fn to_graph_data_directed_output_links_source_relationship() {
889        let (mut sheet, labels) = demo_sheet_with_plan();
890        sheet.propagate().unwrap();
891        let data = to_graph_data(&sheet, &labels);
892
893        let rel_id = data
894            .nodes
895            .iter()
896            .find(|n| n.kind == NodeKind::Relationship)
897            .map(|n| n.id.clone())
898            .unwrap();
899
900        let from_rel: Vec<_> = data
901            .links
902            .iter()
903            .filter(|l| matches!(l.kind, LinkKind::Constraint) && l.source == rel_id)
904            .collect();
905        assert_eq!(from_rel.len(), 1);
906    }
907
908    #[test]
909    /// Conditional selectors produce conditional graph nodes.
910    fn to_graph_data_emits_conditional_node() {
911        let (sheet, labels) = sheet_with_conditional();
912        let data = to_graph_data(&sheet, &labels);
913        assert!(
914            data.nodes.iter().any(|n| n.kind == NodeKind::Conditional),
915            "expected a Conditional node"
916        );
917    }
918
919    #[test]
920    /// Conditional selectors retain their match-cell dependency links.
921    fn to_graph_data_emits_constraint_link_from_match_cell_to_conditional() {
922        let (sheet, labels) = sheet_with_conditional();
923        let data = to_graph_data(&sheet, &labels);
924        let cond_id = data
925            .nodes
926            .iter()
927            .find(|n| n.kind == NodeKind::Conditional)
928            .map(|n| n.id.clone())
929            .unwrap();
930        assert!(
931            data.links
932                .iter()
933                .any(|l| matches!(l.kind, LinkKind::Constraint) && l.target == cond_id),
934            "expected a Constraint link targeting the conditional node"
935        );
936    }
937
938    #[test]
939    /// Active branch relationships retain their branch index and active control state.
940    fn to_graph_data_active_branch_control_link_is_active() {
941        let (sheet, labels) = sheet_with_conditional();
942        let data = to_graph_data(&sheet, &labels);
943        let active_control = data
944            .links
945            .iter()
946            .find(|l| matches!(l.kind, LinkKind::Control) && l.branch_index == Some(0));
947        assert!(
948            active_control.is_some(),
949            "expected a Control link for branch 0"
950        );
951        assert_eq!(active_control.unwrap().branch_active, Some(true));
952    }
953
954    #[test]
955    /// Serialized graph snapshots omit the obsolete groups field.
956    fn to_graph_data_no_groups_field() {
957        let (sheet, labels) = sheet_with_conditional();
958        let data = to_graph_data(&sheet, &labels);
959        let json = serde_json::to_string(&data).unwrap();
960        assert!(
961            !json.contains("\"groups\""),
962            "GraphData must not contain groups"
963        );
964    }
965
966    #[test]
967    /// Forced active cells appear in the graph's forced-cell IDs.
968    fn to_graph_data_forced_field_contains_forced_cell() {
969        let (mut sheet, labels) = sheet_with_forced_conditional();
970        sheet.propagate().unwrap();
971
972        let b_id = sheet
973            .cells()
974            .find(|&id| labels.cells.get(&id).map(|m| m.label.as_str()) == Some("b"))
975            .unwrap();
976
977        let data = to_graph_data(&sheet, &labels);
978        assert!(data.forced.contains(&cell_node_id(b_id)));
979    }
980
981    #[test]
982    /// Inactive conditional relationships do not force their former output cells.
983    fn to_graph_data_forced_field_excludes_cell_when_branch_inactive() {
984        let (mut sheet, labels) = sheet_with_forced_conditional();
985        let p_id = sheet
986            .cells()
987            .find(|&id| labels.cells.get(&id).map(|m| m.label.as_str()) == Some("p"))
988            .unwrap();
989        sheet.write(p_id, 1_i32).unwrap();
990        sheet.propagate().unwrap();
991
992        let b_id = sheet
993            .cells()
994            .find(|&id| labels.cells.get(&id).map(|m| m.label.as_str()) == Some("b"))
995            .unwrap();
996
997        let data = to_graph_data(&sheet, &labels);
998        assert!(!data.forced.contains(&cell_node_id(b_id)));
999    }
1000
1001    #[test]
1002    /// Forced active relationships appear in the graph's forced-relationship IDs.
1003    fn to_graph_data_forced_relationships_field_contains_forced_relationship() {
1004        let (mut sheet, labels) = sheet_with_forced_conditional();
1005        let rel_id = sheet.relationships().next().unwrap();
1006        sheet.propagate().unwrap();
1007
1008        let data = to_graph_data(&sheet, &labels);
1009        assert!(data.forced_relationships.contains(&rel_node_id(rel_id)));
1010    }
1011
1012    #[test]
1013    /// Inactive relationships do not appear in forced-relationship IDs.
1014    fn to_graph_data_forced_relationships_field_excludes_relationship_when_branch_inactive() {
1015        let (mut sheet, labels) = sheet_with_forced_conditional();
1016        let rel_id = sheet.relationships().next().unwrap();
1017        let p_id = sheet
1018            .cells()
1019            .find(|&id| labels.cells.get(&id).map(|m| m.label.as_str()) == Some("p"))
1020            .unwrap();
1021        sheet.write(p_id, 1_i32).unwrap();
1022        sheet.propagate().unwrap();
1023
1024        let data = to_graph_data(&sheet, &labels);
1025        assert!(!data.forced_relationships.contains(&rel_node_id(rel_id)));
1026    }
1027}