1use std::collections::{BTreeMap, BTreeSet, VecDeque};
17
18use serde_json::Value;
19
20use super::schedule::{foreach_config, Issue, Plan};
21use crate::drone::types::{FlowEdge, FlowNode};
22
23fn is_kind(node: &FlowNode, kind: &str) -> bool {
24 node.data.get("kind").and_then(Value::as_str) == Some(kind)
25}
26
27fn writes_of(node: &FlowNode) -> Vec<(String, Option<String>)> {
29 if !is_kind(node, "variables") {
30 return Vec::new();
31 }
32 let entries = node.data.get("entries").and_then(Value::as_array).cloned().unwrap_or_default();
33 entries
34 .iter()
35 .filter_map(|e| {
36 let name = e.get("name").and_then(Value::as_str)?.to_string();
37 Some((name, e.get("reducer").and_then(Value::as_str).map(str::to_string)))
38 })
39 .collect()
40}
41
42fn sides(n: usize, out: &[Vec<(usize, Option<&str>)>], roots: &[usize], conditions: &[usize]) -> BTreeMap<usize, Vec<Option<bool>>> {
46 let walk = |starts: Vec<usize>, skip: Option<usize>| -> Vec<bool> {
47 let mut seen = vec![false; n];
48 let mut queue: VecDeque<usize> = starts.into_iter().filter(|s| Some(*s) != skip).collect();
49 while let Some(u) = queue.pop_front() {
50 if seen[u] {
51 continue;
52 }
53 seen[u] = true;
54 queue.extend(out[u].iter().map(|(v, _)| *v).filter(|v| Some(*v) != skip && !seen[*v]));
55 }
56 seen
57 };
58 let mut result = BTreeMap::new();
59 for &c in conditions {
60 let target = |handle: &str| out[c].iter().filter(|(_, h)| *h == Some(handle)).map(|(v, _)| *v).collect::<Vec<_>>();
61 let (on_true, on_false) = (walk(target("true"), Some(c)), walk(target("false"), Some(c)));
62 let without_c = walk(roots.to_vec(), Some(c));
63 result.insert(
64 c,
65 (0..n)
66 .map(|x| match (on_true[x], on_false[x], without_c[x]) {
67 (true, false, false) => Some(true),
68 (false, true, false) => Some(false),
69 _ => None,
70 })
71 .collect(),
72 );
73 }
74 result
75}
76
77fn check_declarations(sorted: &[&FlowNode], by_name: &BTreeMap<String, Vec<(usize, Option<String>)>>, reach: &[Vec<bool>], issues: &mut Vec<Issue>) {
82 for (name, writes) in by_name {
83 let reducers: BTreeSet<&str> = writes.iter().filter_map(|(_, r)| r.as_deref()).collect();
84 if reducers.len() > 1 {
85 issues.push(Issue {
86 node: Some(sorted[writes[0].0].id.clone()),
87 message: format!("{name:?} is written with different reducers ({}): a variable has one", reducers.iter().copied().collect::<Vec<_>>().join(", ")),
88 });
89 continue;
90 }
91 let Some(reducer) = reducers.iter().next().copied().filter(|r| *r != "replace") else { continue };
92 let declarers: Vec<usize> = writes.iter().filter(|(_, r)| r.is_some()).map(|(i, _)| *i).collect();
93 for (idx, _) in writes.iter().filter(|(_, r)| r.is_none()) {
94 if !declarers.iter().any(|&d| reach[d][*idx] && !reach[*idx][d]) {
95 issues.push(Issue {
96 node: Some(sorted[*idx].id.clone()),
97 message: format!(
98 "{} writes {name:?} without a reducer and may run before the block that gives it {reducer}: put the reducer on this write too, or run the declaring block first",
99 sorted[*idx].id
100 ),
101 });
102 }
103 }
104 }
105}
106
107pub(super) fn check(sorted: &[&FlowNode], edges: &[(usize, usize, &FlowEdge)], reach: &[Vec<bool>], plan: &Plan, issues: &mut Vec<Issue>) {
108 let n = sorted.len();
109 let owner_of = |idx: usize| -> usize {
111 sorted
112 .iter()
113 .position(|f| is_kind(f, "foreach") && foreach_config(f).is_ok_and(|c| c.body == sorted[idx].id) && plan.owned.contains(&sorted[idx].id))
114 .unwrap_or(idx)
115 };
116 let mut writers: BTreeMap<String, BTreeSet<usize>> = BTreeMap::new();
117 let mut declared: BTreeMap<String, String> = BTreeMap::new();
118 let mut by_name: BTreeMap<String, Vec<(usize, Option<String>)>> = BTreeMap::new();
119 for (idx, node) in sorted.iter().enumerate() {
120 for (name, reducer) in writes_of(node) {
121 if let Some(r) = &reducer {
122 declared.insert(name.clone(), r.clone());
123 }
124 by_name.entry(name.clone()).or_default().push((owner_of(idx), reducer));
125 writers.entry(name).or_default().insert(owner_of(idx));
126 }
127 }
128 let mut out: Vec<Vec<(usize, Option<&str>)>> = vec![Vec::new(); n];
129 let mut has_incoming = vec![false; n];
130 for &(s, t, e) in edges {
131 out[s].push((t, e.source_handle.as_deref()));
132 has_incoming[t] = true;
133 }
134 let roots: Vec<usize> = (0..n).filter(|i| !has_incoming[*i]).collect();
135 let conditions: Vec<usize> = (0..n).filter(|i| is_kind(sorted[*i], "condition") || is_kind(sorted[*i], "once")).collect();
137 let side = sides(n, &out, &roots, &conditions);
138 let exclusive = |a: usize, b: usize| side.values().any(|s| matches!((s[a], s[b]), (Some(x), Some(y)) if x != y));
139
140 check_declarations(sorted, &by_name, reach, issues);
141 for (name, who) in &writers {
142 if declared.get(name).is_some_and(|r| r != "replace") {
143 continue;
144 }
145 let who: Vec<usize> = who.iter().copied().collect();
146 for (i, &a) in who.iter().enumerate() {
147 for &b in &who[i + 1..] {
148 if !reach[a][b] && !reach[b][a] && !exclusive(a, b) {
149 issues.push(Issue {
150 node: Some(sorted[a].id.clone()),
151 message: format!(
152 "{} and {} can run at the same time and both write {name:?}, which replaces: give {name:?} a reducer (append, merge or add) or write it from one block",
153 sorted[a].id, sorted[b].id
154 ),
155 });
156 }
157 }
158 }
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use serde_json::{json, Value};
165
166 use super::super::schedule::analyze;
167 use crate::drone::types::{DroneGraph, FlowEdge, FlowNode, NodePosition};
168
169 fn node(id: &str, data: Value) -> FlowNode {
170 FlowNode { id: id.to_string(), position: NodePosition::default(), data, node_type: None }
171 }
172
173 fn writer(id: &str, var: &str, reducer: Option<&str>) -> FlowNode {
174 let mut entry = json!({ "name": var, "value": id });
175 if let Some(r) = reducer {
176 entry["reducer"] = json!(r);
177 }
178 node(id, json!({ "kind": "variables", "entries": [entry] }))
179 }
180
181 fn edge(id: &str, source: &str, target: &str, handle: Option<&str>) -> FlowEdge {
182 FlowEdge {
183 id: id.to_string(),
184 source: source.to_string(),
185 target: target.to_string(),
186 source_handle: handle.map(str::to_string),
187 target_handle: None,
188 }
189 }
190
191 fn fan_out(a_reducer: Option<&str>, b_reducer: Option<&str>) -> DroneGraph {
193 DroneGraph {
194 nodes: vec![writer("start", "s", None), writer("a", "x", a_reducer), writer("b", "x", b_reducer)],
195 edges: vec![edge("e1", "start", "a", None), edge("e2", "start", "b", None)],
196 }
197 }
198
199 #[test]
200 fn two_branches_that_replace_the_same_variable_are_refused_and_named() {
201 let issues = analyze(&fan_out(None, None)).unwrap_err();
202 assert!(issues.iter().any(|i| i.message.contains("a and b can run at the same time") && i.message.contains("\"x\"")), "{issues:?}");
203 }
204
205 #[test]
206 fn the_same_two_branches_are_fine_when_the_variable_has_a_reducer() {
207 assert!(analyze(&fan_out(Some("append"), Some("append"))).is_ok());
208 assert!(analyze(&fan_out(Some("add"), Some("add"))).is_ok());
209 assert!(analyze(&fan_out(Some("replace"), None)).is_err(), "replace is no reducer");
210 }
211
212 #[test]
213 fn writers_must_agree_on_a_reducer_and_declare_it_first() {
214 let issues = analyze(&fan_out(Some("append"), None)).unwrap_err();
215 assert!(issues.iter().any(|i| i.message.contains("without a reducer")), "{issues:?}");
216 let issues = analyze(&fan_out(Some("append"), Some("add"))).unwrap_err();
217 assert!(issues.iter().any(|i| i.message.contains("different reducers")), "{issues:?}");
218 let row = |first: Option<&str>, second: Option<&str>| DroneGraph {
219 nodes: vec![writer("a", "x", first), writer("b", "x", second)],
220 edges: vec![edge("e1", "a", "b", None)],
221 };
222 assert!(analyze(&row(Some("append"), None)).is_ok(), "declared first");
223 assert!(analyze(&row(None, Some("append"))).is_err(), "the write before the declaration would make it fail");
224 }
225
226 #[test]
227 fn blocks_in_a_row_and_the_two_sides_of_a_condition_may_share_a_variable() {
228 let row = DroneGraph {
229 nodes: vec![writer("a", "x", None), writer("b", "x", None)],
230 edges: vec![edge("e1", "a", "b", None)],
231 };
232 assert!(analyze(&row).is_ok());
233 let sides = DroneGraph {
234 nodes: vec![
235 writer("start", "s", None),
236 node("c", json!({ "kind": "condition", "expr": "1 < 2" })),
237 writer("yes", "x", None),
238 writer("no", "x", None),
239 ],
240 edges: vec![edge("e1", "start", "c", None), edge("e2", "c", "yes", Some("true")), edge("e3", "c", "no", Some("false"))],
241 };
242 assert!(analyze(&sides).is_ok(), "only one side runs");
243 }
244
245 #[test]
246 fn the_first_run_and_the_seen_sides_of_a_once_may_share_a_variable_too() {
247 let g = DroneGraph {
248 nodes: vec![
249 writer("start", "s", None),
250 node("once", json!({ "kind": "once", "key": "release-1" })),
251 writer("first", "x", None),
252 writer("seen", "x", None),
253 ],
254 edges: vec![edge("e1", "start", "once", None), edge("e2", "once", "first", Some("true")), edge("e3", "once", "seen", Some("false"))],
255 };
256 assert!(analyze(&g).is_ok(), "only one side of a Once runs");
257 }
258
259 #[test]
260 fn a_branch_that_skips_the_condition_can_still_race_with_a_side() {
261 let g = DroneGraph {
263 nodes: vec![
264 writer("start", "s", None),
265 node("c", json!({ "kind": "condition", "expr": "1 < 2" })),
266 writer("yes", "x", None),
267 writer("no", "x", None),
268 ],
269 edges: vec![
270 edge("e1", "start", "c", None),
271 edge("e2", "c", "yes", Some("true")),
272 edge("e3", "c", "no", Some("false")),
273 edge("e4", "start", "yes", None),
274 ],
275 };
276 assert!(analyze(&g).is_err());
277 }
278
279 #[test]
280 fn a_for_each_body_counts_as_its_for_each() {
281 let g = DroneGraph {
283 nodes: vec![
284 writer("start", "s", None),
285 node("each", json!({ "kind": "foreach", "items": "{{trigger.l}}", "body": "work" })),
286 writer("work", "x", None),
287 writer("other", "x", None),
288 ],
289 edges: vec![edge("e1", "start", "each", None), edge("e2", "start", "other", None)],
290 };
291 let issues = analyze(&g).unwrap_err();
292 assert!(issues.iter().any(|i| i.message.contains("each and other")), "{issues:?}");
293 }
294}