feldera_ir/
lib.rs

1//! Library to parse and compare Feldera SQL dataflow graphs.
2
3use std::collections::{HashMap, HashSet};
4
5use serde::{Deserialize, Serialize};
6
7mod hir;
8mod lir;
9mod mir;
10
11pub use hir::{CalciteId, CalcitePlan};
12pub use lir::{LirCircuit, LirEdge, LirNode, LirNodeId, LirStreamId};
13pub use mir::{MirInput, MirNode, MirNodeId};
14
15/// Indicates what relations (views and tables) of a dataflow graph
16/// are different when compared with another dataflow graph.
17#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Hash)]
18pub enum Changes {
19    Added(String),
20    Removed(String),
21    Modified(String),
22}
23
24/// The JSON representation of a dataflow graph.
25#[derive(Debug, Deserialize)]
26pub struct Dataflow {
27    pub calcite_plan: HashMap<String, CalcitePlan>,
28    pub mir: HashMap<MirNodeId, MirNode>,
29}
30
31impl Dataflow {
32    /// Reports the changes to relations (views and tables) of a dataflow graph when
33    /// compared with another (newer/updated) dataflow graph.
34    ///
35    /// If the returned set is empty, the relations are unchanged and the dataflows
36    /// are (should be) identical.
37    pub fn diff(&self, other: &Dataflow) -> HashSet<Changes> {
38        let mut changes = HashSet::new();
39        let relation_hashes = self.ids_to_hashes(&self.relation_with_ids());
40        let other_relation_hashes = other.ids_to_hashes(&other.relation_with_ids());
41
42        for (relation, hashes) in relation_hashes.iter() {
43            if let Some(other_hashes) = other_relation_hashes.get(relation) {
44                if hashes != other_hashes {
45                    changes.insert(Changes::Modified(relation.clone()));
46                }
47            } else {
48                changes.insert(Changes::Removed(relation.clone()));
49            }
50        }
51
52        for (relation, _hashes) in other_relation_hashes {
53            if !relation_hashes.contains_key(&relation) {
54                changes.insert(Changes::Added(relation));
55            }
56        }
57
58        changes
59    }
60
61    /// Walks the calcite plan and returns a set of relations with their calcite node IDs
62    /// they're dependent on.
63    fn relation_with_ids(&self) -> HashMap<String, HashSet<usize>> {
64        let mut relations_and_ids: HashMap<String, HashSet<usize>> = HashMap::new();
65        for (key, cp) in self.calcite_plan.iter() {
66            for rel in &cp.rels {
67                relations_and_ids
68                    .entry(key.clone())
69                    .or_default()
70                    .insert(rel.id);
71            }
72        }
73
74        relations_and_ids
75    }
76
77    /// Given a set of relations and their associated IDs, returns a map of
78    /// relation names to their corresponding persistent hashes.
79    fn ids_to_hashes(
80        &self,
81        relations_and_ids: &HashMap<String, HashSet<usize>>,
82    ) -> HashMap<String, HashSet<String>> {
83        let mut hashes = HashMap::new();
84        for node in self.mir.values() {
85            let all_calcite_ids: Vec<usize> = node
86                .calcite
87                .as_ref()
88                .map(|cid| cid.clone().into())
89                .unwrap_or_default();
90            let mut all_calcite_ids_of_node = HashSet::with_capacity(all_calcite_ids.len());
91            for id in all_calcite_ids {
92                all_calcite_ids_of_node.insert(id);
93            }
94
95            // Tables (unused ones) don't show up in calcite plan so we find them in the MIR
96            // first
97            if let Some(table) = node.table.as_ref() {
98                if let Some(persistent_id) = &node.persistent_id {
99                    hashes
100                        .entry(table.clone())
101                        .or_insert_with(HashSet::new)
102                        .insert(persistent_id.clone());
103                }
104            }
105
106            for (key, ids) in relations_and_ids {
107                let node_is_dependency_for_relation = !ids.is_disjoint(&all_calcite_ids_of_node);
108                if node_is_dependency_for_relation {
109                    if let Some(persistent_id) = &node.persistent_id {
110                        hashes
111                            .entry(key.clone())
112                            .or_insert_with(HashSet::new)
113                            .insert(persistent_id.clone());
114                    }
115                }
116            }
117        }
118        hashes
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use crate::*;
125    use std::collections::HashSet;
126
127    const SAMPLE_A: (&str, &str) = ("sample_a", include_str!("../test/sample_a.json"));
128    const SAMPLE_B: (&str, &str) = ("sample_b", include_str!("../test/sample_b.json"));
129    const SAMPLE_B_MOD1: (&str, &str) =
130        ("sample_b_mod1", include_str!("../test/sample_b_mod1.json"));
131    const SAMPLE_B_MOD2: (&str, &str) =
132        ("sample_b_mod2", include_str!("../test/sample_b_mod2.json"));
133    const SAMPLE_B_MOD3: (&str, &str) =
134        ("sample_b_mod3", include_str!("../test/sample_b_mod3.json"));
135    const SAMPLE_C: (&str, &str) = ("sample_c", include_str!("../test/sample_c.json"));
136    const SAMPLES: &[(&str, &str)] = &[
137        SAMPLE_A,
138        SAMPLE_B,
139        SAMPLE_B_MOD1,
140        SAMPLE_B_MOD2,
141        SAMPLE_B_MOD3,
142        SAMPLE_C,
143    ];
144
145    #[test]
146    fn can_parse_ir() {
147        for (_name, json) in SAMPLES.iter() {
148            //eprintln!("Parsing: {}", _name);
149            let _plan: Dataflow = serde_json::from_str(json).unwrap();
150            //eprintln!("{:#?}", _plan);
151        }
152    }
153
154    #[test]
155    fn can_get_relations_and_ids() {
156        let plan: Dataflow = serde_json::from_str(SAMPLE_B.1).unwrap();
157        let relations = plan.relation_with_ids();
158        assert_eq!(relations["error_view"], HashSet::from([0]));
159
160        let plan: Dataflow = serde_json::from_str(SAMPLE_A.1).unwrap();
161        let relations = plan.relation_with_ids();
162        assert_eq!(relations["error_view"], HashSet::from([0]));
163        assert_eq!(
164            relations["group_can_read"],
165            HashSet::from([1, 2, 3, 4, 5, 6, 7])
166        );
167        assert_eq!(
168            relations["group_can_write"],
169            HashSet::from([8, 9, 10, 11, 12, 13])
170        );
171        assert_eq!(
172            relations["user_can_read"],
173            HashSet::from([14, 15, 16, 17, 18, 19, 20, 21])
174        );
175        assert_eq!(
176            relations["user_can_write"],
177            HashSet::from([22, 23, 24, 25, 26, 27, 28, 29])
178        );
179    }
180
181    #[test]
182    fn can_find_hashes_in_a() {
183        let plan: Dataflow = serde_json::from_str(SAMPLE_A.1).unwrap();
184        let relations = plan.relation_with_ids();
185        let hashes = plan.ids_to_hashes(&relations);
186
187        assert_eq!(
188            hashes["error_view"],
189            HashSet::from([
190                "8b384059bdb44ad811ab341cc5e2a59697f39aac7b463cab027b185db8105e73".to_string(),
191                "933ebf782e1fe804fe85c4d0f3688bdb5234b386c2834892776e692acd9781d9".to_string()
192            ])
193        );
194
195        assert_eq!(
196            hashes["group_file_viewer"],
197            HashSet::from([
198                "44b862944cb9ff1772f75112d6b74d87bcbbe770502fe47f91b07c0bb3987bb3".to_string()
199            ])
200        );
201
202        assert_eq!(
203            hashes["user_can_write"],
204            HashSet::from([
205                "2f90ee4cdb4895d44ac7efb7104402dcf39a5fcfbe90492cc95311d4c70f623e".to_string(),
206                "db1532ae31ea981721261c4a3892a6f373f98ecce41c59b2b8a5f5186c3c7d69".to_string(),
207                "53944e28b6a21187dccb34ee9859bddbb4266157b21541feb2e4166a4034e907".to_string(),
208                "61a52a49c5285c66a9656f211205002d48bd282b9f7f48be666f7fe7c208a338".to_string(),
209                "739c3d0dafe5c2f650824df3529602ddae8acfa8789b35d80ea3eb7c3b156796".to_string(),
210                "e989408d6aaecac2943caac41fdab83aca539622526b4289303c6a4de6eb658f".to_string(),
211                "71d57c70dd7a5e3ae6da1adc565f9c119f93d4dcd50c61573a117d5d9aac3389".to_string(),
212                "a8918a1fd4c90f6091dade7d6a44d46bb72809da98262781240ca1be5d738271".to_string(),
213                "94b255b29c463d2918fe4a8c23cc75e943cb10e486d21942c8cb8c124c31eb7f".to_string(),
214            ])
215        );
216    }
217
218    #[test]
219    fn unchanged_diff_is_empty() {
220        for (_name, json) in SAMPLES.iter() {
221            let plan: Dataflow = serde_json::from_str(json).unwrap();
222            assert!(plan.diff(&plan).is_empty());
223        }
224    }
225
226    fn diff(json1: &str, json2: &str) -> HashSet<Changes> {
227        let plan1: Dataflow = serde_json::from_str(json1).unwrap();
228        let plan2: Dataflow = serde_json::from_str(json2).unwrap();
229        plan1.diff(&plan2)
230    }
231
232    #[test]
233    fn change_only_view() {
234        let diff = diff(SAMPLE_B.1, SAMPLE_B_MOD1.1);
235        assert_eq!(
236            diff,
237            HashSet::from([Changes::Modified("example_count".to_string())])
238        );
239    }
240
241    #[test]
242    fn change_table() {
243        let diff = diff(SAMPLE_B.1, SAMPLE_B_MOD2.1);
244        assert_eq!(
245            diff,
246            HashSet::from([
247                Changes::Modified("example".to_string()),
248                Changes::Modified("example_count".to_string())
249            ])
250        );
251    }
252
253    #[test]
254    fn add_table() {
255        let diff = diff(SAMPLE_B.1, SAMPLE_B_MOD3.1);
256        assert_eq!(
257            diff,
258            HashSet::from([
259                // tables that aren't used by any views currently don't appear in the graph
260                Changes::Added("example_new".to_string()),
261                Changes::Added("example_view_count".to_string())
262            ])
263        );
264    }
265
266    #[test]
267    fn remove_table() {
268        let diff = diff(SAMPLE_B_MOD3.1, SAMPLE_B.1);
269        assert_eq!(
270            diff,
271            HashSet::from([
272                Changes::Removed("example_new".to_string()),
273                Changes::Removed("example_view_count".to_string())
274            ])
275        );
276    }
277}