1use 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
53pub const SUBJECT_PREFIX: &str = "subject:";
55const SUBJECT_DOMAIN: &[u8] = b"leanctx.cloud.subject.v1";
57const EDGE_DOMAIN: &[u8] = b"leanctx.cloud.contradicts.v1";
59const SUPERSEDES_DOMAIN: &[u8] = b"leanctx.cloud.supersedes.v1";
61pub const MAX_PER_SYNC: usize = 32;
63
64pub 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
79pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
91pub enum Kind {
92 Contradicts,
94 Supersedes,
96}
97
98impl Kind {
99 pub fn as_str(self) -> &'static str {
101 match self {
102 Self::Contradicts => "contradicts",
103 Self::Supersedes => "supersedes",
104 }
105 }
106}
107
108#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
110pub struct Link {
111 pub edge_id: String,
112 pub kind: Kind,
113 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
130pub 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
142pub 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
153fn 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#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct Own {
173 pub project_hash: String,
175 pub subject: Option<String>,
178}
179
180#[derive(Debug, Default)]
182pub struct Inputs {
183 pub own: BTreeMap<String, Own>,
185 pub queued_edges: BTreeSet<String>,
187 pub queued_superseded: BTreeSet<String>,
189 pub saves: BTreeMap<String, Save>,
192}
193
194pub 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 for (i, to) in ids.iter().enumerate() {
236 for from in &ids[i + 1..] {
237 if marked.contains(&(*from, *to)) {
238 continue;
239 }
240 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 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
263pub 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 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 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 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
343pub 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
386pub 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 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
424pub 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;