//! A state: a dependency-closed set of changes, applied to a tree graph and //! per-node file graphs (spec §8.3), with materialization (spec §9.5, §11). use crate::cbor::{self, Value}; use crate::graph::{AtomKey, DepOracle, FileGraph, Materialized, Vertex}; use crate::hash::KeyId; use crate::hash::{ChangeHash, ObjectRef}; use crate::ids::NodeId; use crate::objects::{ self as o, AtomRef, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, ObjectError, TreeOp, }; use crate::tree::{TreeGraph, TreeView}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::{Arc, Mutex}; /// Checkpoint payload version 2 (spec §11): file graphs by reference. pub const CHECKPOINT_INDEX_VERSION: u64 = 2; /// A file graph encoded in fewer bytes stays inline in a version 2 index. pub const INLINE_GRAPH_LIMIT: usize = 2048; #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum StateError { #[error("change {1} depends on {0}, which is not in the state")] MissingDep(ChangeHash, ChangeHash), } /// One `Replace` edit: `(change, old blob, new blob)`. type ReplaceRecord = (ChangeHash, Option, Option); /// What a state remembers about a change: everything but its operations, /// which live in the graphs once applied (and in the store). #[derive(Clone, Debug, PartialEq, Eq)] pub struct ChangeMeta { pub change_id: crate::ids::ChangeId, pub deps: Vec, pub author: KeyId, pub hlc: Hlc, pub message: String, pub kind: ChangeKind, } impl ChangeMeta { pub fn of(c: &Change) -> ChangeMeta { ChangeMeta { change_id: c.change_id, deps: c.deps.clone(), author: c.author, hlc: c.hlc, message: c.message.clone(), kind: c.kind, } } } #[derive(Default)] pub struct State { changes: HashMap, tree: TreeGraph, /// Shared between clones: a clone copies a graph only when an edit /// changes it (`Arc::make_mut`), so keeping several states that differ /// by a few changes costs little more than one. files: HashMap>, replaces: HashMap>, /// Memoised transitive dependencies. A mutex, not a `RefCell`, so a /// loaded state can be shared across threads by a host that caches it. closure: Mutex>>>, /// `None` for a full state. For a history-only state (loaded for its /// changes and tree), the file graphs not built yet, by node: `files` /// holds only those loaded with [`State::load_graphs`]. deferred: Option>, } /// A stored insert's text blob and line count. type TextRef = (ObjectRef, u32); /// A file graph a history-only state has not built: its base from a /// version 2 checkpoint, if any, and the edits of later changes in the /// order they were applied (spec §11). Building it later gives the same /// graph, since graph construction does not depend on order (§8). #[derive(Clone, Default)] struct Deferred { base: Option, edits: Vec<(ChangeHash, Vec)>, /// The text blob and line count of each insert in `edits` left without /// its lines, in order: read when the graph is built. texts: Vec<(ObjectRef, u32)>, } #[derive(Clone)] enum DeferredBase { Inline(Value), Blob(ObjectRef), } impl Clone for State { fn clone(&self) -> State { State { changes: self.changes.clone(), tree: self.tree.clone(), files: self.files.clone(), replaces: self.replaces.clone(), closure: Mutex::new(self.closure.lock().unwrap().clone()), deferred: self.deferred.clone(), } } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum FileContent { Text { bytes: Vec, materialized: Materialized, }, /// Live blobs; more than one is a replace conflict (spec §9.3). Opaque { blobs: Vec, }, Dir, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct FileState { pub node: NodeId, pub kind: NodeKind, pub mode: Mode, pub content: FileContent, } impl FileState { pub fn is_conflicted(&self) -> bool { match &self.content { FileContent::Text { materialized, .. } => materialized.is_conflicted(), FileContent::Opaque { blobs } => blobs.len() > 1, FileContent::Dir => false, } } } /// See `State::conflict_regions`. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ConflictRegions { pub plain: Vec<(AtomKey, Vec)>, pub region_atoms: Vec, pub contributors: Vec, } /// The whole tree of a state, materialized. #[derive(Clone, Debug, Default)] pub struct Snapshot { pub tree: TreeView, pub files: BTreeMap, /// Text files left unrendered by [`State::materialize_except`]: their /// `bytes` are empty and they are known not to be conflicted. pub unrendered: BTreeSet, } impl Snapshot { pub fn is_conflicted(&self) -> bool { self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted()) } } fn vertex(r: AtomRef) -> Vertex { match r { AtomRef::Start => Vertex::Start, AtomRef::End => Vertex::End, AtomRef::Atom { change, index } => Vertex::Atom((change, index)), } } /// Replace self references in a tree op with the concrete change hash. pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp { match op { TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode { node: *node, placement: placement.resolve(me), }, TreeOp::Move { node, old, parent, name, } => TreeOp::Move { node: *node, old: old.resolve(me), parent: *parent, name: name.clone(), }, TreeOp::SetMode { node, old, mode } => TreeOp::SetMode { node: *node, old: old.resolve(me), mode: *mode, }, add @ TreeOp::AddNode { .. } => add.clone(), } } /// Apply one change's edits of one file (inserts and deletes; replaces /// live beside the graphs) to that file's graph. fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec) { let mut next = 0u32; for e in edits { match e { Edit::Insert { after, before, lines, .. } => { let first = next; next += lines.len() as u32; g.insert_owned( h, first, vertex(after.resolve(h)), vertex(before.resolve(h)), lines, ); } Edit::Delete { atoms, .. } => { for r in atoms { g.delete(h, &r.resolve(h)); } } Edit::Replace { .. } => {} } } } impl State { pub fn new() -> Self { Self::default() } /// An empty state for history only: changes and tree are kept, file /// edits are recorded but no file graph is built until /// [`State::load_graphs`] asks for it. For log and other commands that /// need no file contents, or only a few files. pub fn new_history_only() -> Self { State { deferred: Some(HashMap::new()), ..Self::default() } } /// Whether this state builds file graphs only when asked /// ([`State::new_history_only`]), even if it has none waiting. pub fn is_history_only(&self) -> bool { self.deferred.is_some() } /// Whether this state holds every file graph. pub fn is_full(&self) -> bool { self.deferred.as_ref().is_none_or(|d| d.is_empty()) } /// The graph of `node`, which must be loaded: asking a history-only /// state for a graph it has not built is a bug, never an empty file. fn graph(&self, node: &NodeId) -> Option<&FileGraph> { if let Some(d) = &self.deferred { assert!( !d.contains_key(node), "file graph {} of a history-only state was not loaded (State::load_graphs)", node.short(12) ); } self.files.get(node).map(|g| g.as_ref()) } /// Operations over every file need every graph. fn require_full(&self, what: &str) { assert!( self.is_full(), "{what} needs every file graph; this state was loaded for history only" ); } /// Build the graphs of `nodes` in a history-only state: from their /// checkpoint base (blobs read in one batch through `load`) and their /// deferred edits. Nodes already built, or with no graph, are skipped. pub fn load_graphs( &mut self, nodes: &[NodeId], load: impl FnOnce(&[ObjectRef]) -> Result>, ObjectError>, ) -> Result<(), ObjectError> { let Some(deferred) = self.deferred.as_mut() else { return Ok(()); }; let mut taken: Vec<(NodeId, Deferred)> = nodes .iter() .filter_map(|n| deferred.remove(n).map(|d| (*n, d))) .collect(); let mut refs: Vec = taken .iter() .filter_map(|(_, d)| match &d.base { Some(DeferredBase::Blob(r)) => Some(*r), _ => None, }) .collect(); // Text blobs of inserts read without their lines, after the bases. let bases = refs.len(); refs.extend( taken .iter() .flat_map(|(_, d)| d.texts.iter().map(|(r, _)| *r)), ); let mut blobs = if refs.is_empty() { Vec::new() } else { load(&refs)? }; if blobs.len() != refs.len() { return Err(ObjectError::Schema("graph blobs: wrong count".into())); } let mut texts = blobs.split_off(bases).into_iter(); let mut blobs = blobs.into_iter(); // Pair each graph with its blob, then build them all in parallel: // graphs are independent. let mut work: Vec<(NodeId, Deferred, Option>)> = Vec::with_capacity(taken.len()); for (node, mut d) in taken.drain(..) { // Fill in the lines of inserts read without them, in order. let mut want = std::mem::take(&mut d.texts).into_iter(); for (_, edits) in d.edits.iter_mut() { for e in edits.iter_mut() { if let Edit::Insert { lines, .. } = e { if lines.is_empty() { let (_, count) = want.next().ok_or_else(|| { ObjectError::Schema("an insert's text is missing".into()) })?; let content = texts.next().ok_or_else(|| { ObjectError::Schema("text blobs: wrong count".into()) })?; *lines = crate::objects::text_lines(&content, count)?; } } } } let bytes = match &d.base { Some(DeferredBase::Blob(_)) => Some( blobs .next() .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?, ), _ => None, }; work.push((node, d, bytes)); } use rayon::prelude::*; let built: Vec<(NodeId, FileGraph)> = work .into_par_iter() .map(|(node, mut d, bytes)| { let mut graph = match (d.base.take(), bytes) { (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?, (Some(DeferredBase::Blob(_)), Some(bytes)) => { FileGraph::from_value(&cbor::decode(&bytes)?)? } _ => FileGraph::default(), }; for (h, edits) in std::mem::take(&mut d.edits) { apply_file_edits(&mut graph, h, edits); } Ok((node, graph)) }) .collect::>()?; self.files .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g)))); Ok(()) } /// Build every graph a history-only state has not built, making it full. pub fn load_all_graphs( &mut self, load: impl FnOnce(&[ObjectRef]) -> Result>, ObjectError>, ) -> Result<(), ObjectError> { let nodes: Vec = match &self.deferred { Some(d) => d.keys().copied().collect(), None => return Ok(()), }; self.load_graphs(&nodes, load)?; self.deferred = None; Ok(()) } /// A key for the graph of `node` in a history-only state that has not /// built it: equal keys mean equal graphs, so equal renderings (a /// rendering depends only on the graph and on the changes' own /// immutable metadata). It names the node, its checkpoint base (a blob, /// an inline value, or none) and the set of later changes that edited /// the file. /// `None` for a full state or a graph already built. pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> { let deferred = self.deferred.as_ref()?; if self.files.contains_key(node) { return None; } let mut h = blake3::Hasher::new(); h.update(b"oxy graph key 1\0"); // A change's edits are applied per node: the node is part of it. h.update(&node.0); let Some(d) = deferred.get(node) else { // Never edited: the empty graph. h.update(&[0]); return Some(*h.finalize().as_bytes()); }; match &d.base { None => h.update(&[0]), Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0), Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)), }; let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect(); changes.sort(); changes.dedup(); h.update(&(changes.len() as u64).to_le_bytes()); for c in changes { h.update(&c.0); } Some(*h.finalize().as_bytes()) } pub fn len(&self) -> usize { self.changes.len() } pub fn is_empty(&self) -> bool { self.changes.is_empty() } pub fn contains(&self, h: &ChangeHash) -> bool { self.changes.contains_key(h) } pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> { self.changes.get(h) } pub fn changes(&self) -> impl Iterator { self.changes.iter() } pub fn tree(&self) -> &TreeGraph { &self.tree } pub fn file(&self, node: &NodeId) -> Option<&FileGraph> { self.graph(node) } /// Add a change whose dependencies are already present. pub fn add(&mut self, change: Change) -> Result { let h = change.hash(); if self.changes.contains_key(&h) { return Ok(h); } for d in &change.deps { if !self.changes.contains_key(d) { return Err(StateError::MissingDep(*d, h)); } } Ok(self.add_unchecked(change)) } /// Add a change in any order; call `validate` once all are in. pub fn add_unchecked(&mut self, change: Change) -> ChangeHash { let h = change.hash(); self.add_known(h, change, Vec::new()); h } /// Add a change read from the store under hash `h`, without hashing it /// again (for a version 2 change that means chunking all its text). /// `texts` names, in order, the inserts left without their lines (see /// [`crate::store::Store::get_change_lazy`]); only a history-only state /// takes them, and only for graphs it has not built. pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<(ObjectRef, u32)>) { if self.changes.contains_key(&h) { return; } let meta = ChangeMeta::of(&change); self.apply_with(h, change, texts); self.changes.insert(h, meta); self.closure.lock().unwrap().clear(); } // ------------------------------------------------------------ checkpoints (spec §11) /// Serialize the whole state in payload version 1: change metadata, /// tree, file graphs, replaces, all in one value (spec §11). pub fn checkpoint_payload(&self) -> Vec { self.require_full("a checkpoint"); let mut nodes: Vec<&NodeId> = self.files.keys().collect(); nodes.sort(); let files = Value::Array( nodes .into_iter() .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()])) .collect(), ); cbor::encode(&self.payload_value(o::FORMAT_VERSION, files)) } /// Each file graph encoded on its own, by node, for a version 2 payload /// (spec §11): the graphs of large files become blobs of their own. pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec)> { use rayon::prelude::*; self.require_full("a checkpoint"); let mut nodes: Vec<(&NodeId, &FileGraph)> = self.files.iter().map(|(n, g)| (n, g.as_ref())).collect(); nodes.sort_by_key(|(n, _)| **n); nodes .into_par_iter() .map(|(n, g)| (*n, cbor::encode(&g.to_value()))) .collect() } /// The payload version 2 index for the graphs of /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by /// `blob_of` (the ObjectRef of the blob holding its encoding). pub fn checkpoint_index( &self, graphs: &[(NodeId, Vec)], mut blob_of: impl FnMut(&[u8]) -> ObjectRef, ) -> Vec { let files = Value::Array( graphs .iter() .map(|(n, enc)| { let entry = if enc.len() < INLINE_GRAPH_LIMIT { cbor::decode(enc).expect("an encoded graph decodes") } else { Value::Bytes(blob_of(enc).0.to_vec()) }; Value::Array(vec![Value::Bytes(n.0.to_vec()), entry]) }) .collect(), ); cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files)) } /// The payload map around `files`: changes, tree and replaces as in version 1. fn payload_value(&self, version: u64, files: Value) -> Value { let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect(); hashes.sort(); let changes = Value::Array( hashes .into_iter() .map(|h| { let m = &self.changes[h]; Value::Array(vec![ Value::Bytes(h.0.to_vec()), Value::Bytes(m.change_id.0.to_vec()), Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()), Value::Text(m.message.clone()), Value::Uint(m.hlc.wall_ms), Value::Uint(m.hlc.logical as u64), Value::Uint(m.kind.tag()), Value::Bytes(m.author.0.to_vec()), ]) }) .collect(), ); let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect(); rnodes.sort(); let opt = |o: &Option| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null); let replaces = Value::Array( rnodes .into_iter() .map(|n| { Value::Array(vec![ Value::Bytes(n.0.to_vec()), Value::Array( self.replaces[n] .iter() .map(|(c, o, nw)| { Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)]) }) .collect(), ), ]) }) .collect(), ); Value::map([ (0, Value::Uint(version)), (1, changes), (2, self.tree.to_value()), (3, files), (4, replaces), ]) } /// Decode a version 1 payload (the whole state in one value). A /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`]. pub fn from_checkpoint_payload(bytes: &[u8]) -> Result { State::from_checkpoint(bytes, |_| { Err(ObjectError::Schema( "a version 2 checkpoint needs its graph blobs".into(), )) }) } /// Decode a checkpoint payload of either version (spec §11). For /// version 2, `load` returns the contents of the named graph blobs, in /// order; the graphs are then decoded in parallel. pub fn from_checkpoint( bytes: &[u8], load: impl FnOnce(&[ObjectRef]) -> Result>, ObjectError>, ) -> Result { use rayon::prelude::*; let v = cbor::decode(bytes)?; let m = o::map(&v, "checkpoint payload")?; let version = o::uint(o::field(m, 0, "version")?, "version")?; if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION { return Err(ObjectError::Schema(format!( "checkpoint payload version {version} is not supported" ))); } let mut st = State::payload_common(m)?; let entries = o::array(o::field(m, 3, "files")?, "files")?; let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len()); for f in entries { let e = o::array(f, "file")?; if e.len() != 2 { return Err(ObjectError::Schema("file: expected [node, graph]".into())); } let node = NodeId::from_slice(o::bytes(&e[0], "node")?) .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?; parsed.push((node, &e[1])); } // Version 2 names large graphs by blob: fetch those in one batch. let mut fetched: HashMap> = HashMap::new(); if version == CHECKPOINT_INDEX_VERSION { let wanted: Vec<(NodeId, ObjectRef)> = parsed .iter() .filter(|(_, e)| matches!(e, Value::Bytes(_))) .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?))) .collect::>()?; if !wanted.is_empty() { let refs: Vec = wanted.iter().map(|(_, r)| *r).collect(); let contents = { let _t = crate::timing::phase("load: graph blobs read"); load(&refs)? }; if contents.len() != refs.len() { return Err(ObjectError::Schema("graph blobs: wrong count".into())); } fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents)); } } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) { return Err(ObjectError::Schema( "a version 1 payload holds graphs inline".into(), )); } // File graphs are independent; decode and build them in parallel. let graphs = parsed .par_iter() .map(|(node, entry)| { let graph = match fetched.get(node) { Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?, None => FileGraph::from_value(entry)?, }; Ok((*node, graph)) }) .collect::, ObjectError>>()?; st.files .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g)))); Ok(st) } /// The graph blobs a payload names: empty for version 1. pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result, ObjectError> { let v = cbor::decode(bytes)?; let m = o::map(&v, "checkpoint payload")?; let mut out = Vec::new(); for f in o::array(o::field(m, 3, "files")?, "files")? { if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) { out.push(o::oref(entry, "graph blob")?); } } Ok(out) } /// Decode a checkpoint payload for history only: a version 2 payload's /// graphs are noted, not read or built, and come later through /// [`State::load_graphs`]. A version 1 payload holds them inline and is /// decoded in full. pub fn from_checkpoint_history(bytes: &[u8]) -> Result { let v = cbor::decode(bytes)?; let m = o::map(&v, "checkpoint payload")?; let version = o::uint(o::field(m, 0, "version")?, "version")?; if version != CHECKPOINT_INDEX_VERSION { return State::from_checkpoint_payload(bytes); } let mut st = State::payload_common(m)?; let mut deferred = HashMap::new(); for f in o::array(o::field(m, 3, "files")?, "files")? { let e = o::array(f, "file")?; if e.len() != 2 { return Err(ObjectError::Schema("file: expected [node, graph]".into())); } let node = NodeId::from_slice(o::bytes(&e[0], "node")?) .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?; let base = match &e[1] { Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?), other => DeferredBase::Inline(other.clone()), }; deferred.insert( node, Deferred { base: Some(base), edits: Vec::new(), texts: Vec::new(), }, ); } st.deferred = Some(deferred); Ok(st) } /// Changes, tree and replaces of a payload of either version. fn payload_common(m: &BTreeMap) -> Result { let mut st = State::new(); for c in o::array(o::field(m, 1, "changes")?, "changes")? { let e = o::array(c, "change meta")?; if e.len() != 8 { return Err(ObjectError::Schema("change meta: expected 8 fields".into())); } let hash = o::oref(&e[0], "hash")?; let meta = ChangeMeta { change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?) .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?, deps: o::array(&e[2], "deps")? .iter() .map(|d| o::oref(d, "dep")) .collect::, _>>()?, message: o::text(&e[3], "message")?.to_owned(), hlc: Hlc { wall_ms: o::uint(&e[4], "wall")?, logical: o::u32_(&e[5], "logical")?, }, kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?, author: o::oref(&e[7], "author")?, }; st.changes.insert(hash, meta); } st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?; let opt = |v: &Value| -> Result, ObjectError> { if v.is_null() { Ok(None) } else { o::oref(v, "blob").map(Some) } }; for r in o::array(o::field(m, 4, "replaces")?, "replaces")? { let e = o::array(r, "replace")?; if e.len() != 2 { return Err(ObjectError::Schema( "replace: expected [node, records]".into(), )); } let node = NodeId::from_slice(o::bytes(&e[0], "node")?) .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?; let mut recs = Vec::new(); for rec in o::array(&e[1], "records")? { let x = o::array(rec, "record")?; if x.len() != 3 { return Err(ObjectError::Schema("record: expected 3 fields".into())); } recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?)); } st.replaces.insert(node, recs); } Ok(st) } pub fn validate(&self) -> Result<(), StateError> { for (h, c) in &self.changes { for d in &c.deps { if !self.changes.contains_key(d) { return Err(StateError::MissingDep(*d, *h)); } } } Ok(()) } fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<(ObjectRef, u32)>) { for (i, op) in c.tree_ops.iter().enumerate() { self.tree.apply(h, i as u32, &resolve_tree_op(op, h)); } if let Some(deferred) = self.deferred.as_mut() { // History only: edits of files not built wait, grouped per file, // with the texts of inserts read without their lines. let mut texts = texts.into_iter(); let mut per_node: HashMap, Vec)> = HashMap::new(); for e in c.edits { match e { Edit::Replace { node, old, new } => { self.replaces.entry(node).or_default().push((h, old, new)) } e => { let slot = per_node.entry(e.node()).or_default(); if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) { slot.1.extend(texts.next()); } slot.0.push(e); } } } for (node, (edits, node_texts)) in per_node { match self.files.get_mut(&node) { Some(g) => { assert!( node_texts.is_empty(), "a change read without its text applied to a built graph" ); apply_file_edits(Arc::make_mut(g), h, edits) } None => { let d = deferred.entry(node).or_default(); d.edits.push((h, edits)); d.texts.extend(node_texts); } } } return; } assert!( texts.is_empty(), "a change read without its text applied to a full state" ); let mut counters: HashMap = HashMap::new(); for e in c.edits { match e { Edit::Insert { node, after, before, lines, } => { let idx = counters.entry(node).or_default(); let first = *idx; *idx += lines.len() as u32; Arc::make_mut(self.files.entry(node).or_default()).insert_owned( h, first, vertex(after.resolve(h)), vertex(before.resolve(h)), lines, ); } Edit::Delete { node, atoms } => { let g = Arc::make_mut(self.files.entry(node).or_default()); for r in atoms { g.delete(h, &r.resolve(h)); } } Edit::Replace { node, old, new } => { self.replaces.entry(node).or_default().push((h, old, new)); } } } } /// Transitive dependencies of `h`, excluding `h` itself. pub fn closure(&self, h: &ChangeHash) -> Arc> { if let Some(c) = self.closure.lock().unwrap().get(h) { return c.clone(); } let mut out = HashSet::new(); let mut stack: Vec = self .changes .get(h) .map(|c| c.deps.clone()) .unwrap_or_default(); while let Some(d) = stack.pop() { if out.insert(d) { if let Some(c) = self.changes.get(&d) { stack.extend(c.deps.iter().copied()); } } } let rc = Arc::new(out); self.closure.lock().unwrap().insert(*h, rc.clone()); rc } /// Changes that no other change depends on directly, sorted. pub fn heads(&self) -> Vec { let depended: HashSet<&ChangeHash> = self.changes.values().flat_map(|c| c.deps.iter()).collect(); let mut heads: Vec = self .changes .keys() .filter(|h| !depended.contains(h)) .copied() .collect(); heads.sort(); heads } /// Maximal elements among `hashes` (those not in the closure of another), /// sorted. One walk down from all of them at once: whatever the walk /// reaches is below some other element. Linear in the changes reached, /// where comparing every pair's closures was quadratic in the number /// of heads, which a bookmark of independent changes has many of. pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec { let set: BTreeSet = hashes.iter().copied().collect(); let mut below: HashSet = HashSet::new(); let mut stack: Vec = set .iter() .filter_map(|h| self.changes.get(h)) .flat_map(|c| c.deps.iter().copied()) .collect(); while let Some(d) = stack.pop() { if below.insert(d) { if let Some(c) = self.changes.get(&d) { stack.extend(c.deps.iter().copied()); } } } set.into_iter().filter(|h| !below.contains(h)).collect() } pub fn materialize_file(&self, node: &NodeId) -> Materialized { self.graph(node) .map(|g| g.materialize(self)) .unwrap_or_default() } /// Live lines of a text node in materialized order. pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec)> { let Some(g) = self.graph(node) else { return vec![]; }; let m = g.materialize(self); m.live_atoms() .into_iter() .map(|a| (a, g.content(&a).unwrap_or_default().to_vec())) .collect() } /// Live blobs of an opaque node: every `new` that no later `Replace` retired. pub fn live_blobs(&self, node: &NodeId) -> Vec { let mut live: Vec = self .live_replaces(node) .into_iter() .map(|(_, n)| n) .collect(); live.sort(); live.dedup(); live } /// The replace records whose blob is live, with the change that set it /// (spec §9.3). A record's blob is superseded by a later replacement of /// that blob: one whose change depends on the record's change, as every /// replacement depends on the change that made its old blob current /// (§8.1). Two replacements that do not know each other both stay live /// (a replace conflict), and a file reverted to an earlier blob keeps it. /// A replacement without that dependency, from before the rule, is read /// as before: it supersedes every record that did not come after it. pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> { let Some(rs) = self.replaces.get(node) else { return vec![]; }; let knows_its_old = |s: &ChangeHash, old: &ObjectRef| { rs.iter() .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q)) }; rs.iter() .filter_map(|(c, _, n)| n.map(|n| (*c, n))) .filter(|(c, n)| { !rs.iter().any(|(s, o, _)| { s != c && *o == Some(*n) && (self.closure(s).contains(c) || (!knows_its_old(s, n) && !self.closure(c).contains(s))) }) }) .collect() } /// Short label for conflict markers: `changeid-prefix "message"`. pub fn label(&self, h: &ChangeHash) -> String { match self.changes.get(h) { Some(c) => format!( "{} \"{}\"", c.change_id.short(8), c.message.lines().next().unwrap_or("") ), None => format!("#{}", h.short(12)), } } /// For resolving a conflicted text node (spec §9.6): the live atoms that /// are not part of any conflict region in order, every live atom that is /// part of a region, and every change that contributed to a region. /// The changes that introduced the live blobs of an opaque node, for a /// replace conflict (spec §9.3). pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec { let mut out: Vec = Vec::new(); for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) { if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) { out.push(*h); } } out.sort(); out } pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions { let mut out = ConflictRegions::default(); let Some(g) = self.graph(node) else { return out; }; let m = g.materialize(self); let mut contributors = BTreeSet::new(); for seg in &m.segments { match seg { crate::graph::Segment::Lines(atoms) => { for a in atoms { out.plain .push((*a, g.content(a).unwrap_or_default().to_vec())); } } crate::graph::Segment::Conflict(sides) => { for side in sides { for a in side { out.region_atoms.push(*a); contributors.insert(a.0); } } } crate::graph::Segment::Zombie { deleted, inserted } => { for a in deleted { contributors.insert(a.0); contributors.extend(g.deleters(a).copied()); } for a in inserted { out.region_atoms.push(*a); contributors.insert(a.0); } } } } out.contributors = contributors.into_iter().collect(); out } pub fn render_file(&self, node: &NodeId) -> (Vec, Materialized) { let Some(g) = self.graph(node) else { return (Vec::new(), Materialized::default()); }; let m = g.materialize(self); let bytes = g.render(&m, &|h| self.label(h)); (bytes, m) } /// Every file rendered, in parallel: files are independent, and /// rendering them is most of a snapshot's cost in a large tree. pub fn materialize(&self) -> Snapshot { use rayon::prelude::*; self.require_full("materializing a state"); let tree = self.tree.view(); let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect(); let rendered: Vec<(String, FileState)> = entries .par_iter() .map(|(path, e)| (path.to_string(), self.file_state(e))) .collect(); let files: BTreeMap = rendered.into_iter().collect(); Snapshot { tree, files, unrendered: BTreeSet::new(), } } /// Like [`State::materialize`], leaving the text files of nodes in /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other /// file's graph must be loaded. For a caller that already knows those /// files are unchanged and not conflicted. pub fn materialize_except(&self, skip: &HashSet) -> Snapshot { use rayon::prelude::*; let tree = self.tree.view(); let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect(); let rendered: Vec<(String, FileState, bool)> = entries .par_iter() .map(|(path, e)| { if e.kind == NodeKind::File && !e.mode.opaque && skip.contains(&e.node) { let f = FileState { node: e.node, kind: e.kind, mode: e.mode, content: FileContent::Text { bytes: Vec::new(), materialized: Materialized::default(), }, }; (path.to_string(), f, true) } else { (path.to_string(), self.file_state(e), false) } }) .collect(); let mut files = BTreeMap::new(); let mut unrendered = BTreeSet::new(); for (p, f, skipped) in rendered { if skipped { unrendered.insert(p.clone()); } files.insert(p, f); } Snapshot { tree, files, unrendered, } } fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState { { let content = match e.kind { NodeKind::Dir => FileContent::Dir, NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque { blobs: self.live_blobs(&e.node), }, NodeKind::File if e.mode.opaque => FileContent::Opaque { blobs: self.live_blobs(&e.node), }, NodeKind::File => { let (bytes, materialized) = self.render_file(&e.node); FileContent::Text { bytes, materialized, } } }; FileState { node: e.node, kind: e.kind, mode: e.mode, content, } } } } impl DepOracle for State { fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool { a == b || self.closure(a).contains(b) } } #[cfg(test)] mod tests { use super::*; use crate::ids::ChangeId; use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef}; fn change(deps: Vec, tree_ops: Vec, edits: Vec) -> Change { let mut c = Change { version: crate::objects::CHANGE_VERSION, change_id: ChangeId::random(), deps, author: ObjectRef::ZERO, hlc: Hlc { wall_ms: 1, logical: 0, }, message: "m".into(), tree_ops, edits, kind: ChangeKind::Normal, }; c.normalize(); c } #[test] fn build_edit_and_materialize() { let mut st = State::new(); let f = NodeId::random(); let c1 = change( vec![], vec![TreeOp::AddNode { node: f, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: "a.txt".into(), }], vec![Edit::Insert { node: f, after: AtomRef::Start, before: AtomRef::End, lines: vec![b"one\n".to_vec(), b"two\n".to_vec()], }], ); let h1 = st.add(c1).unwrap(); // Depends on h1: append a line and delete "one". let c2 = change( vec![h1], vec![], vec![ Edit::Delete { node: f, atoms: vec![AtomRange { change: h1, from: 0, to: 1, }], }, Edit::Insert { node: f, after: AtomRef::Atom { change: h1, index: 1, }, before: AtomRef::End, lines: vec![b"three\n".to_vec()], }, ], ); let h2 = st.add(c2).unwrap(); assert_eq!(st.heads(), vec![h2]); assert!(st.depends_on(&h2, &h1)); assert!(!st.depends_on(&h1, &h2)); let snap = st.materialize(); assert!(!snap.is_conflicted()); let a = &snap.files["a.txt"]; assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n")); assert_eq!(st.live_lines(&f).len(), 2); } #[test] fn missing_dependency_is_rejected() { let mut st = State::new(); let c = change(vec![ObjectRef([1; 32])], vec![], vec![]); assert!(matches!(st.add(c), Err(StateError::MissingDep(..)))); } #[test] fn self_references_and_multi_insert_indexing() { let mut st = State::new(); let f = NodeId::random(); let me = OpRef { change: ObjectRef::ZERO, index: 0, }; let c1 = change( vec![], vec![ TreeOp::AddNode { node: f, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: "x".into(), }, TreeOp::SetMode { node: f, old: me, mode: Mode { exec: true, opaque: false, }, }, ], vec![ Edit::Insert { node: f, after: AtomRef::Start, before: AtomRef::End, lines: vec![b"a\n".to_vec(), b"c\n".to_vec()], }, // Insert between the two lines just inserted, using self references. Edit::Insert { node: f, after: AtomRef::Atom { change: ObjectRef::ZERO, index: 0, }, before: AtomRef::Atom { change: ObjectRef::ZERO, index: 1, }, lines: vec![b"b\n".to_vec()], }, ], ); st.add(c1).unwrap(); let snap = st.materialize(); let x = &snap.files["x"]; assert_eq!( x.mode, Mode { exec: true, opaque: false } ); assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n")); } #[test] fn opaque_replace_and_conflict() { let mut st = State::new(); let f = NodeId::random(); let b1 = ObjectRef([1; 32]); let b2 = ObjectRef([2; 32]); let b3 = ObjectRef([3; 32]); let h1 = st .add(change( vec![], vec![TreeOp::AddNode { node: f, kind: NodeKind::File, mode: Mode::OPAQUE, parent: NodeId::ROOT, name: "img".into(), }], vec![Edit::Replace { node: f, old: None, new: Some(b1), }], )) .unwrap(); assert_eq!(st.live_blobs(&f), vec![b1]); st.add(change( vec![h1], vec![], vec![Edit::Replace { node: f, old: Some(b1), new: Some(b2), }], )) .unwrap(); st.add(change( vec![h1], vec![], vec![Edit::Replace { node: f, old: Some(b1), new: Some(b3), }], )) .unwrap(); let snap = st.materialize(); assert!(snap.is_conflicted()); assert!( matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3]) ); } #[test] fn checkpoint_payload_round_trip_and_replay() { let mut st = State::new(); let f = NodeId::random(); let h1 = st .add(change( vec![], vec![TreeOp::AddNode { node: f, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: "a".into(), }], vec![Edit::Insert { node: f, after: AtomRef::Start, before: AtomRef::End, lines: vec![b"1\n".to_vec(), b"2\n".to_vec()], }], )) .unwrap(); let h2 = st .add(change( vec![h1], vec![], vec![Edit::Delete { node: f, atoms: vec![AtomRange { change: h1, from: 0, to: 1, }], }], )) .unwrap(); let payload = st.checkpoint_payload(); let back = State::from_checkpoint_payload(&payload).unwrap(); assert_eq!(back.len(), 2); assert_eq!(back.heads(), vec![h2]); assert_eq!(back.get(&h1).unwrap().message, "m"); assert_eq!(back.checkpoint_payload(), payload, "deterministic"); // Replaying a further change onto the restored state equals a full build. let c3 = change( vec![h2], vec![], vec![Edit::Insert { node: f, after: AtomRef::Atom { change: h1, index: 1, }, before: AtomRef::End, lines: vec![b"3\n".to_vec()], }], ); let mut full = st.clone(); full.add(c3.clone()).unwrap(); let mut restored = back; restored.add(c3).unwrap(); let (a, b) = (full.materialize(), restored.materialize()); assert_eq!( a.files.keys().collect::>(), b.files.keys().collect::>() ); assert_eq!(a.files["a"].content, b.files["a"].content); assert!( matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n") ); assert!(State::from_checkpoint_payload(b"nonsense").is_err()); } /// History-only states (O10f): the same state as a full load once its /// graphs are built, by replay and from a version 2 checkpoint with /// later changes; unloaded graphs are never read as empty. #[test] fn graph_keys_change_exactly_when_a_graph_does() { let (f, g) = (NodeId::random(), NodeId::random()); let add = |node: NodeId, name: &str| TreeOp::AddNode { node, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: name.into(), }; let ins = |node: NodeId, line: &[u8]| Edit::Insert { node, after: AtomRef::Start, before: AtomRef::End, lines: vec![line.to_vec()], }; let c1 = change( vec![], vec![add(f, "f"), add(g, "g")], vec![ins(f, b"f\n"), ins(g, b"g\n")], ); let h1 = c1.hash(); let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]); let h2 = c2.hash(); let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]); let load = |cs: &[&Change]| { let mut st = State::new_history_only(); for c in cs { st.add((*c).clone()).unwrap(); } st }; let s1 = load(&[&c1]); let s2 = load(&[&c1, &c2]); let s3 = load(&[&c1, &c2, &c3]); let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap(); assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key"); assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it"); assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it"); assert_ne!(key(&s2, &f), key(&s3, &f)); assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ"); let mut built = load(&[&c1]); built.load_graphs(&[f], |_| unreachable!()).unwrap(); assert!(built.graph_key(&f).is_none(), "a built graph has no key"); let mut full = State::new(); full.add(c1.clone()).unwrap(); assert!(full.graph_key(&f).is_none(), "nor has a full state"); // Through a version 2 checkpoint of c1, keys name its graph blobs // or inline values: stable across loads, changed by later edits. let graphs = full.checkpoint_file_graphs(); let index = full.checkpoint_index(&graphs, |enc| { crate::hash::hash_object(crate::hash::ObjectType::Blob, enc) }); let cp = |extra: &[&Change]| { let mut st = State::from_checkpoint_history(&index).unwrap(); for c in extra { st.add((*c).clone()).unwrap(); } st }; assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f)); assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f)); assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g)); assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f)); // Partial rendering: skipped files are listed and empty, the others // render as in a full state. let mut part = load(&[&c1, &c2]); part.load_graphs(&[g], |_| unreachable!()).unwrap(); let snap = part.materialize_except(&[f].into_iter().collect()); assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect()); let mut whole = State::new(); whole.add(c1.clone()).unwrap(); whole.add(c2.clone()).unwrap(); assert_eq!(snap.files["g"], whole.materialize().files["g"]); assert!( matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty()) ); } #[test] fn history_only_states_build_the_same_graphs_on_demand() { let small = NodeId::random(); let big = NodeId::random(); let add = |node: NodeId, name: &str| TreeOp::AddNode { node, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: name.into(), }; let lines: Vec> = (0..300) .map(|i| format!("line {i}\n").into_bytes()) .collect(); let c1 = change( vec![], vec![add(small, "small"), add(big, "big")], vec![ Edit::Insert { node: small, after: AtomRef::Start, before: AtomRef::End, lines: vec![b"x\n".to_vec()], }, Edit::Insert { node: big, after: AtomRef::Start, before: AtomRef::End, lines, }, ], ); let h1 = c1.hash(); let c2 = change( vec![h1], vec![], vec![ Edit::Delete { node: big, atoms: vec![AtomRange { change: h1, from: 2, to: 9, }], }, Edit::Insert { node: big, after: AtomRef::Atom { change: h1, index: 20, }, before: AtomRef::Atom { change: h1, index: 21, }, lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()], }, Edit::Insert { node: small, after: AtomRef::Atom { change: h1, index: 0, }, before: AtomRef::End, lines: vec![b"y\n".to_vec()], }, ], ); let h2 = c2.hash(); let c3 = change( vec![h2], vec![], vec![Edit::Delete { node: small, atoms: vec![AtomRange { change: h1, from: 0, to: 1, }], }], ); let mut full = State::new(); for c in [&c1, &c2, &c3] { full.add(c.clone()).unwrap(); } // By replay: nothing built until asked, then exactly the full graphs. let mut hist = State::new_history_only(); for c in [&c1, &c2, &c3] { hist.add(c.clone()).unwrap(); } assert!(!hist.is_full() && hist.files.is_empty(), "no graph built"); assert_eq!(hist.len(), 3); hist.load_graphs(&[big], |_| unreachable!("no checkpoint")) .unwrap(); assert_eq!( hist.render_file(&big).0, full.render_file(&big).0, "one file on its own" ); assert!(!hist.is_full()); hist.load_graphs(&[small, big], |_| unreachable!()).unwrap(); assert!(hist.is_full()); assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload()); // From a version 2 checkpoint of c1+c2, then c3 applied later. let mut base = State::new(); base.add(c1.clone()).unwrap(); base.add(c2.clone()).unwrap(); let graphs = base.checkpoint_file_graphs(); let mut blobs: HashMap> = HashMap::new(); let index = base.checkpoint_index(&graphs, |enc| { let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc); blobs.insert(r, enc.to_vec()); r }); let mut from_cp = State::from_checkpoint_history(&index).unwrap(); from_cp.add(c3.clone()).unwrap(); assert!(!from_cp.is_full()); let mut fetched = 0; from_cp .load_graphs(&[small, big], |refs| { fetched += refs.len(); refs.iter() .map(|r| { blobs .get(r) .cloned() .ok_or_else(|| ObjectError::Schema("missing".into())) }) .collect() }) .unwrap(); assert_eq!( fetched, 1, "the large graph's blob, in one batch; the small one was inline" ); assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload()); } #[test] #[should_panic(expected = "was not loaded")] fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() { let f = NodeId::random(); let mut st = State::new_history_only(); st.add(change( vec![], vec![TreeOp::AddNode { node: f, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: "a".into(), }], vec![Edit::Insert { node: f, after: AtomRef::Start, before: AtomRef::End, lines: vec![b"a\n".to_vec()], }], )) .unwrap(); st.render_file(&f); } #[test] #[should_panic(expected = "needs every file graph")] fn materializing_a_history_only_state_is_refused() { let f = NodeId::random(); let mut st = State::new_history_only(); st.add(change( vec![], vec![TreeOp::AddNode { node: f, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: "a".into(), }], vec![Edit::Insert { node: f, after: AtomRef::Start, before: AtomRef::End, lines: vec![b"a\n".to_vec()], }], )) .unwrap(); st.materialize(); } /// Version 2 payloads (spec §11): small graphs inline, large ones by /// blob; the state read back is the same as from version 1. #[test] fn checkpoint_index_round_trip_matches_version_1() { let mut st = State::new(); let small = NodeId::random(); let big = NodeId::random(); let add = |node: NodeId, name: &str| TreeOp::AddNode { node, kind: NodeKind::File, mode: Mode::TEXT, parent: NodeId::ROOT, name: name.into(), }; let big_lines: Vec> = (0..400) .map(|i| format!("line {i} of a long file\n").into_bytes()) .collect(); let h1 = st .add(change( vec![], vec![add(small, "small"), add(big, "big")], vec![ Edit::Insert { node: small, after: AtomRef::Start, before: AtomRef::End, lines: vec![b"x\n".to_vec()], }, Edit::Insert { node: big, after: AtomRef::Start, before: AtomRef::End, lines: big_lines, }, ], )) .unwrap(); st.add(change( vec![h1], vec![], vec![Edit::Delete { node: big, atoms: vec![AtomRange { change: h1, from: 3, to: 7, }], }], )) .unwrap(); let graphs = st.checkpoint_file_graphs(); let mut blobs: HashMap> = HashMap::new(); let index = st.checkpoint_index(&graphs, |enc| { let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc); blobs.insert(r, enc.to_vec()); r }); assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own"); assert_eq!( State::checkpoint_graph_refs(&index).unwrap(), blobs.keys().copied().collect::>() ); assert!( State::checkpoint_graph_refs(&st.checkpoint_payload()) .unwrap() .is_empty(), "version 1 names none" ); assert!(index.len() < st.checkpoint_payload().len()); let back = State::from_checkpoint(&index, |refs| { refs.iter() .map(|r| { blobs .get(r) .cloned() .ok_or_else(|| ObjectError::Schema("missing".into())) }) .collect() }) .unwrap(); assert_eq!( back.checkpoint_payload(), st.checkpoint_payload(), "the same state as version 1" ); assert_eq!( back.materialize().files["big"].content, st.materialize().files["big"].content ); // Deterministic: the same state gives the same index. assert_eq!( back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| { crate::hash::hash_object(crate::hash::ObjectType::Blob, enc) }), index ); // A missing graph blob is an error, not an empty file. assert!( State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err() ); assert!( State::from_checkpoint_payload(&index).is_err(), "version 2 needs its blobs" ); // Version 1 payloads still read, and unknown versions do not. assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok()); let mut v3 = cbor::decode(&index).unwrap(); if let Value::Map(m) = &mut v3 { m.insert(0, Value::Uint(3)); } assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err()); } #[test] fn maximal_elements() { let mut st = State::new(); let h1 = st.add(change(vec![], vec![], vec![])).unwrap(); let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap(); let h3 = st.add(change(vec![], vec![], vec![])).unwrap(); let mut m = st.maximal(&[h1, h2, h3]); m.sort(); let mut want = vec![h2, h3]; want.sort(); assert_eq!(m, want); assert_eq!(st.heads(), want); } /// The one-walk `maximal` agrees with the definition (not in the /// closure of another element) on random graphs, with repeated and /// unknown hashes among the input. #[test] fn maximal_matches_its_definition() { use rand::{Rng, SeedableRng}; let mut rng = rand::rngs::StdRng::seed_from_u64(7); for _ in 0..20 { let mut st = State::new(); let mut all: Vec = Vec::new(); for _ in 0..60 { let deps: Vec = all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect(); all.push(st.add(change(deps, vec![], vec![])).unwrap()); } let mut pick: Vec = all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect(); pick.extend(pick.clone().into_iter().take(3)); pick.push(ObjectRef([0xee; 32])); let set: BTreeSet = pick.iter().copied().collect(); let want: Vec = set .iter() .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h))) .copied() .collect(); assert_eq!(st.maximal(&pick), want); assert_eq!(st.maximal(&all), st.heads()); } } }