Skip to main content

khive_request/
conflict.rs

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/// One cross-unit static write-key conflict: `leaf` (inside the unit this
12/// entry is filed under) claims the same statically knowable write key as
13/// `other_leaf`, which belongs to a *different* unit, `other_unit`.
14#[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
22/// Finds every statically knowable write-key collision between *different*
23/// units of a bracketed batch of chains (ADR-016 Amendment 2).
24///
25/// A key repeated by two leaves of the *same* unit is legal, because a chain's own
26/// leaves are already ordered, and is never reported. A key claimed by leaves
27/// in two different units is reported once per affected unit (symmetric:
28/// both units get an entry), each naming the other unit's conflicting global
29/// leaf position, so a caller can refuse both units before any of their
30/// leaves dispatch. Units absent from the returned map share no cross-unit
31/// key with any other unit.
32pub fn unit_write_key_conflicts(
33    ops: &[ParsedOp],
34    ranges: &[Range<usize>],
35) -> BTreeMap<usize, Vec<UnitKeyConflict>> {
36    // Per unit, collapse repeated in-unit keys to their first-occurring leaf
37    // (deterministic: ranges are walked in leaf order regardless of the
38    // arbitrary hash order `write_keys_for_op_pub` or a later `HashMap`
39    // iteration might otherwise introduce).
40    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
90/// Extracts statically knowable, substrate-prefixed write-conflict keys for `op`.
91///
92/// Missing, dynamic, or non-string targets contribute no key. The result order
93/// follows the tool's argument/entry order.
94/// See `crates/khive-request/docs/api/write-conflicts.md` for key formats.
95pub 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            // A dry-run merge reads the pair and returns a prediction, so it targets
105            // no stored record and declares no key. Only a literal `true` reads as a
106            // preview: absent, `false` and a non-boolean value keep the keys, on the
107            // same static-knowability rule the rest of this builder follows, so an
108            // argument this cannot read as a preview stays conservative.
109            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            // Edge keys must not collide with their endpoint entities.
123            if let (
124                Some(ArgValue::Value(Value::String(s))),
125                Some(ArgValue::Value(Value::String(t))),
126                Some(ArgValue::Value(Value::String(r))),
127            ) = (
128                op.args.get("source_id"),
129                op.args.get("target_id"),
130                op.args.get("relation"),
131            ) {
132                push_link_key(&mut keys, s, t, r);
133            }
134
135            // Bulk and singleton links share natural keys so equivalent writes collide.
136            if let Some(ArgValue::Value(Value::Array(links))) = op.args.get("links") {
137                for link in links {
138                    let Some(obj) = link.as_object() else {
139                        continue;
140                    };
141                    let (Some(s), Some(t), Some(r)) = (
142                        obj.get("source_id").and_then(Value::as_str),
143                        obj.get("target_id").and_then(Value::as_str),
144                        obj.get("relation").and_then(Value::as_str),
145                    ) else {
146                        continue;
147                    };
148                    push_link_key(&mut keys, s, t, r);
149                }
150            }
151        }
152        _ => {}
153    }
154    keys
155}
156
157/// Adds a natural edge key, ordering endpoints for known symmetric relations.
158fn push_link_key(keys: &mut Vec<String>, source: &str, target: &str, relation: &str) {
159    let relation_key = canonical_relation_key(relation);
160    let (source_key, target_key) = if is_static_symmetric_relation(&relation_key) && target < source
161    {
162        (target, source)
163    } else {
164        (source, target)
165    };
166    keys.push(format!(
167        "edge-natural:{source_key}:{target_key}:{relation_key}"
168    ));
169}
170
171/// Normalizes relation spelling without adding a `khive-types` dependency.
172fn canonical_relation_key(relation: &str) -> String {
173    let normalized: String = relation
174        .chars()
175        .map(|c| {
176            if c == '-' {
177                '_'
178            } else {
179                c.to_ascii_lowercase()
180            }
181        })
182        .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
183        .collect();
184    match normalized.as_str() {
185        "competeswith" => "competes_with".to_string(),
186        "composedwith" => "composed_with".to_string(),
187        _ => normalized,
188    }
189}
190
191/// Returns whether the deliberately conservative local relation set is symmetric.
192fn is_static_symmetric_relation(relation: &str) -> bool {
193    matches!(relation, "competes_with" | "composed_with")
194}
195
196/// Scans a parsed batch for duplicate write keys; ordered chains are exempt.
197#[cfg(test)]
198pub(crate) fn check_write_key_conflicts(req: &ParsedRequest) -> Result<(), DslError> {
199    if req.mode == ExecutionMode::Chain {
200        return Ok(());
201    }
202    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
203    for op in &req.ops {
204        let keys = write_keys_for_op_pub(op);
205        for key in keys {
206            if let Some(first) = seen.get(&key) {
207                return Err(DslError::WriteKeyConflict {
208                    id: key,
209                    first_op: first.clone(),
210                    second_op: op.tool.clone(),
211                });
212            }
213            seen.insert(key, op.tool.clone());
214        }
215    }
216    Ok(())
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::parse_request;
223
224    #[test]
225    fn no_conflict_on_non_write_ops() {
226        let r =
227            parse_request(r#"[list(kind="entity"), search(kind="entity", query="x")]"#).unwrap();
228        check_write_key_conflicts(&r).unwrap();
229    }
230
231    #[test]
232    fn update_and_delete_same_id_conflict() {
233        let r =
234            parse_request(r#"[update(id="abc-123", name="new"), delete(id="abc-123")]"#).unwrap();
235        let err = check_write_key_conflicts(&r).unwrap_err();
236        assert!(
237            matches!(&err, DslError::WriteKeyConflict { id, first_op, second_op }
238                if id == "entity:abc-123" && first_op == "update" && second_op == "delete"),
239            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
240        );
241    }
242
243    #[test]
244    fn two_updates_same_id_conflict() {
245        let r = parse_request(
246            r#"[update(id="uuid-1", name="a"), update(id="uuid-1", description="b")]"#,
247        )
248        .unwrap();
249        let err = check_write_key_conflicts(&r).unwrap_err();
250        assert!(
251            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:uuid-1"),
252            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
253        );
254    }
255
256    #[test]
257    fn merge_from_id_conflicts_with_delete() {
258        let r =
259            parse_request(r#"[merge(into_id="new-id", from_id="old-id"), delete(id="old-id")]"#)
260                .unwrap();
261        let err = check_write_key_conflicts(&r).unwrap_err();
262        assert!(
263            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
264            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
265        );
266    }
267
268    #[test]
269    fn two_dry_run_merges_in_one_batch_do_not_conflict() {
270        // The refusal this closes: two previews over the same pair were rejected as
271        // overlapping writes and had to be issued as sequential singleton calls.
272        let r = parse_request(
273            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)]"#,
274        )
275        .unwrap();
276        check_write_key_conflicts(&r).unwrap();
277    }
278
279    #[test]
280    fn a_dry_run_merge_does_not_conflict_with_a_delete_of_its_from_id() {
281        // The same pair as merge_from_id_conflicts_with_delete above, which is the
282        // control: the only difference between the two cases is the preview flag.
283        let r = parse_request(
284            r#"[merge(into_id="new-id", from_id="old-id", dry_run=true), delete(id="old-id")]"#,
285        )
286        .unwrap();
287        check_write_key_conflicts(&r).unwrap();
288    }
289
290    #[test]
291    fn dry_run_false_keeps_the_merge_keys() {
292        let r = parse_request(
293            r#"[merge(into_id="new-id", from_id="old-id", dry_run=false), delete(id="old-id")]"#,
294        )
295        .unwrap();
296        let err = check_write_key_conflicts(&r).unwrap_err();
297        assert!(
298            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
299            "a merge that writes must keep its keys, got {err:?}"
300        );
301    }
302
303    #[test]
304    fn a_non_boolean_dry_run_keeps_the_merge_keys() {
305        // A string is not the preview the handler acts on, so reading it as one here
306        // would drop the keys of an op that goes on to write.
307        let r = parse_request(
308            r#"[merge(into_id="new-id", from_id="old-id", dry_run="true"), delete(id="old-id")]"#,
309        )
310        .unwrap();
311        let err = check_write_key_conflicts(&r).unwrap_err();
312        assert!(
313            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
314            "a non-boolean dry_run must stay conservative, got {err:?}"
315        );
316    }
317
318    #[test]
319    fn different_ids_no_conflict() {
320        let r = parse_request(
321            r#"[update(id="id-1", name="a"), delete(id="id-2"), update(id="id-3", name="c")]"#,
322        )
323        .unwrap();
324        check_write_key_conflicts(&r).unwrap();
325    }
326
327    #[test]
328    fn chain_mode_skips_conflict_detection() {
329        let r = parse_request(r#"update(id="same-id", name="a") | delete(id="same-id")"#).unwrap();
330        assert_eq!(r.mode, ExecutionMode::Chain);
331        check_write_key_conflicts(&r).unwrap();
332    }
333
334    #[test]
335    fn link_source_id_does_not_conflict_with_entity_update() {
336        let r = parse_request(
337            r#"[update(id="node-1", name="x"), link(source_id="node-1", target_id="node-2", relation="extends")]"#,
338        )
339        .unwrap();
340        check_write_key_conflicts(&r).unwrap();
341    }
342
343    #[test]
344    fn two_links_same_natural_key_conflict() {
345        let r = parse_request(
346            r#"[link(source_id="a", target_id="b", relation="extends"), link(source_id="a", target_id="b", relation="extends")]"#,
347        )
348        .unwrap();
349        let err = check_write_key_conflicts(&r).unwrap_err();
350        assert!(
351            matches!(&err, DslError::WriteKeyConflict { id, .. }
352                if id == "edge-natural:a:b:extends"),
353            "expected WriteKeyConflict on edge-natural key, got {err:?}"
354        );
355    }
356
357    #[test]
358    fn single_write_op_no_conflict() {
359        let r = parse_request(r#"delete(id="solo-id")"#).unwrap();
360        assert_eq!(r.mode, ExecutionMode::Single);
361        check_write_key_conflicts(&r).unwrap();
362    }
363
364    #[test]
365    fn bulk_link_and_singleton_same_natural_key_conflict() {
366        let r = parse_request(
367            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)]"#,
368        )
369        .unwrap();
370        let err = check_write_key_conflicts(&r).unwrap_err();
371        assert!(
372            matches!(&err, DslError::WriteKeyConflict { id, .. }
373                if id == "edge-natural:a:b:extends"),
374            "expected WriteKeyConflict on edge-natural key, got {err:?}"
375        );
376    }
377
378    #[test]
379    fn reversed_symmetric_links_conflict() {
380        let r = parse_request(
381            r#"[link(source_id="b", target_id="a", relation="competes_with"), link(source_id="a", target_id="b", relation="competes_with")]"#,
382        )
383        .unwrap();
384        let err = check_write_key_conflicts(&r).unwrap_err();
385        assert!(
386            matches!(&err, DslError::WriteKeyConflict { id, .. }
387                if id == "edge-natural:a:b:competes_with"),
388            "expected WriteKeyConflict on canonicalized symmetric key, got {err:?}"
389        );
390    }
391
392    #[test]
393    fn reversed_non_symmetric_links_do_not_conflict() {
394        let r = parse_request(
395            r#"[link(source_id="b", target_id="a", relation="extends"), link(source_id="a", target_id="b", relation="extends")]"#,
396        )
397        .unwrap();
398        check_write_key_conflicts(&r).unwrap();
399    }
400
401    #[test]
402    fn write_keys_for_op_pub_bulk_link_extracts_all_edges() {
403        let r = parse_request(
404            r#"link(links=[{"source_id":"a","target_id":"b","relation":"extends"},{"source_id":"c","target_id":"d","relation":"extends"}])"#,
405        )
406        .unwrap();
407        let keys = write_keys_for_op_pub(&r.ops[0]);
408        assert_eq!(
409            keys,
410            vec![
411                "edge-natural:a:b:extends".to_string(),
412                "edge-natural:c:d:extends".to_string(),
413            ]
414        );
415    }
416
417    #[test]
418    fn unit_conflict_refuses_both_units_sharing_a_key() {
419        let r = parse_request(
420            r#"[update(id="x", name="1") | update(id="y", name="2"), update(id="x", name="3")]"#,
421        )
422        .unwrap();
423        assert_eq!(r.ranges, vec![0..2, 2..3]);
424        let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
425        assert_eq!(
426            conflicts.len(),
427            2,
428            "both units must be named: {conflicts:?}"
429        );
430        assert_eq!(
431            conflicts[&0],
432            vec![UnitKeyConflict {
433                key: "entity:x".to_string(),
434                leaf: 0,
435                other_unit: 1,
436                other_leaf: 2,
437            }]
438        );
439        assert_eq!(
440            conflicts[&1],
441            vec![UnitKeyConflict {
442                key: "entity:x".to_string(),
443                leaf: 2,
444                other_unit: 0,
445                other_leaf: 0,
446            }]
447        );
448    }
449
450    #[test]
451    fn same_key_repeated_within_one_unit_is_not_reported() {
452        let r = parse_request(r#"[update(id="x", name="1") | update(id="x", name="2")]"#).unwrap();
453        assert_eq!(r.ranges.len(), 1);
454        assert_eq!(r.ranges[0], 0..2);
455        let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
456        assert!(
457            conflicts.is_empty(),
458            "a chain's own ordered leaves must not conflict with each other: {conflicts:?}"
459        );
460    }
461
462    #[test]
463    fn disjoint_units_share_no_conflict() {
464        let r = parse_request(r#"[update(id="x", name="1"), update(id="y", name="2")]"#).unwrap();
465        assert_eq!(r.ranges, vec![0..1, 1..2]);
466        assert!(unit_write_key_conflicts(&r.ops, &r.ranges).is_empty());
467    }
468
469    #[test]
470    fn three_way_unit_conflict_names_every_affected_unit() {
471        let r = parse_request(
472            r#"[update(id="x", name="1"), update(id="x", name="2"), update(id="x", name="3")]"#,
473        )
474        .unwrap();
475        let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
476        assert_eq!(conflicts.len(), 3, "{conflicts:?}");
477    }
478}