Skip to main content

khive_request/
conflict.rs

1use std::collections::{BTreeMap, BTreeSet, 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/// Direct conflict participants for each flat-batch operation, including itself.
13///
14/// Lists are sorted and unique. Repeated key occurrences within one operation
15/// retain the existing flat-batch refusal and produce a self-only list. This
16/// reports static write keys; it does not resolve IDs or change admission.
17pub fn write_key_conflict_ops(ops: &[ParsedOp]) -> Vec<Vec<usize>> {
18    participants_for_keys(
19        ops.len(),
20        key_claims(ops)
21            .into_values()
22            .filter(|claims| claims.len() > 1),
23    )
24}
25
26/// Direct conflict participants for each global leaf of a parallel batch of chains.
27///
28/// Only keys shared across different units count. For such a key, every claiming
29/// leaf is included, even repeated claims within a unit. An innocent leaf in a
30/// refused unit has an empty list. Lists never expand through transitive conflicts.
31/// `ranges` must partition `ops`, as guaranteed by the request parser.
32pub fn unit_write_key_conflict_ops(ops: &[ParsedOp], ranges: &[Range<usize>]) -> Vec<Vec<usize>> {
33    let mut unit_of = vec![0; ops.len()];
34    for (unit, range) in ranges.iter().enumerate() {
35        for leaf in range.clone() {
36            unit_of[leaf] = unit;
37        }
38    }
39    participants_for_keys(
40        ops.len(),
41        key_claims(ops).into_values().filter(|claims| {
42            claims
43                .iter()
44                .any(|&leaf| unit_of[leaf] != unit_of[claims[0]])
45        }),
46    )
47}
48
49fn key_claims(ops: &[ParsedOp]) -> HashMap<String, Vec<usize>> {
50    let mut claims: HashMap<String, Vec<usize>> = HashMap::new();
51    for (index, op) in ops.iter().enumerate() {
52        for key in write_keys_for_op_pub(op) {
53            claims.entry(key).or_default().push(index);
54        }
55    }
56    claims
57}
58
59fn participants_for_keys(count: usize, keys: impl Iterator<Item = Vec<usize>>) -> Vec<Vec<usize>> {
60    let mut participants = vec![BTreeSet::new(); count];
61    for claims in keys {
62        let claims: BTreeSet<_> = claims.into_iter().collect();
63        for &index in &claims {
64            participants[index].extend(claims.iter().copied());
65        }
66    }
67    participants
68        .into_iter()
69        .map(|indices| indices.into_iter().collect())
70        .collect()
71}
72
73/// One cross-unit static write-key conflict: `leaf` (inside the unit this
74/// entry is filed under) claims the same statically knowable write key as
75/// `other_leaf`, which belongs to a *different* unit, `other_unit`.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct UnitKeyConflict {
78    pub key: String,
79    pub leaf: usize,
80    pub other_unit: usize,
81    pub other_leaf: usize,
82}
83
84/// Finds every statically knowable write-key collision between *different*
85/// units of a bracketed batch of chains (ADR-016 Amendment 2).
86///
87/// A key repeated by two leaves of the *same* unit is legal, because a chain's own
88/// leaves are already ordered, and is never reported. A key claimed by leaves
89/// in two different units is reported once per affected unit (symmetric:
90/// both units get an entry), each naming the other unit's conflicting global
91/// leaf position, so a caller can refuse both units before any of their
92/// leaves dispatch. Units absent from the returned map share no cross-unit
93/// key with any other unit.
94pub fn unit_write_key_conflicts(
95    ops: &[ParsedOp],
96    ranges: &[Range<usize>],
97) -> BTreeMap<usize, Vec<UnitKeyConflict>> {
98    // Per unit, collapse repeated in-unit keys to their first-occurring leaf
99    // (deterministic: ranges are walked in leaf order regardless of the
100    // arbitrary hash order `write_keys_for_op_pub` or a later `HashMap`
101    // iteration might otherwise introduce).
102    let mut per_unit_keys: Vec<HashMap<String, usize>> = Vec::with_capacity(ranges.len());
103    for range in ranges {
104        let mut keys: HashMap<String, usize> = HashMap::new();
105        for leaf in range.clone() {
106            for key in write_keys_for_op_pub(&ops[leaf]) {
107                keys.entry(key).or_insert(leaf);
108            }
109        }
110        per_unit_keys.push(keys);
111    }
112
113    let mut first_claim: HashMap<String, (usize, usize)> = HashMap::new();
114    let mut conflicts: BTreeMap<usize, Vec<UnitKeyConflict>> = BTreeMap::new();
115    for (unit_index, keys) in per_unit_keys.iter().enumerate() {
116        for (key, &leaf) in keys {
117            match first_claim.get(key) {
118                Some(&(other_unit, other_leaf)) if other_unit != unit_index => {
119                    conflicts
120                        .entry(unit_index)
121                        .or_default()
122                        .push(UnitKeyConflict {
123                            key: key.clone(),
124                            leaf,
125                            other_unit,
126                            other_leaf,
127                        });
128                    conflicts
129                        .entry(other_unit)
130                        .or_default()
131                        .push(UnitKeyConflict {
132                            key: key.clone(),
133                            leaf: other_leaf,
134                            other_unit: unit_index,
135                            other_leaf: leaf,
136                        });
137                }
138                Some(_) => {}
139                None => {
140                    first_claim.insert(key.clone(), (unit_index, leaf));
141                }
142            }
143        }
144    }
145    for entries in conflicts.values_mut() {
146        entries.sort_by_key(|c| (c.leaf, c.other_leaf));
147        entries.dedup();
148    }
149    conflicts
150}
151
152/// Extracts statically knowable, substrate-prefixed write-conflict keys for `op`.
153///
154/// Missing, dynamic, or non-string targets contribute no key. The result order
155/// follows the tool's argument/entry order.
156/// See `crates/khive-request/docs/api/write-conflicts.md` for key formats.
157pub fn write_keys_for_op_pub(op: &ParsedOp) -> Vec<String> {
158    let mut keys = Vec::new();
159    match op.tool.as_str() {
160        "update" | "delete" => {
161            if let Some(ArgValue::Value(Value::String(s))) = op.args.get("id") {
162                keys.push(format!("entity:{s}"));
163            }
164        }
165        "merge" => {
166            // A dry-run merge reads the pair and returns a prediction, so it targets
167            // no stored record and declares no key. Only a literal `true` reads as a
168            // preview: absent, `false` and a non-boolean value keep the keys, on the
169            // same static-knowability rule the rest of this builder follows, so an
170            // argument this cannot read as a preview stays conservative.
171            let previews_without_writing = matches!(
172                op.args.get("dry_run"),
173                Some(ArgValue::Value(Value::Bool(true)))
174            );
175            if !previews_without_writing {
176                for name in &["into_id", "from_id"] {
177                    if let Some(ArgValue::Value(Value::String(s))) = op.args.get(*name) {
178                        keys.push(format!("entity:{s}"));
179                    }
180                }
181            }
182        }
183        "link" => {
184            // Edge keys must not collide with their endpoint entities.
185            // `source`, `target` and `kind` are accepted spellings of `source_id`,
186            // `target_id` and `relation`. Each field reads the canonical name first
187            // and the alias only when the canonical name is absent, so both
188            // spellings of one edge claim the same key. A call giving both
189            // spellings of a field is refused by the handler, so which one this
190            // reads for it does not matter.
191            let link_arg = |canonical: &str, alias: &str| {
192                op.args.get(canonical).or_else(|| op.args.get(alias))
193            };
194            if let (
195                Some(ArgValue::Value(Value::String(s))),
196                Some(ArgValue::Value(Value::String(t))),
197                Some(ArgValue::Value(Value::String(r))),
198            ) = (
199                link_arg("source_id", "source"),
200                link_arg("target_id", "target"),
201                link_arg("relation", "kind"),
202            ) {
203                push_link_key(&mut keys, s, t, r);
204            }
205
206            // Bulk and singleton links share natural keys so equivalent writes collide.
207            if let Some(ArgValue::Value(Value::Array(links))) = op.args.get("links") {
208                for link in links {
209                    let Some(obj) = link.as_object() else {
210                        continue;
211                    };
212                    let (Some(s), Some(t), Some(r)) = (
213                        obj.get("source_id").and_then(Value::as_str),
214                        obj.get("target_id").and_then(Value::as_str),
215                        obj.get("relation").and_then(Value::as_str),
216                    ) else {
217                        continue;
218                    };
219                    push_link_key(&mut keys, s, t, r);
220                }
221            }
222        }
223        _ => {}
224    }
225    keys
226}
227
228/// Adds a natural edge key, ordering endpoints for known symmetric relations.
229fn push_link_key(keys: &mut Vec<String>, source: &str, target: &str, relation: &str) {
230    let parsed = relation.parse::<EdgeRelation>().ok();
231    let relation_key = parsed.as_ref().map_or(relation, |r| r.as_str());
232    let (source_key, target_key) =
233        parsed.map_or((source, target), |r| r.canonical_endpoints(source, target));
234    keys.push(format!(
235        "edge-natural:{source_key}:{target_key}:{relation_key}"
236    ));
237}
238
239/// Scans a parsed batch for duplicate write keys; ordered chains are exempt.
240#[cfg(test)]
241pub(crate) fn check_write_key_conflicts(req: &ParsedRequest) -> Result<(), DslError> {
242    if req.mode == ExecutionMode::Chain {
243        return Ok(());
244    }
245    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
246    for op in &req.ops {
247        let keys = write_keys_for_op_pub(op);
248        for key in keys {
249            if let Some(first) = seen.get(&key) {
250                return Err(DslError::WriteKeyConflict {
251                    conflict_ops: key_claims(&req.ops)[&key]
252                        .iter()
253                        .copied()
254                        .collect::<BTreeSet<_>>()
255                        .into_iter()
256                        .collect(),
257                    id: key,
258                    first_op: first.clone(),
259                    second_op: op.tool.clone(),
260                });
261            }
262            seen.insert(key, op.tool.clone());
263        }
264    }
265    Ok(())
266}
267
268#[cfg(test)]
269#[path = "conflict_tests.rs"]
270mod tests;