Skip to main content

khive_request/
conflict.rs

1use std::collections::{BTreeMap, HashMap};
2use std::ops::Range;
3
4use khive_types::EdgeRelation;
5use serde_json::Value;
6
7use crate::types::{ArgValue, ParsedOp};
8
9#[cfg(test)]
10use crate::types::{DslError, ExecutionMode, ParsedRequest};
11
12/// One cross-unit static write-key conflict: `leaf` (inside the unit this
13/// entry is filed under) claims the same statically knowable write key as
14/// `other_leaf`, which belongs to a *different* unit, `other_unit`.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct UnitKeyConflict {
17    pub key: String,
18    pub leaf: usize,
19    pub other_unit: usize,
20    pub other_leaf: usize,
21}
22
23/// Finds every statically knowable write-key collision between *different*
24/// units of a bracketed batch of chains (ADR-016 Amendment 2).
25///
26/// A key repeated by two leaves of the *same* unit is legal, because a chain's own
27/// leaves are already ordered, and is never reported. A key claimed by leaves
28/// in two different units is reported once per affected unit (symmetric:
29/// both units get an entry), each naming the other unit's conflicting global
30/// leaf position, so a caller can refuse both units before any of their
31/// leaves dispatch. Units absent from the returned map share no cross-unit
32/// key with any other unit.
33pub fn unit_write_key_conflicts(
34    ops: &[ParsedOp],
35    ranges: &[Range<usize>],
36) -> BTreeMap<usize, Vec<UnitKeyConflict>> {
37    // Per unit, collapse repeated in-unit keys to their first-occurring leaf
38    // (deterministic: ranges are walked in leaf order regardless of the
39    // arbitrary hash order `write_keys_for_op_pub` or a later `HashMap`
40    // iteration might otherwise introduce).
41    let mut per_unit_keys: Vec<HashMap<String, usize>> = Vec::with_capacity(ranges.len());
42    for range in ranges {
43        let mut keys: HashMap<String, usize> = HashMap::new();
44        for leaf in range.clone() {
45            for key in write_keys_for_op_pub(&ops[leaf]) {
46                keys.entry(key).or_insert(leaf);
47            }
48        }
49        per_unit_keys.push(keys);
50    }
51
52    let mut first_claim: HashMap<String, (usize, usize)> = HashMap::new();
53    let mut conflicts: BTreeMap<usize, Vec<UnitKeyConflict>> = BTreeMap::new();
54    for (unit_index, keys) in per_unit_keys.iter().enumerate() {
55        for (key, &leaf) in keys {
56            match first_claim.get(key) {
57                Some(&(other_unit, other_leaf)) if other_unit != unit_index => {
58                    conflicts
59                        .entry(unit_index)
60                        .or_default()
61                        .push(UnitKeyConflict {
62                            key: key.clone(),
63                            leaf,
64                            other_unit,
65                            other_leaf,
66                        });
67                    conflicts
68                        .entry(other_unit)
69                        .or_default()
70                        .push(UnitKeyConflict {
71                            key: key.clone(),
72                            leaf: other_leaf,
73                            other_unit: unit_index,
74                            other_leaf: leaf,
75                        });
76                }
77                Some(_) => {}
78                None => {
79                    first_claim.insert(key.clone(), (unit_index, leaf));
80                }
81            }
82        }
83    }
84    for entries in conflicts.values_mut() {
85        entries.sort_by_key(|c| (c.leaf, c.other_leaf));
86        entries.dedup();
87    }
88    conflicts
89}
90
91/// Extracts statically knowable, substrate-prefixed write-conflict keys for `op`.
92///
93/// Missing, dynamic, or non-string targets contribute no key. The result order
94/// follows the tool's argument/entry order.
95/// See `crates/khive-request/docs/api/write-conflicts.md` for key formats.
96pub fn write_keys_for_op_pub(op: &ParsedOp) -> Vec<String> {
97    let mut keys = Vec::new();
98    match op.tool.as_str() {
99        "update" | "delete" => {
100            if let Some(ArgValue::Value(Value::String(s))) = op.args.get("id") {
101                keys.push(format!("entity:{s}"));
102            }
103        }
104        "merge" => {
105            // A dry-run merge reads the pair and returns a prediction, so it targets
106            // no stored record and declares no key. Only a literal `true` reads as a
107            // preview: absent, `false` and a non-boolean value keep the keys, on the
108            // same static-knowability rule the rest of this builder follows, so an
109            // argument this cannot read as a preview stays conservative.
110            let previews_without_writing = matches!(
111                op.args.get("dry_run"),
112                Some(ArgValue::Value(Value::Bool(true)))
113            );
114            if !previews_without_writing {
115                for name in &["into_id", "from_id"] {
116                    if let Some(ArgValue::Value(Value::String(s))) = op.args.get(*name) {
117                        keys.push(format!("entity:{s}"));
118                    }
119                }
120            }
121        }
122        "link" => {
123            // Edge keys must not collide with their endpoint entities.
124            // `source`, `target` and `kind` are accepted spellings of `source_id`,
125            // `target_id` and `relation`. Each field reads the canonical name first
126            // and the alias only when the canonical name is absent, so both
127            // spellings of one edge claim the same key. A call giving both
128            // spellings of a field is refused by the handler, so which one this
129            // reads for it does not matter.
130            let link_arg = |canonical: &str, alias: &str| {
131                op.args.get(canonical).or_else(|| op.args.get(alias))
132            };
133            if let (
134                Some(ArgValue::Value(Value::String(s))),
135                Some(ArgValue::Value(Value::String(t))),
136                Some(ArgValue::Value(Value::String(r))),
137            ) = (
138                link_arg("source_id", "source"),
139                link_arg("target_id", "target"),
140                link_arg("relation", "kind"),
141            ) {
142                push_link_key(&mut keys, s, t, r);
143            }
144
145            // Bulk and singleton links share natural keys so equivalent writes collide.
146            if let Some(ArgValue::Value(Value::Array(links))) = op.args.get("links") {
147                for link in links {
148                    let Some(obj) = link.as_object() else {
149                        continue;
150                    };
151                    let (Some(s), Some(t), Some(r)) = (
152                        obj.get("source_id").and_then(Value::as_str),
153                        obj.get("target_id").and_then(Value::as_str),
154                        obj.get("relation").and_then(Value::as_str),
155                    ) else {
156                        continue;
157                    };
158                    push_link_key(&mut keys, s, t, r);
159                }
160            }
161        }
162        _ => {}
163    }
164    keys
165}
166
167/// Adds a natural edge key, ordering endpoints for known symmetric relations.
168fn push_link_key(keys: &mut Vec<String>, source: &str, target: &str, relation: &str) {
169    let parsed = relation.parse::<EdgeRelation>().ok();
170    let relation_key = parsed.as_ref().map_or(relation, |r| r.as_str());
171    let (source_key, target_key) =
172        parsed.map_or((source, target), |r| r.canonical_endpoints(source, target));
173    keys.push(format!(
174        "edge-natural:{source_key}:{target_key}:{relation_key}"
175    ));
176}
177
178/// Scans a parsed batch for duplicate write keys; ordered chains are exempt.
179#[cfg(test)]
180pub(crate) fn check_write_key_conflicts(req: &ParsedRequest) -> Result<(), DslError> {
181    if req.mode == ExecutionMode::Chain {
182        return Ok(());
183    }
184    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
185    for op in &req.ops {
186        let keys = write_keys_for_op_pub(op);
187        for key in keys {
188            if let Some(first) = seen.get(&key) {
189                return Err(DslError::WriteKeyConflict {
190                    id: key,
191                    first_op: first.clone(),
192                    second_op: op.tool.clone(),
193                });
194            }
195            seen.insert(key, op.tool.clone());
196        }
197    }
198    Ok(())
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::parse_request;
205
206    #[test]
207    fn no_conflict_on_non_write_ops() {
208        let r =
209            parse_request(r#"[list(kind="entity"), search(kind="entity", query="x")]"#).unwrap();
210        check_write_key_conflicts(&r).unwrap();
211    }
212
213    #[test]
214    fn update_and_delete_same_id_conflict() {
215        let r =
216            parse_request(r#"[update(id="abc-123", name="new"), delete(id="abc-123")]"#).unwrap();
217        let err = check_write_key_conflicts(&r).unwrap_err();
218        assert!(
219            matches!(&err, DslError::WriteKeyConflict { id, first_op, second_op }
220                if id == "entity:abc-123" && first_op == "update" && second_op == "delete"),
221            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
222        );
223    }
224
225    #[test]
226    fn two_updates_same_id_conflict() {
227        let r = parse_request(
228            r#"[update(id="uuid-1", name="a"), update(id="uuid-1", description="b")]"#,
229        )
230        .unwrap();
231        let err = check_write_key_conflicts(&r).unwrap_err();
232        assert!(
233            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:uuid-1"),
234            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
235        );
236    }
237
238    #[test]
239    fn merge_from_id_conflicts_with_delete() {
240        let r =
241            parse_request(r#"[merge(into_id="new-id", from_id="old-id"), delete(id="old-id")]"#)
242                .unwrap();
243        let err = check_write_key_conflicts(&r).unwrap_err();
244        assert!(
245            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
246            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
247        );
248    }
249
250    #[test]
251    fn two_dry_run_merges_in_one_batch_do_not_conflict() {
252        // The refusal this closes: two previews over the same pair were rejected as
253        // overlapping writes and had to be issued as sequential singleton calls.
254        let r = parse_request(
255            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)]"#,
256        )
257        .unwrap();
258        check_write_key_conflicts(&r).unwrap();
259    }
260
261    #[test]
262    fn a_dry_run_merge_does_not_conflict_with_a_delete_of_its_from_id() {
263        // The same pair as merge_from_id_conflicts_with_delete above, which is the
264        // control: the only difference between the two cases is the preview flag.
265        let r = parse_request(
266            r#"[merge(into_id="new-id", from_id="old-id", dry_run=true), delete(id="old-id")]"#,
267        )
268        .unwrap();
269        check_write_key_conflicts(&r).unwrap();
270    }
271
272    #[test]
273    fn dry_run_false_keeps_the_merge_keys() {
274        let r = parse_request(
275            r#"[merge(into_id="new-id", from_id="old-id", dry_run=false), delete(id="old-id")]"#,
276        )
277        .unwrap();
278        let err = check_write_key_conflicts(&r).unwrap_err();
279        assert!(
280            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
281            "a merge that writes must keep its keys, got {err:?}"
282        );
283    }
284
285    #[test]
286    fn a_non_boolean_dry_run_keeps_the_merge_keys() {
287        // A string is not the preview the handler acts on, so reading it as one here
288        // would drop the keys of an op that goes on to write.
289        let r = parse_request(
290            r#"[merge(into_id="new-id", from_id="old-id", dry_run="true"), delete(id="old-id")]"#,
291        )
292        .unwrap();
293        let err = check_write_key_conflicts(&r).unwrap_err();
294        assert!(
295            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
296            "a non-boolean dry_run must stay conservative, got {err:?}"
297        );
298    }
299
300    #[test]
301    fn different_ids_no_conflict() {
302        let r = parse_request(
303            r#"[update(id="id-1", name="a"), delete(id="id-2"), update(id="id-3", name="c")]"#,
304        )
305        .unwrap();
306        check_write_key_conflicts(&r).unwrap();
307    }
308
309    #[test]
310    fn chain_mode_skips_conflict_detection() {
311        let r = parse_request(r#"update(id="same-id", name="a") | delete(id="same-id")"#).unwrap();
312        assert_eq!(r.mode, ExecutionMode::Chain);
313        check_write_key_conflicts(&r).unwrap();
314    }
315
316    #[test]
317    fn link_source_id_does_not_conflict_with_entity_update() {
318        let r = parse_request(
319            r#"[update(id="node-1", name="x"), link(source_id="node-1", target_id="node-2", relation="extends")]"#,
320        )
321        .unwrap();
322        check_write_key_conflicts(&r).unwrap();
323    }
324
325    #[test]
326    fn two_links_same_natural_key_conflict() {
327        let r = parse_request(
328            r#"[link(source_id="a", target_id="b", relation="extends"), link(source_id="a", target_id="b", relation="extends")]"#,
329        )
330        .unwrap();
331        let err = check_write_key_conflicts(&r).unwrap_err();
332        assert!(
333            matches!(&err, DslError::WriteKeyConflict { id, .. }
334                if id == "edge-natural:a:b:extends"),
335            "expected WriteKeyConflict on edge-natural key, got {err:?}"
336        );
337    }
338
339    #[test]
340    fn mixed_spelling_links_to_one_edge_conflict_like_the_canonical_spelling() {
341        // Both spellings of the same edge must produce the same key: the
342        // canonical pair is the control, and each mixed ordering is the case a
343        // key builder that only knows the canonical names lets through.
344        for ops in [
345            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)]"#,
346            r#"[link(source_id="a", target_id="b", relation="extends", weight=0.1), link(source="a", target="b", kind="extends", weight=0.9)]"#,
347            r#"[link(source="a", target="b", kind="extends", weight=0.1), link(source_id="a", target_id="b", relation="extends", weight=0.9)]"#,
348        ] {
349            let r = parse_request(ops).unwrap();
350            let err = check_write_key_conflicts(&r).unwrap_err();
351            assert!(
352                matches!(&err, DslError::WriteKeyConflict { id, first_op, second_op }
353                    if id == "edge-natural:a:b:extends"
354                        && first_op == "link"
355                        && second_op == "link"),
356                "{ops} must conflict on the edge key, got {err:?}"
357            );
358        }
359    }
360
361    #[test]
362    fn aliased_only_links_to_one_edge_conflict() {
363        let r = parse_request(
364            r#"[link(source="a", target="b", kind="extends"), link(source="a", target="b", kind="extends")]"#,
365        )
366        .unwrap();
367        let err = check_write_key_conflicts(&r).unwrap_err();
368        assert!(
369            matches!(&err, DslError::WriteKeyConflict { id, .. }
370                if id == "edge-natural:a:b:extends"),
371            "expected WriteKeyConflict on edge-natural key, got {err:?}"
372        );
373    }
374
375    #[test]
376    fn each_link_field_reads_its_own_alias_into_the_canonical_key() {
377        // A directional relation, so an alias read into the wrong endpoint slot
378        // would yield `b:a` rather than `a:b`.
379        for ops in [
380            r#"link(source="a", target="b", kind="extends")"#,
381            r#"link(source="a", target_id="b", relation="extends")"#,
382            r#"link(source_id="a", target="b", relation="extends")"#,
383            r#"link(source_id="a", target_id="b", kind="extends")"#,
384        ] {
385            let r = parse_request(ops).unwrap();
386            assert_eq!(
387                write_keys_for_op_pub(&r.ops[0]),
388                vec!["edge-natural:a:b:extends".to_string()],
389                "{ops}"
390            );
391        }
392    }
393
394    #[test]
395    fn single_write_op_no_conflict() {
396        let r = parse_request(r#"delete(id="solo-id")"#).unwrap();
397        assert_eq!(r.mode, ExecutionMode::Single);
398        check_write_key_conflicts(&r).unwrap();
399    }
400
401    #[test]
402    fn bulk_link_and_singleton_same_natural_key_conflict() {
403        let r = parse_request(
404            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)]"#,
405        )
406        .unwrap();
407        let err = check_write_key_conflicts(&r).unwrap_err();
408        assert!(
409            matches!(&err, DslError::WriteKeyConflict { id, .. }
410                if id == "edge-natural:a:b:extends"),
411            "expected WriteKeyConflict on edge-natural key, got {err:?}"
412        );
413    }
414
415    #[test]
416    fn reversed_symmetric_links_conflict() {
417        let r = parse_request(
418            r#"[link(source_id="b", target_id="a", relation="competes_with"), link(source_id="a", target_id="b", relation="competes_with")]"#,
419        )
420        .unwrap();
421        let err = check_write_key_conflicts(&r).unwrap_err();
422        assert!(
423            matches!(&err, DslError::WriteKeyConflict { id, .. }
424                if id == "edge-natural:a:b:competes_with"),
425            "expected WriteKeyConflict on canonicalized symmetric key, got {err:?}"
426        );
427    }
428
429    #[test]
430    fn reversed_non_symmetric_links_do_not_conflict() {
431        for (relation, key) in [
432            ("extends", "extends"),
433            ("derivedfrom", "derived_from"),
434            ("Custom-Relation", "Custom-Relation"),
435        ] {
436            let r = parse_request(&format!(
437                r#"[link(source_id="b", target_id="a", relation="{relation}"), link(source_id="a", target_id="b", relation="{relation}")]"#,
438            )).unwrap();
439            check_write_key_conflicts(&r).unwrap();
440            assert_eq!(
441                write_keys_for_op_pub(&r.ops[0]),
442                [format!("edge-natural:b:a:{key}")]
443            );
444        }
445    }
446
447    #[test]
448    fn write_keys_for_op_pub_bulk_link_extracts_all_edges() {
449        let r = parse_request(
450            r#"link(links=[{"source_id":"a","target_id":"b","relation":"extends"},{"source_id":"c","target_id":"d","relation":"extends"}])"#,
451        )
452        .unwrap();
453        let keys = write_keys_for_op_pub(&r.ops[0]);
454        assert_eq!(
455            keys,
456            vec![
457                "edge-natural:a:b:extends".to_string(),
458                "edge-natural:c:d:extends".to_string(),
459            ]
460        );
461    }
462
463    #[test]
464    fn unit_conflict_refuses_both_units_sharing_a_key() {
465        let r = parse_request(
466            r#"[update(id="x", name="1") | update(id="y", name="2"), update(id="x", name="3")]"#,
467        )
468        .unwrap();
469        assert_eq!(r.ranges, vec![0..2, 2..3]);
470        let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
471        assert_eq!(
472            conflicts.len(),
473            2,
474            "both units must be named: {conflicts:?}"
475        );
476        assert_eq!(
477            conflicts[&0],
478            vec![UnitKeyConflict {
479                key: "entity:x".to_string(),
480                leaf: 0,
481                other_unit: 1,
482                other_leaf: 2,
483            }]
484        );
485        assert_eq!(
486            conflicts[&1],
487            vec![UnitKeyConflict {
488                key: "entity:x".to_string(),
489                leaf: 2,
490                other_unit: 0,
491                other_leaf: 0,
492            }]
493        );
494    }
495
496    #[test]
497    fn same_key_repeated_within_one_unit_is_not_reported() {
498        let r = parse_request(r#"[update(id="x", name="1") | update(id="x", name="2")]"#).unwrap();
499        assert_eq!(r.ranges.len(), 1);
500        assert_eq!(r.ranges[0], 0..2);
501        let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
502        assert!(
503            conflicts.is_empty(),
504            "a chain's own ordered leaves must not conflict with each other: {conflicts:?}"
505        );
506    }
507
508    #[test]
509    fn disjoint_units_share_no_conflict() {
510        let r = parse_request(r#"[update(id="x", name="1"), update(id="y", name="2")]"#).unwrap();
511        assert_eq!(r.ranges, vec![0..1, 1..2]);
512        assert!(unit_write_key_conflicts(&r.ops, &r.ranges).is_empty());
513    }
514
515    #[test]
516    fn three_way_unit_conflict_names_every_affected_unit() {
517        let r = parse_request(
518            r#"[update(id="x", name="1"), update(id="x", name="2"), update(id="x", name="3")]"#,
519        )
520        .unwrap();
521        let conflicts = unit_write_key_conflicts(&r.ops, &r.ranges);
522        assert_eq!(conflicts.len(), 3, "{conflicts:?}");
523    }
524}