alizarin-core 2.0.0-alpha.118

Core data structures and algorithms for Arches heritage graph and tile processing
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
//! Graph pruning utilities
//!
//! Provides functions for pruning a graph to only include permitted nodegroups
//! and their dependencies. This is useful for permission-based filtering.

use super::{StaticGraph, StaticNode};
use std::collections::{HashMap, HashSet};

/// Maximum depth for edge traversal to prevent infinite loops
const MAX_GRAPH_DEPTH: usize = 100;

/// Error type for graph pruning operations
#[derive(Debug, Clone)]
pub enum PruneError {
    /// Node has multiple parents (malformed graph)
    MultipleParents {
        node: String,
        parent1: String,
        parent2: String,
    },
    /// Node has no parent but is not root (disconnected)
    NoParent { node: String },
    /// Edge traversal hit depth limit (likely cycle)
    CycleDetected,
    /// Graph has no root node
    NoRootNode,
}

impl std::fmt::Display for PruneError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PruneError::MultipleParents {
                node,
                parent1,
                parent2,
            } => {
                write!(
                    f,
                    "Graph is malformed, node {} has multiple parents: {} and {}",
                    node, parent1, parent2
                )
            }
            PruneError::NoParent { node } => {
                write!(f, "Graph does not have a parent for {}", node)
            }
            PruneError::CycleDetected => {
                write!(f, "Hit edge traversal limit when pruning, is the graph well-formed without cycles?")
            }
            PruneError::NoRootNode => {
                write!(f, "Could not find root node in graph")
            }
        }
    }
}

impl std::error::Error for PruneError {}

/// Find the root node of a graph
///
/// The root node is the node with no nodegroup_id or an empty nodegroup_id.
pub fn find_root_node(graph: &StaticGraph) -> Option<&StaticNode> {
    graph.nodes.iter().find(|node| {
        node.nodegroup_id.is_none()
            || node
                .nodegroup_id
                .as_ref()
                .map(|s| s.is_empty())
                .unwrap_or(true)
    })
}

/// Build backedges map (child -> parent) from a graph's edges
///
/// Returns an error if any node has multiple parents.
pub fn build_backedges(graph: &StaticGraph) -> Result<HashMap<String, String>, PruneError> {
    let mut backedges: HashMap<String, String> = HashMap::new();

    for edge in &graph.edges {
        if let Some(existing_parent) = backedges.get(&edge.rangenode_id) {
            return Err(PruneError::MultipleParents {
                node: edge.rangenode_id.clone(),
                parent1: existing_parent.clone(),
                parent2: edge.domainnode_id.clone(),
            });
        }
        backedges.insert(edge.rangenode_id.clone(), edge.domainnode_id.clone());
    }

    Ok(backedges)
}

