1use std::collections::{BTreeMap, HashMap};
2use std::ops::Range;
3
4use serde_json::Value;
5
6use crate::types::{ArgValue, ParsedOp};
7
8#[cfg(test)]
9use crate::types::{DslError, ExecutionMode, ParsedRequest};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct UnitKeyConflict {
16 pub key: String,
17 pub leaf: usize,
18 pub other_unit: usize,
19 pub other_leaf: usize,
20}
21
22pub fn unit_write_key_conflicts(
33 ops: &[ParsedOp],
34 ranges: &[Range<usize>],
35) -> BTreeMap<usize, Vec<UnitKeyConflict>> {
36 let mut per_unit_keys: Vec<HashMap<String, usize>> = Vec::with_capacity(ranges.len());
41 for range in ranges {
42 let mut keys: HashMap<String, usize> = HashMap::new();
43 for leaf in range.clone() {
44 for key in write_keys_for_op_pub(&ops[leaf]) {
45 keys.entry(key).or_insert(leaf);
46 }
47 }
48 per_unit_keys.push(keys);
49 }
50
51 let mut first_claim: HashMap<String, (usize, usize)> = HashMap::new();
52 let mut conflicts: BTreeMap<usize, Vec<UnitKeyConflict>> = BTreeMap::new();
53 for (unit_index, keys) in per_unit_keys.iter().enumerate() {
54 for (key, &leaf) in keys {
55 match first_claim.get(key) {
56 Some(&(other_unit, other_leaf)) if other_unit != unit_index => {
57 conflicts
58 .entry(unit_index)
59 .or_default()
60 .push(UnitKeyConflict {
61 key: key.clone(),
62 leaf,
63 other_unit,
64 other_leaf,
65 });
66 conflicts
67 .entry(other_unit)
68 .or_default()
69 .push(UnitKeyConflict {
70 key: key.clone(),
71 leaf: other_leaf,
72 other_unit: unit_index,
73 other_leaf: leaf,
74 });
75 }
76 Some(_) => {}
77 None => {
78 first_claim.insert(key.clone(), (unit_index, leaf));
79 }
80 }
81 }
82 }
83 for entries in conflicts.values_mut() {
84 entries.sort_by_key(|c| (c.leaf, c.other_leaf));
85 entries.dedup();
86 }
87 conflicts
88}
89
90pub fn write_keys_for_op_pub(op: &ParsedOp) -> Vec<String> {
96 let mut keys = Vec::new();
97 match op.tool.as_str() {
98 "update" | "delete" => {
99 if let Some(ArgValue::Value(Value::String(s))) = op.args.get("id") {
100 keys.push(format!("entity:{s}"));
101 }
102 }
103 "merge" => {
104 let previews_without_writing = matches!(
110 op.args.get("dry_run"),
111 Some(ArgValue::Value(Value::Bool(true)))
112 );
113 if !previews_without_writing {
114 for name in &["into_id", "from_id"] {
115 if let Some(ArgValue::Value(Value::String(s))) = op.args.get(*name) {
116 keys.push(format!("entity:{s}"));
117 }
118 }
119 }
120 }
121 "link" => {
122 let link_arg = |canonical: &str, alias: &str| {
130 op.args.get(canonical).or_else(|| op.args.get(alias))
131 };
132 if let (
133 Some(ArgValue::Value(Value::String(s))),
134 Some(ArgValue::Value(Value::String(t))),
135 Some(ArgValue::Value(Value::String(r))),
136 ) = (
137 link_arg("source_id", "source"),
138 link_arg("target_id", "target"),
139 link_arg("relation", "kind"),
140 ) {
141 push_link_key(&mut keys, s, t, r);
142 }
143
144 if let Some(ArgValue::Value(Value::Array(links))) = op.args.get("links") {
146 for link in links {
147 let Some(obj) = link.as_object() else {
148 continue;
149 };
150 let (Some(s), Some(t), Some(r)) = (
151 obj.get("source_id").and_then(Value::as_str),
152 obj.get("target_id").and_then(Value::as_str),
153 obj.get("relation").and_then(Value::as_str),
154 ) else {
155 continue;
156 };
157 push_link_key(&mut keys, s, t, r);
158 }
159 }
160 }
161 _ => {}
162 }
163 keys
164}
165
166fn push_link_key(keys: &mut Vec<String>, source: &str, target: &str, relation: &str) {
168 let relation_key = canonical_relation_key(relation);
169 let (source_key, target_key) = if is_static_symmetric_relation(&relation_key) && target < source
170 {
171 (target, source)
172 } else {
173 (source, target)
174 };
175 keys.push(format!(
176 "edge-natural:{source_key}:{target_key}:{relation_key}"
177 ));
178}
179
180fn canonical_relation_key(relation: &str) -> String {
182 let normalized: String = relation
183 .chars()
184 .map(|c| {
185 if c == '-' {
186 '_'
187 } else {
188 c.to_ascii_lowercase()
189 }
190 })
191 .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
192 .collect();
193 match normalized.as_str() {
194 "competeswith" => "competes_with".to_string(),
195 "composedwith" => "composed_with".to_string(),
196 _ => normalized,
197 }
198}
199
200fn is_static_symmetric_relation(relation: &str) -> bool {
202 matches!(relation, "competes_with" | "composed_with")
203}
204
205#[cfg(test)]
207pub(crate) fn check_write_key_conflicts(req: &ParsedRequest) -> Result<(), DslError> {
208 if req.mode == ExecutionMode::Chain {
209 return Ok(());
210 }
211 let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
212 for op in &req.ops {
213 let keys = write_keys_for_op_pub(op);
214 for key in keys {
215 if let Some(first) = seen.get(&key) {
216 return Err(DslError::WriteKeyConflict {
217 id: key,
218 first_op: first.clone(),
219 second_op: op.tool.clone(),
220 });
221 }
222 seen.insert(key, op.tool.clone());
223 }
224 }
225 Ok(())
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231 use crate::parse_request;
232
233 #[test]
234 fn no_conflict_on_non_write_ops() {
235 let r =
236 parse_request(r#"[list(kind="entity"), search(kind="entity", query="x")]"#).unwrap();
237 check_write_key_conflicts(&r).unwrap();
238 }
239
240 #[test]
241 fn update_and_delete_same_id_conflict() {
242 let r =
243 parse_request(r#"[update(id="abc-123", name="new"), delete(id="abc-123")]"#).unwrap();
244 let err = check_write_key_conflicts(&r).unwrap_err();
245 assert!(
246 matches!(&err, DslError::WriteKeyConflict { id, first_op, second_op }
247 if id == "entity:abc-123" && first_op == "update" && second_op == "delete"),
248 "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
249 );
250 }
251
252 #[test]
253 fn two_updates_same_id_conflict() {
254 let r = parse_request(
255 r#"[update(id="uuid-1", name="a"), update(id="uuid-1", description="b")]"#,
256 )
257 .unwrap();
258 let err = check_write_key_conflicts(&r).unwrap_err();
259 assert!(
260 matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:uuid-1"),
261 "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
262 );
263 }
264
265 #[test]
266 fn merge_from_id_conflicts_with_delete() {
267 let r =
268 parse_request(r#"[merge(into_id="new-id", from_id="old-id"), delete(id="old-id")]"#)
269 .unwrap();
270 let err = check_write_key_conflicts(&r).unwrap_err();
271 assert!(
272 matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
273 "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
274 );
275 }
276
277 #[test]
278 fn two_dry_run_merges_in_one_batch_do_not_conflict() {
279 let r = parse_request(
282 r#"[merge(into_id="a-id", from_id="b-id", dry_run=true), merge(into_id="a-id", from_id="b-id", dry_run=true)]"#,
283 )
284 .unwrap();
285 check_write_key_conflicts(&r).unwrap();
286 }
287
288 #[test]
289 fn a_dry_run_merge_does_not_conflict_with_a_delete_of_its_from_id() {
290 let r = parse_request(
293 r#"[merge(into_id="new-id", from_id="old-id", dry_run=true), delete(id="old-id")]"#,
294 )
295 .unwrap();
296 check_write_key_conflicts(&r).unwrap();
297 }
298
299 #[test]
300 fn dry_run_false_keeps_the_merge_keys() {
301 let r = parse_request(
302 r#"[merge(into_id="new-id", from_id="old-id", dry_run=false), delete(id="old-id")]"#,
303 )
304 .unwrap();
305 let err = check_write_key_conflicts(&r).unwrap_err();
306 assert!(
307 matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
308 "a merge that writes must keep its keys, got {err:?}"
309 );
310 }
311
312 #[test]
313 fn a_non_boolean_dry_run_keeps_the_merge_keys() {
314 let r = parse_request(
317 r#"[merge(into_id="new-id", from_id="old-id", dry_run="true"), delete(id="old-id")]"#,
318 )
319 .unwrap();
320 let err = check_write_key_conflicts(&r).unwrap_err();
321 assert!(
322 matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
323 "a non-boolean dry_run must stay conservative, got {err:?}"
324 );
325 }
326
327 #[test]
328 fn different_ids_no_conflict() {
329 let r = parse_request(
330 r#"[update(id="id-1", name="a"), delete(id="id-2"), update(id="id-3", name="c")]"#,
331 )
332 .unwrap();
333 check_write_key_conflicts(&r).unwrap();
334 }
335
336 #[test]
337 fn chain_mode_skips_conflict_detection() {
338 let r = parse_request(r#"update(id="same-id", name="a") | delete(id="same-id")"#).unwrap();
339 assert_eq!(r.mode, ExecutionMode::Chain);
340 check_write_key_conflicts(&r).unwrap();
341 }
342
343 #[test]
344 fn link_source_id_does_not_conflict_with_entity_update() {
345 let r = parse_request(
346 r#"[update(id="node-1", name="x"), link(source_id="node-1", target_id="node-2", relation="extends")]"#,
347 )
348 .unwrap();
349 check_write_key_conflicts(&r).unwrap();
350 }
351
352 #[test]
353 fn two_links_same_natural_key_conflict() {
354 let r = parse_request(
355 r#"[link(source_id="a", target_id="b", relation="extends"), link(source_id="a", target_id="b", relation="extends")]"#,
356 )
357 .unwrap();
358 let err = check_write_key_conflicts(&r).unwrap_err();
359 assert!(
360 matches!(&err, DslError::WriteKeyConflict { id, .. }
361 if id == "edge-natural:a:b:extends"),
362 "expected WriteKeyConflict on edge-natural key, got {err:?}"
363 );
364 }
365
366 #[test]
367 fn mixed_spelling_links_to_one_edge_conflict_like_the_canonical_spelling() {
368 for ops in [
372 r#"[link(source_id="a", target_id="b", relation="extends", weight=0.1), link(source_id="a", target_id="b", relation="extends", weight=0.9)]"#,
373 r#"[link(source_id="a", target_id="b", relation="extends", weight=0.1), link(source="a", target="b", kind="extends", weight=0.9)]"#,
374 r#"[link(source="a", target="b", kind="extends", weight=0.1), link(source_id="a", target_id="b", relation="extends", weight=0.9)]"#,
375 ] {
376 let r = parse_request(ops).unwrap();
377 let err = check_write_key_conflicts(&r).unwrap_err();
378 assert!(
379 matches!(&err, DslError::WriteKeyConflict { id, first_op, second_op }
380 if id == "edge-natural:a:b:extends"
381 && first_op == "link"
382 && second_op == "link"),
383 "{ops} must conflict on the edge key, got {err:?}"
384 );
385 }
386 }
387
388 #[test]
389 fn aliased_only_links_to_one_edge_conflict() {
390 let r = parse_request(
391 r#"[link(source="a", target="b", kind="extends"), link(source="a", target="b", kind="extends")]"#,
392 )
393 .unwrap();
394 let err = check_write_key_conflicts(&r).unwrap_err();
395 assert!(
396 matches!(&err, DslError::WriteKeyConflict { id, .. }
397 if id == "edge-natural:a:b:extends"),
398 "expected WriteKeyConflict on edge-natural key, got {err:?}"
399 );
400 }
401
402 #[test]
403 fn each_link_field_reads_its_own_alias_into_the_canonical_key() {
404 for ops in [
407 r#"link(source="a", target="b", kind="extends")"#,
408 r#"link(source="a", target_id="b", relation="extends")"#,
409 r#"link(source_id="a", target="b", relation="extends")"#,
410 r#"link(source_id="a", target_id="b", kind="extends")"#,
411 ] {
412 let r = parse_request(ops).unwrap();
413 assert_eq!(
414 write_keys_for_op_pub(&r.ops[0]),
415 vec!["edge-natural:a:b:extends".to_string()],
416 "{ops}"
417 );
418 }
419 }
420
421 #[test]
422 fn single_write_op_no_conflict() {
423 let r = parse_request(r#"delete(id="solo-id")"#).unwrap();
424 assert_eq!(r.mode, ExecutionMode::Single);
425 check_write_key_conflicts(&r).unwrap();
426 }
427
428 #[test]
429 fn bulk_link_and_singleton_same_natural_key_conflict() {
430 let r = parse_request(
431 r#"[link(links=[{"source_id":"a","target_id":"b","relation":"extends","weight":0.1}]), link(source_id="a", target_id="b", relation="extends", weight=0.9)]"#,
432 )
433 .unwrap();
434 let err = check_write_key_conflicts(&r).unwrap_err();
435 assert!(
436 matches!(&err, DslError::WriteKeyConflict { id, .. }
437 if id == "edge-natural:a:b:extends"),
438 "expected WriteKeyConflict on edge-natural key, got {err:?}"
439 );
440 }
441
442 #[test]
443 fn reversed_symmetric_links_conflict() {
444 let r = parse_request(
445 r#"[link(source_id="b", target_id="a", relation="competes_with"), link(source_id="a", target_id="b", relation="competes_with")]"#,
446 )
447 .unwrap();
448 let err = check_write_key_conflicts(&r).unwrap_err();
449 assert!(
450 matches!(&err, DslError::WriteKeyConflict { id, .. }
451 if id == "edge-natural:a:b:competes_with"),
452 "expected WriteKeyConflict on canonicalized symmetric key, got {err:?}"
453 );
454 }
455
456 #[test]
457 fn reversed_non_symmetric_links_do_not_conflict() {
458 let r = parse_request(
459 r#"[link(source_id="b", target_id="a", relation="extends"), link(source_id="a", target_id="b", relation="extends")]"#,
460 )
461 .unwrap();
462 check_write_key_conflicts(&r).unwrap();
463 }
464
465 #[test]
466 fn write_keys_for_op_pub_bulk_link_extracts_all_edges() {
467 let r = parse_request(
468 r#"link(links=[{"source_id":"a","target_id":"b","relation":"extends"},{"source_id":"c","target_id":"d","relation":"extends"}])"#,
469 )
470 .unwrap();
471 let keys = write_keys_for_op_pub(&r.ops[0]);
472 assert_eq!(
473 keys,
474 vec![
475 "edge-natural:a:b:extends".to_string(),
476 "edge-natural:c:d:extends".to_string(),
477 ]
478 );
479 }
480
481 #[test]
482 fn unit_conflict_refuses_both_units_sharing_a_key() {
483 let r = parse_request(
484 r#"[update(id="x", name="1") | update(id="y", name="2"), update(id="x", name="3")]"#,
485 )
486 .unwrap();
487 assert_eq!(r.ranges, vec![0..2, 2..3]);
488 let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
489 assert_eq!(
490 conflicts.len(),
491 2,
492 "both units must be named: {conflicts:?}"
493 );
494 assert_eq!(
495 conflicts[&0],
496 vec![UnitKeyConflict {
497 key: "entity:x".to_string(),
498 leaf: 0,
499 other_unit: 1,
500 other_leaf: 2,
501 }]
502 );
503 assert_eq!(
504 conflicts[&1],
505 vec![UnitKeyConflict {
506 key: "entity:x".to_string(),
507 leaf: 2,
508 other_unit: 0,
509 other_leaf: 0,
510 }]
511 );
512 }
513
514 #[test]
515 fn same_key_repeated_within_one_unit_is_not_reported() {
516 let r = parse_request(r#"[update(id="x", name="1") | update(id="x", name="2")]"#).unwrap();
517 assert_eq!(r.ranges.len(), 1);
518 assert_eq!(r.ranges[0], 0..2);
519 let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
520 assert!(
521 conflicts.is_empty(),
522 "a chain's own ordered leaves must not conflict with each other: {conflicts:?}"
523 );
524 }
525
526 #[test]
527 fn disjoint_units_share_no_conflict() {
528 let r = parse_request(r#"[update(id="x", name="1"), update(id="y", name="2")]"#).unwrap();
529 assert_eq!(r.ranges, vec![0..1, 1..2]);
530 assert!(unit_write_key_conflicts(&r.ops, &r.ranges).is_empty());
531 }
532
533 #[test]
534 fn three_way_unit_conflict_names_every_affected_unit() {
535 let r = parse_request(
536 r#"[update(id="x", name="1"), update(id="x", name="2"), update(id="x", name="3")]"#,
537 )
538 .unwrap();
539 let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
540 assert_eq!(conflicts.len(), 3, "{conflicts:?}");
541 }
542}