Skip to main content

lean_ctx_cloud/capture/
conflicts.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Concurrent edits of one shared fact across Instances (#286).
3//!
4//! A claim's node id comes from its text, so two Instances that give the
5//! same fact (`category`, `key`) different values write two unlinked nodes.
6//! Capture therefore gives every shared `fact` node a subject reference in
7//! its `applies_to`: `subject:<id>`, a digest of (`category`, `key`) keyed
8//! with the place id key `pk_id` (like the dedupe key: two engines of a
9//! place reach the same id, nobody without the key can confirm a guessed
10//! key, and no local key text leaves the machine).
11//!
12//! Every sync then folds the place and groups the live, not superseded
13//! fact nodes by subject. Two nodes of one subject are linked, and which
14//! link follows from the save history: each node's first `seq` in the log
15//! and the `causal_base` of that save (how far its writer had folded when
16//! it wrote the fact: the sync stamps fact saves with the position before
17//! its own pull, so a value pulled in the same sync never counts as seen).
18//!
19//! * **Sequential edit**: the later save's writer had already folded the
20//!   earlier one (`causal_base >= seq` of the earlier). The later value
21//!   replaces it: its author queues `edge.add supersedes` from the newer
22//!   node to the older one, so the older value is served as outdated and
23//!   the newer as current.
24//! * **Concurrent edit**: neither writer had seen the other's save, or the
25//!   history of either is unknown. That is a conflict: one `edge.add
26//!   contradicts` between them, and delivery serves both as
27//!   `[conflicting]` on every Instance.
28//!
29//! The resolution is deterministic, the same on every Instance that folded
30//! the same log: the edge id is a keyed digest of its kind and its pair, so
31//! a second write names the same edge (the place refuses it, nothing
32//! doubles), and exactly one Instance writes it (the replica's
33//! `own_sources` know the authors): the newer node's author a
34//! `supersedes`, the larger node's author a `contradicts`, which runs `from`
35//! the larger node id `to` the smaller one. Others never race it.
36//!
37//! A node superseded in the place (or by a queued `supersedes`) is no
38//! longer linked, and two nodes of one subject from the same checkout are
39//! left to the capture lifecycle.
40
41use std::collections::{BTreeMap, BTreeSet};
42
43use serde_json::Value;
44
45use crate::CloudError;
46use crate::events::hlc::{self, Stamp};
47use crate::events::ids;
48use crate::replica::Replica;
49use crate::replica::fold::{Graph, Node};
50use crate::replica::log::Save;
51use crate::review::maintain::{Target, queue};
52
53/// Prefix of the subject reference in a fact's `applies_to`.
54pub const SUBJECT_PREFIX: &str = "subject:";
55/// Domain of the subject digest.
56const SUBJECT_DOMAIN: &[u8] = b"leanctx.cloud.subject.v1";
57/// Domain of a conflict edge id.
58const EDGE_DOMAIN: &[u8] = b"leanctx.cloud.contradicts.v1";
59/// Domain of a sequential edit's `supersedes` edge id.
60const SUPERSEDES_DOMAIN: &[u8] = b"leanctx.cloud.supersedes.v1";
61/// The most conflict edges one sync queues (the rest follow next sync).
62pub const MAX_PER_SYNC: usize = 32;
63
64/// The subject reference of the fact (`category`, `key`) in a place with
65/// id key `pk_id`: `subject:` + 26 base32 characters.
66pub fn subject_ref(pk_id: &[u8; 32], category: &str, key: &str) -> String {
67    let mut h = blake3::Hasher::new_keyed(pk_id);
68    h.update(SUBJECT_DOMAIN);
69    h.update(&[0]);
70    h.update(category.as_bytes());
71    h.update(&[0]);
72    h.update(key.as_bytes());
73    format!(
74        "{SUBJECT_PREFIX}{}",
75        &ids::base32_lower(h.finalize().as_bytes())[..26]
76    )
77}
78
79/// The subject reference a folded node carries, if any.
80pub fn subject_of(node: &Node) -> Option<&str> {
81    node.fields
82        .get("applies_to")?
83        .as_array()?
84        .iter()
85        .filter_map(Value::as_str)
86        .find(|a| a.starts_with(SUBJECT_PREFIX))
87}
88
89/// What a link between two values of one fact says.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
91pub enum Kind {
92    /// Concurrent values: both are served as conflicting.
93    Contradicts,
94    /// A sequential edit: `from` (newer) replaces `to` (older).
95    Supersedes,
96}
97
98impl Kind {
99    /// The edge kind in the event body.
100    pub fn as_str(self) -> &'static str {
101        match self {
102            Self::Contradicts => "contradicts",
103            Self::Supersedes => "supersedes",
104        }
105    }
106}
107
108/// One link edge to write.
109#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
110pub struct Link {
111    pub edge_id: String,
112    pub kind: Kind,
113    /// `contradicts`: the larger node id of the pair; `supersedes`: the
114    /// newer node.
115    pub from: String,
116    pub to: String,
117}
118
119fn link_id(pk_id: &[u8; 32], domain: &[u8], from: &str, to: &str) -> String {
120    let mut h = blake3::Hasher::new_keyed(pk_id);
121    h.update(domain);
122    h.update(&[0]);
123    h.update(from.as_bytes());
124    h.update(&[0]);
125    h.update(to.as_bytes());
126    let bytes: [u8; 16] = h.finalize().as_bytes()[..16].try_into().expect("16 bytes");
127    ids::random_id("e", &bytes)
128}
129
130/// The deterministic conflict edge between `a` and `b` in a place with id
131/// key `pk_id`.
132pub fn contradiction(pk_id: &[u8; 32], a: &str, b: &str) -> Link {
133    let (from, to) = if a > b { (a, b) } else { (b, a) };
134    Link {
135        edge_id: link_id(pk_id, EDGE_DOMAIN, from, to),
136        kind: Kind::Contradicts,
137        from: from.to_owned(),
138        to: to.to_owned(),
139    }
140}
141
142/// The deterministic `supersedes` edge from the newer value `new` to the
143/// older value `old` in a place with id key `pk_id`.
144pub fn supersession(pk_id: &[u8; 32], new: &str, old: &str) -> Link {
145    Link {
146        edge_id: link_id(pk_id, SUPERSEDES_DOMAIN, new, old),
147        kind: Kind::Supersedes,
148        from: new.to_owned(),
149        to: old.to_owned(),
150    }
151}
152
153/// How two values of one fact relate, from their save history: `Some((new,
154/// old))` when the later save's writer had folded the earlier one, `None`
155/// for concurrent values or an unknown history (a conflict).
156fn sequential<'a>(
157    saves: &BTreeMap<String, Save>,
158    a: &'a str,
159    b: &'a str,
160) -> Option<(&'a str, &'a str)> {
161    let (sa, sb) = (saves.get(a)?, saves.get(b)?);
162    let ((new, s_new), (old, s_old)) = if sa.seq > sb.seq {
163        ((a, sa), (b, sb))
164    } else {
165        ((b, sb), (a, sa))
166    };
167    (s_new.seq != s_old.seq && s_new.causal_base >= s_old.seq).then_some((new, old))
168}
169
170/// A fact node this Instance authored (`own_sources`).
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct Own {
173    /// The checkout that captured it.
174    pub project_hash: String,
175    /// Its subject, from the source's category and key (nodes captured
176    /// before subjects were written carry none in their body).
177    pub subject: Option<String>,
178}
179
180/// What [`plan`] reads besides the folded graph.
181#[derive(Debug, Default)]
182pub struct Inputs {
183    /// This Instance's own fact nodes.
184    pub own: BTreeMap<String, Own>,
185    /// Targets of `edge.add` events queued and not yet folded.
186    pub queued_edges: BTreeSet<String>,
187    /// Nodes a queued `supersedes` edge supersedes.
188    pub queued_superseded: BTreeSet<String>,
189    /// Each node's first save in the log ([`Replica::first_saves`]); a node
190    /// without one has an unknown history.
191    pub saves: BTreeMap<String, Save>,
192}
193
194/// The link edges this Instance writes for `graph`, in a stable order
195/// (at most [`MAX_PER_SYNC`]).
196pub fn plan(graph: &Graph, pk_id: &[u8; 32], inputs: &Inputs) -> Vec<Link> {
197    let live = |id: &str| {
198        graph
199            .nodes
200            .get(id)
201            .is_some_and(|n| !n.retracted && !n.purged)
202    };
203    let mut superseded: BTreeSet<&str> = graph
204        .edges
205        .values()
206        .filter(|e| e.kind == "supersedes" && !e.retracted && live(&e.from))
207        .map(|e| e.to.as_str())
208        .collect();
209    superseded.extend(inputs.queued_superseded.iter().map(String::as_str));
210    let marked: BTreeSet<(&str, &str)> = graph
211        .edges
212        .values()
213        .filter(|e| e.kind == "contradicts" && !e.retracted)
214        .flat_map(|e| {
215            [
216                (e.from.as_str(), e.to.as_str()),
217                (e.to.as_str(), e.from.as_str()),
218            ]
219        })
220        .collect();
221    let mut by_subject: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
222    for (id, node) in graph.live_nodes() {
223        if node.node_type != "fact" || superseded.contains(id.as_str()) {
224            continue;
225        }
226        let subject =
227            subject_of(node).or_else(|| inputs.own.get(id).and_then(|o| o.subject.as_deref()));
228        if let Some(subject) = subject {
229            by_subject.entry(subject).or_default().push(id);
230        }
231    }
232    let mut out = Vec::new();
233    for ids in by_subject.values().filter(|ids| ids.len() > 1) {
234        // `live_nodes` iterates in id order: `ids` is sorted.
235        for (i, to) in ids.iter().enumerate() {
236            for from in &ids[i + 1..] {
237                if marked.contains(&(*from, *to)) {
238                    continue;
239                }
240                // Two values from one checkout: the lifecycle supersedes.
241                if let (Some(a), Some(b)) = (inputs.own.get(*from), inputs.own.get(*to))
242                    && a.project_hash == b.project_hash
243                {
244                    continue;
245                }
246                // A sequential edit: the newer node's author supersedes;
247                // otherwise the larger node's author marks the conflict.
248                let (writer, link) = match sequential(&inputs.saves, from, to) {
249                    Some((new, old)) => (new, supersession(pk_id, new, old)),
250                    None => (*from, contradiction(pk_id, from, to)),
251                };
252                if inputs.own.contains_key(writer) && !inputs.queued_edges.contains(&link.edge_id) {
253                    out.push(link);
254                }
255            }
256        }
257    }
258    out.sort();
259    out.truncate(MAX_PER_SYNC);
260    out
261}
262
263/// The links between the values of one fact that every Instance derives on
264/// read, from the folded graph and the save history alone: the same
265/// resolution as [`plan`], before (or without) its edge reaching this
266/// replica. Without it, an Instance that pulled both values of a fact
267/// served them as two plain claims until the one Instance the resolution
268/// names had written its edge and this one had pulled it (#286).
269///
270/// A node is grouped by the subject in its body (nodes captured before
271/// subjects are left to their author's edge). Sequential edits come
272/// first: the older value is superseded, then the open values left in a
273/// group contradict each other pairwise. Pairs a folded `contradicts` or
274/// `supersedes` edge already links, retracted or not, are skipped first,
275/// as in [`plan`]. Returns `(kind, from, to)` in a stable order.
276pub fn derived(graph: &Graph, saves: &BTreeMap<String, Save>) -> Vec<(Kind, String, String)> {
277    let live = |id: &str| {
278        graph
279            .nodes
280            .get(id)
281            .is_some_and(|n| !n.retracted && !n.purged)
282    };
283    let superseded: BTreeSet<&str> = graph
284        .edges
285        .values()
286        .filter(|e| e.kind == "supersedes" && !e.retracted && live(&e.from))
287        .map(|e| e.to.as_str())
288        .collect();
289    // A pair any folded link edge joins is decided, either way round and
290    // even when retracted: a curator's retraction is a decision too, and
291    // deriving the link again would undo it.
292    let decided: BTreeSet<(&str, &str)> = graph
293        .edges
294        .values()
295        .filter(|e| e.kind == "contradicts" || e.kind == "supersedes")
296        .flat_map(|e| {
297            [
298                (e.from.as_str(), e.to.as_str()),
299                (e.to.as_str(), e.from.as_str()),
300            ]
301        })
302        .collect();
303    let mut by_subject: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
304    for (id, node) in graph.live_nodes() {
305        if node.node_type != "fact" || superseded.contains(id.as_str()) {
306            continue;
307        }
308        if let Some(subject) = subject_of(node) {
309            by_subject.entry(subject).or_default().push(id);
310        }
311    }
312    let mut out = Vec::new();
313    for ids in by_subject.values().filter(|ids| ids.len() > 1) {
314        // Same order as `plan`: a decided pair is skipped first, then a
315        // sequential edit supersedes, otherwise the pair contradicts.
316        let mut old: BTreeSet<&str> = BTreeSet::new();
317        let mut open: Vec<(&str, &str)> = Vec::new();
318        for (i, to) in ids.iter().enumerate() {
319            for from in &ids[i + 1..] {
320                if decided.contains(&(*from, *to)) {
321                    continue;
322                }
323                match sequential(saves, from, to) {
324                    Some((new, older)) => {
325                        old.insert(older);
326                        out.push((Kind::Supersedes, new.to_owned(), older.to_owned()));
327                    }
328                    None => open.push((*from, *to)),
329                }
330            }
331        }
332        // A value superseded here no longer conflicts.
333        out.extend(
334            open.into_iter()
335                .filter(|(from, to)| !old.contains(from) && !old.contains(to))
336                .map(|(from, to)| (Kind::Contradicts, from.to_owned(), to.to_owned())),
337        );
338    }
339    out.sort();
340    out
341}
342
343/// [`Inputs`] from the replica: own fact sources, the save history and
344/// the pending queue.
345pub fn inputs(replica: &Replica, pk_id: &[u8; 32]) -> Result<Inputs, CloudError> {
346    let mut inputs = Inputs {
347        saves: replica.first_saves()?,
348        ..Inputs::default()
349    };
350    for (node_id, kind, source) in replica.own_sources()? {
351        if kind != "fact" {
352            continue;
353        }
354        let text = |k: &str| source.get(k).and_then(Value::as_str);
355        let subject = match (text("category"), text("key")) {
356            (Some(category), Some(key)) => Some(subject_ref(pk_id, category, key)),
357            _ => None,
358        };
359        inputs.own.insert(
360            node_id,
361            Own {
362                project_hash: text("project_hash").unwrap_or_default().to_owned(),
363                subject,
364            },
365        );
366    }
367    for (_, bytes) in replica.pending()? {
368        let Ok(event) = serde_json::from_slice::<Value>(&bytes) else {
369            continue;
370        };
371        if event["op"] != "edge.add" {
372            continue;
373        }
374        if let Some(target) = event["target"].as_str() {
375            inputs.queued_edges.insert(target.to_owned());
376        }
377        if event["body"]["kind"] == "supersedes"
378            && let Some(to) = event["body"]["to"].as_str()
379        {
380            inputs.queued_superseded.insert(to.to_owned());
381        }
382    }
383    Ok(inputs)
384}
385
386/// Queue the signed link edges of `planned` (the sync push sends them),
387/// continuing `clock`. Returns how many it queued and the clock.
388pub fn queue_all(
389    target: &Target<'_>,
390    planned: &[Link],
391    clock: Stamp,
392    now_ms: u64,
393) -> Result<(usize, Stamp), CloudError> {
394    let mut clock = clock;
395    for c in planned {
396        clock = hlc::send(clock, now_ms);
397        let event = match c.kind {
398            Kind::Contradicts => crate::review::curate::contradicts_edge_at(
399                target.place,
400                &c.edge_id,
401                &c.from,
402                &c.to,
403                clock,
404                target.signer,
405            )?,
406            // Written like the capture lifecycle's supersedes: by the
407            // newer value's author.
408            Kind::Supersedes => crate::events::build::edge_add_at(
409                &c.edge_id,
410                c.kind.as_str(),
411                &c.from,
412                &c.to,
413                "observed",
414                target.place,
415                clock,
416                target.signer,
417            )?,
418        };
419        queue(target, &event, clock)?;
420    }
421    Ok((planned.len(), clock))
422}
423
424/// Fold the replica, plan and queue this Instance's conflict edges.
425pub fn detect(
426    target: &Target<'_>,
427    pk_id: &[u8; 32],
428    clock: Stamp,
429    now_ms: u64,
430) -> Result<(usize, Stamp), CloudError> {
431    let mut graph = Graph::default();
432    graph
433        .fold(&target.replica.fold_events()?)
434        .map_err(|e| CloudError::Protocol(e.to_string()))?;
435    let planned = plan(&graph, pk_id, &inputs(target.replica, pk_id)?);
436    queue_all(target, &planned, clock, now_ms)
437}
438
439#[cfg(test)]
440#[path = "conflicts_tests.rs"]
441mod tests;