/// Prune a graph to only include permitted nodegroups and their dependencies.
///
/// # Arguments
/// * `graph` - The graph to prune
/// * `is_nodegroup_permitted` - Function that returns true if a nodegroup is permitted
/// * `keep_functions` - Optional list of function IDs to keep (if None, all functions are removed)
///
/// # Returns
/// A new pruned graph containing only permitted nodes, edges, cards, etc.
///
/// # Errors
/// Returns an error if the graph is malformed (multiple parents, cycles, etc.)
pub fn prune_graph<F>(
    graph: &StaticGraph,
    is_nodegroup_permitted: F,
    keep_functions: Option<&[String]>,
) -> Result<StaticGraph, PruneError>
where
    F: Fn(&str) -> bool,
{
    // Find root node
    let root_node = find_root_node(graph).ok_or(PruneError::NoRootNode)?;
    let root = root_node.nodeid.clone();

    // Build nodegroup set from nodes
    let all_nodegroups: HashSet<String> = graph
        .nodes
        .iter()
        .filter_map(|n| n.nodegroup_id.clone())
        .collect();

    // Build allowed_nodegroups map: nodegroup_id -> is_rooted
    // Filter to only permitted nodegroups
    let mut allowed_nodegroups: HashMap<String, bool> = all_nodegroups
        .iter()
        .filter(|ng_id| is_nodegroup_permitted(ng_id))
        .map(|ng_id| {
            let is_root = ng_id.is_empty() || *ng_id == root;
            (ng_id.clone(), is_root)
        })
        .collect();

    // Build backedges map (child -> parent)
    let backedges = build_backedges(graph)?;

    // Mark root as rooted
    allowed_nodegroups.insert(root.clone(), true);

    // Iteratively ensure all kept nodegroups have path to root
    let mut loops = 0;
    while loops < MAX_GRAPH_DEPTH {
        let unrooted: Vec<String> = allowed_nodegroups
            .iter()
            .filter(|(_, &rooted)| !rooted)
            .map(|(ng, _)| ng.clone())
            .collect();

        if unrooted.is_empty() {
            break;
        }

        for ng in unrooted {
            if ng == root {
                continue;
            }

            let next = backedges
                .get(&ng)
                .ok_or_else(|| PruneError::NoParent { node: ng.clone() })?;

            allowed_nodegroups.insert(ng.clone(), true);
            if !allowed_nodegroups.contains_key(next) {
                allowed_nodegroups.insert(next.clone(), false);
            }
        }

        loops += 1;
    }

    if loops >= MAX_GRAPH_DEPTH {
        return Err(PruneError::CycleDetected);
    }

    // Build set of allowed node IDs
    let allowed_nodes: HashSet<String> = graph
        .nodes
        .iter()
        .filter(|node| {
            node.nodegroup_id
                .as_ref()
                .and_then(|ng_id| allowed_nodegroups.get(ng_id))
                .copied()
                .unwrap_or(false)
                || node.nodeid == root
        })
        .map(|node| node.nodeid.clone())
        .collect();

    // Create pruned graph
    let mut pruned = graph.clone();

    // Filter cards
    pruned.cards = pruned.cards.map(|cards| {
        cards
            .into_iter()
            .filter(|card| {
                allowed_nodegroups
                    .get(&card.nodegroup_id)
                    .copied()
                    .unwrap_or(false)
            })
            .collect()
    });

    // Filter cards_x_nodes_x_widgets
    pruned.cards_x_nodes_x_widgets = pruned.cards_x_nodes_x_widgets.map(|cxnxws| {
        cxnxws
            .into_iter()
            .filter(|cxnxw| allowed_nodes.contains(&cxnxw.node_id))
            .collect()
    });

    // Filter edges
    pruned.edges.retain(|edge| {
        (edge.domainnode_id == root || allowed_nodes.contains(&edge.domainnode_id))
            && allowed_nodes.contains(&edge.rangenode_id)
    });

    // Filter nodegroups
    pruned
        .nodegroups
        .retain(|ng| allowed_nodegroups.contains_key(&ng.nodegroupid));

    // Filter nodes
    pruned
        .nodes
        .retain(|node| allowed_nodes.contains(&node.nodeid));

    // Filter functions_x_graphs
    if let Some(keep_fns) = keep_functions {
        pruned.functions_x_graphs = pruned.functions_x_graphs.map(|fxgs| {
            fxgs.into_iter()
                .filter(|fxg| keep_fns.contains(&fxg.function_id))
                .collect()
        });
    } else {
        pruned.functions_x_graphs = Some(Vec::new());
    }

    Ok(pruned)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{StaticEdge, StaticNodegroup};
    use serde_json::json;

    fn create_test_node(nodeid: &str, nodegroup_id: Option<&str>) -> StaticNode {
        let node_json = json!({
            "nodeid": nodeid,
            "name": nodeid,
            "datatype": if nodegroup_id.is_none() { "semantic" } else { "string" },
            "nodegroup_id": nodegroup_id,
            "alias": nodeid,
            "graph_id": "test_graph",
            "is_collector": false,
            "isrequired": false,
            "exportable": true,
            "issearchable": false,
            "istopnode": nodegroup_id.is_none(),
        });
        serde_json::from_value(node_json).expect("Failed to create test node")
    }

    fn create_test_edge(domain: &str, range: &str) -> StaticEdge {
        StaticEdge {
            edgeid: format!("{}->{}", domain, range),
            domainnode_id: domain.to_string(),
            rangenode_id: range.to_string(),
            graph_id: "test_graph".to_string(),
            name: None,
            description: None,
            ontologyproperty: None,
            source_identifier_id: None,
        }
    }

    fn create_test_nodegroup(nodegroupid: &str) -> StaticNodegroup {
        StaticNodegroup {
            nodegroupid: nodegroupid.to_string(),
            cardinality: Some("n".to_string()),
            parentnodegroup_id: None,
            legacygroupid: None,
            grouping_node_id: None,
        }
    }

    #[test]
    fn test_prune_graph_filters_unpermitted_nodegroups() {
        // Create nodes: root, child1 (permitted), child2 (not permitted)
        let root = create_test_node("root", None);
        let child1 = create_test_node("child1", Some("child1"));
        let child2 = create_test_node("child2", Some("child2"));

        let edge1 = create_test_edge("root", "child1");
        let edge2 = create_test_edge("root", "child2");

        let ng1 = create_test_nodegroup("child1");
        let ng2 = create_test_nodegroup("child2");

        let graph_json = json!({
            "graphid": "test_graph",
            "name": {"en": "Test Graph"},
            "nodes": [root.clone(), child1, child2],
            "edges": [edge1, edge2],
            "nodegroups": [ng1, ng2],
            "root": root,
            "cards": [],
            "cards_x_nodes_x_widgets": [],
            "functions_x_graphs": [],
            "config": {}
        });

        let graph: StaticGraph =
            serde_json::from_value(graph_json).expect("Failed to create graph");

        // Only permit child1
        let permitted = |ng: &str| ng == "child1";

        let pruned = prune_graph(&graph, permitted, None).expect("Prune failed");

        // Verify child1 is included, child2 is not
        assert!(
            pruned.nodes.iter().any(|n| n.nodeid == "root"),
            "Root should be included"
        );
        assert!(
            pruned.nodes.iter().any(|n| n.nodeid == "child1"),
            "child1 should be included"
        );
        assert!(
            !pruned.nodes.iter().any(|n| n.nodeid == "child2"),
            "child2 should NOT be included"
        );

        // Verify nodegroups
        assert!(pruned
            .nodegroups
            .iter()
            .any(|ng| ng.nodegroupid == "child1"));
        assert!(!pruned
            .nodegroups
            .iter()
            .any(|ng| ng.nodegroupid == "child2"));

        // Verify edges
        assert!(pruned.edges.iter().any(|e| e.rangenode_id == "child1"));
        assert!(!pruned.edges.iter().any(|e| e.rangenode_id == "child2"));
    }

    #[test]
    fn test_prune_graph_includes_path_to_root() {
        // Create a chain: root -> middle -> leaf
        // If only leaf is permitted, middle should also be included to maintain path
        let root = create_test_node("root", None);
        let middle = create_test_node("middle", Some("middle"));
        let leaf = create_test_node("leaf", Some("leaf"));

        let edge1 = create_test_edge("root", "middle");
        let edge2 = create_test_edge("middle", "leaf");

        let ng_middle = create_test_nodegroup("middle");
        let ng_leaf = create_test_nodegroup("leaf");

        let graph_json = json!({
            "graphid": "test_graph",
            "name": {"en": "Test Graph"},
            "nodes": [root.clone(), middle, leaf],
            "edges": [edge1, edge2],
            "nodegroups": [ng_middle, ng_leaf],
            "root": root,
            "cards": [],
            "cards_x_nodes_x_widgets": [],
            "functions_x_graphs": [],
            "config": {}
        });

        let graph: StaticGraph =
            serde_json::from_value(graph_json).expect("Failed to create graph");

        // Only permit leaf - middle should still be included for path to root
        let permitted = |ng: &str| ng == "leaf";

        let pruned = prune_graph(&graph, permitted, None).expect("Prune failed");

        // All nodes should be included to maintain path
        assert!(pruned.nodes.iter().any(|n| n.nodeid == "root"));
        assert!(
            pruned.nodes.iter().any(|n| n.nodeid == "middle"),
            "middle should be included for path"
        );
        assert!(pruned.nodes.iter().any(|n| n.nodeid == "leaf"));
    }

    #[test]
    fn test_prune_graph_detects_multiple_parents() {
        let root = create_test_node("root", None);
        let child = create_test_node("child", Some("child"));

        // Two edges pointing to same child = multiple parents
        let edge1 = create_test_edge("root", "child");
        let mut edge2 = create_test_edge("root", "child");
        edge2.domainnode_id = "other_parent".to_string();

        let ng = create_test_nodegroup("child");

        let graph_json = json!({
            "graphid": "test_graph",
            "name": {"en": "Test Graph"},
            "nodes": [root.clone(), child],
            "edges": [edge1, edge2],
            "nodegroups": [ng],
            "root": root,
            "cards": [],
            "cards_x_nodes_x_widgets": [],
            "functions_x_graphs": [],
            "config": {}
        });

        let graph: StaticGraph =
            serde_json::from_value(graph_json).expect("Failed to create graph");

        let result = prune_graph(&graph, |_| true, None);
        assert!(matches!(result, Err(PruneError::MultipleParents { .. })));
    }
}