OXYGENHUB
# d3cd7ef95da6 oxygen / crates / oxy-core / src / state.rs
68.7 KiB · Rust · last changed Read a change's skeleton for history-only states 1 month ago source blame history raw
ff0af1ee unknown 1
//! A state: a dependency-closed set of changes, applied to a tree graph and
2
//! per-node file graphs (spec §8.3), with materialization (spec §9.5, §11).
3
75167672 Andy McCall 4
use crate::cbor::{self, Value};
ff0af1ee unknown 5
use crate::graph::{AtomKey, DepOracle, FileGraph, Materialized, Vertex};
75167672 Andy McCall 6
use crate::hash::KeyId;
ff0af1ee unknown 7
use crate::hash::{ChangeHash, ObjectRef};
8
use crate::ids::NodeId;
75167672 Andy McCall 9
use crate::objects::{
10
    self as o, AtomRef, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, ObjectError, TreeOp,
11
};
ff0af1ee unknown 12
use crate::tree::{TreeGraph, TreeView};
9d333fc9 Andy McCall ↶ 13
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
119bbf50 Andy McCall ↶ 14
use std::sync::{Arc, Mutex};
ff0af1ee unknown 15
afaba5f1 Andy McCall ↶ 16
/// Checkpoint payload version 2 (spec §11): file graphs by reference.
17
pub const CHECKPOINT_INDEX_VERSION: u64 = 2;
18
19
/// A file graph encoded in fewer bytes stays inline in a version 2 index.
20
pub const INLINE_GRAPH_LIMIT: usize = 2048;
21
ff0af1ee unknown 22
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23
pub enum StateError {
24
    #[error("change {1} depends on {0}, which is not in the state")]
25
    MissingDep(ChangeHash, ChangeHash),
26
}
27
55e5a16a unknown ↶ 28
/// One `Replace` edit: `(change, old blob, new blob)`.
29
type ReplaceRecord = (ChangeHash, Option<ObjectRef>, Option<ObjectRef>);
30
252e8cb2 Andy McCall ↶ 31
/// What a state remembers about a change: everything but its operations,
32
/// which live in the graphs once applied (and in the store).
33
#[derive(Clone, Debug, PartialEq, Eq)]
34
pub struct ChangeMeta {
35
    pub change_id: crate::ids::ChangeId,
36
    pub deps: Vec<ChangeHash>,
37
    pub author: KeyId,
38
    pub hlc: Hlc,
39
    pub message: String,
40
    pub kind: ChangeKind,
41
}
42
43
impl ChangeMeta {
44
    pub fn of(c: &Change) -> ChangeMeta {
75167672 Andy McCall 45
        ChangeMeta {
46
            change_id: c.change_id,
47
            deps: c.deps.clone(),
48
            author: c.author,
49
            hlc: c.hlc,
50
            message: c.message.clone(),
51
            kind: c.kind,
52
        }
252e8cb2 Andy McCall ↶ 53
    }
54
}
55
119bbf50 Andy McCall ↶ 56
#[derive(Default)]
ff0af1ee unknown 57
pub struct State {
252e8cb2 Andy McCall ↶ 58
    changes: HashMap<ChangeHash, ChangeMeta>,
ff0af1ee unknown 59
    tree: TreeGraph,
dfb23a3a Andy McCall ↶ 60
    /// Shared between clones: a clone copies a graph only when an edit
61
    /// changes it (`Arc::make_mut`), so keeping several states that differ
62
    /// by a few changes costs little more than one.
63
    files: HashMap<NodeId, Arc<FileGraph>>,
55e5a16a unknown ↶ 64
    replaces: HashMap<NodeId, Vec<ReplaceRecord>>,
119bbf50 Andy McCall ↶ 65
    /// Memoised transitive dependencies. A mutex, not a `RefCell`, so a
66
    /// loaded state can be shared across threads by a host that caches it.
67
    closure: Mutex<HashMap<ChangeHash, Arc<HashSet<ChangeHash>>>>,
e8d38e47 Andy McCall ↶ 68
    /// `None` for a full state. For a history-only state (loaded for its
69
    /// changes and tree), the file graphs not built yet, by node: `files`
70
    /// holds only those loaded with [`State::load_graphs`].
71
    deferred: Option<HashMap<NodeId, Deferred>>,
ff0af1ee unknown 72
}
73
a4fad5b0 Andy McCall ↶ 74
use crate::objects::TextRef;
86e1824f Andy McCall ↶ 75
e8d38e47 Andy McCall ↶ 76
/// A file graph a history-only state has not built: its base from a
77
/// version 2 checkpoint, if any, and the edits of later changes in the
78
/// order they were applied (spec §11). Building it later gives the same
79
/// graph, since graph construction does not depend on order (§8).
80
#[derive(Clone, Default)]
81
struct Deferred {
82
    base: Option<DeferredBase>,
83
    edits: Vec<(ChangeHash, Vec<Edit>)>,
86e1824f Andy McCall ↶ 84
    /// The text blob and line count of each insert in `edits` left without
85
    /// its lines, in order: read when the graph is built.
a4fad5b0 Andy McCall ↶ 86
    texts: Vec<TextRef>,
e8d38e47 Andy McCall ↶ 87
}
88
89
#[derive(Clone)]
90
enum DeferredBase {
91
    Inline(Value),
92
    Blob(ObjectRef),
93
}
94
119bbf50 Andy McCall ↶ 95
impl Clone for State {
96
    fn clone(&self) -> State {
97
        State {
98
            changes: self.changes.clone(),
99
            tree: self.tree.clone(),
100
            files: self.files.clone(),
101
            replaces: self.replaces.clone(),
102
            closure: Mutex::new(self.closure.lock().unwrap().clone()),
e8d38e47 Andy McCall ↶ 103
            deferred: self.deferred.clone(),
119bbf50 Andy McCall ↶ 104
        }
105
    }
106
}
107
ff0af1ee unknown 108
#[derive(Clone, Debug, PartialEq, Eq)]
109
pub enum FileContent {
75167672 Andy McCall 110
    Text {
111
        bytes: Vec<u8>,
112
        materialized: Materialized,
113
    },
ff0af1ee unknown 114
    /// Live blobs; more than one is a replace conflict (spec §9.3).
75167672 Andy McCall 115
    Opaque {
116
        blobs: Vec<ObjectRef>,
117
    },
ff0af1ee unknown 118
    Dir,
119
}
120
121
#[derive(Clone, Debug, PartialEq, Eq)]
122
pub struct FileState {
123
    pub node: NodeId,
124
    pub kind: NodeKind,
125
    pub mode: Mode,
126
    pub content: FileContent,
127
}
128
129
impl FileState {
130
    pub fn is_conflicted(&self) -> bool {
131
        match &self.content {
132
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
133
            FileContent::Opaque { blobs } => blobs.len() > 1,
134
            FileContent::Dir => false,
135
        }
136
    }
137
}
138
20247a03 Andy McCall ↶ 139
/// See `State::conflict_regions`.
140
#[derive(Clone, Debug, Default, PartialEq, Eq)]
141
pub struct ConflictRegions {
142
    pub plain: Vec<(AtomKey, Vec<u8>)>,
143
    pub region_atoms: Vec<AtomKey>,
144
    pub contributors: Vec<ChangeHash>,
145
}
146
ff0af1ee unknown 147
/// The whole tree of a state, materialized.
148
#[derive(Clone, Debug, Default)]
149
pub struct Snapshot {
150
    pub tree: TreeView,
151
    pub files: BTreeMap<String, FileState>,
cc7a0056 Andy McCall ↶ 152
    /// Text files left unrendered by [`State::materialize_except`]: their
153
    /// `bytes` are empty and they are known not to be conflicted.
154
    pub unrendered: BTreeSet<String>,
ff0af1ee unknown 155
}
156
157
impl Snapshot {
158
    pub fn is_conflicted(&self) -> bool {
159
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
160
    }
161
}
162
163
fn vertex(r: AtomRef) -> Vertex {
164
    match r {
165
        AtomRef::Start => Vertex::Start,
166
        AtomRef::End => Vertex::End,
167
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
168
    }
169
}
170
171
/// Replace self references in a tree op with the concrete change hash.
172
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
173
    match op {
75167672 Andy McCall 174
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
175
            node: *node,
176
            placement: placement.resolve(me),
177
        },
178
        TreeOp::Move {
179
            node,
180
            old,
181
            parent,
182
            name,
183
        } => TreeOp::Move {
184
            node: *node,
185
            old: old.resolve(me),
186
            parent: *parent,
187
            name: name.clone(),
188
        },
189
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
190
            node: *node,
191
            old: old.resolve(me),
192
            mode: *mode,
193
        },
ff0af1ee unknown 194
        add @ TreeOp::AddNode { .. } => add.clone(),
e8d38e47 Andy McCall ↶ 195
    }
196
}
197
198
/// Apply one change's edits of one file (inserts and deletes; replaces
199
/// live beside the graphs) to that file's graph.
200
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
201
    let mut next = 0u32;
202
    for e in edits {
203
        match e {
204
            Edit::Insert {
205
                after,
206
                before,
207
                lines,
208
                ..
209
            } => {
210
                let first = next;
211
                next += lines.len() as u32;
212
                g.insert_owned(
213
                    h,
214
                    first,
215
                    vertex(after.resolve(h)),
216
                    vertex(before.resolve(h)),
217
                    lines,
218
                );
219
            }
220
            Edit::Delete { atoms, .. } => {
221
                for r in atoms {
222
                    g.delete(h, &r.resolve(h));
223
                }
224
            }
225
            Edit::Replace { .. } => {}
226
        }
ff0af1ee unknown 227
    }
228
}
229
230
impl State {
231
    pub fn new() -> Self {
232
        Self::default()
e8d38e47 Andy McCall ↶ 233
    }
234
235
    /// An empty state for history only: changes and tree are kept, file
236
    /// edits are recorded but no file graph is built until
237
    /// [`State::load_graphs`] asks for it. For log and other commands that
238
    /// need no file contents, or only a few files.
239
    pub fn new_history_only() -> Self {
240
        State {
241
            deferred: Some(HashMap::new()),
242
            ..Self::default()
243
        }
244
    }
245
86e1824f Andy McCall ↶ 246
    /// Whether this state builds file graphs only when asked
247
    /// ([`State::new_history_only`]), even if it has none waiting.
248
    pub fn is_history_only(&self) -> bool {
249
        self.deferred.is_some()
250
    }
251
e8d38e47 Andy McCall ↶ 252
    /// Whether this state holds every file graph.
253
    pub fn is_full(&self) -> bool {
254
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
255
    }
256
257
    /// The graph of `node`, which must be loaded: asking a history-only
258
    /// state for a graph it has not built is a bug, never an empty file.
259
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
260
        if let Some(d) = &self.deferred {
261
            assert!(
262
                !d.contains_key(node),
263
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
264
                node.short(12)
265
            );
266
        }
dfb23a3a Andy McCall ↶ 267
        self.files.get(node).map(|g| g.as_ref())
e8d38e47 Andy McCall ↶ 268
    }
269
270
    /// Operations over every file need every graph.
271
    fn require_full(&self, what: &str) {
272
        assert!(
273
            self.is_full(),
274
            "{what} needs every file graph; this state was loaded for history only"
275
        );
276
    }
277
278
    /// Build the graphs of `nodes` in a history-only state: from their
279
    /// checkpoint base (blobs read in one batch through `load`) and their
280
    /// deferred edits. Nodes already built, or with no graph, are skipped.
281
    pub fn load_graphs(
282
        &mut self,
283
        nodes: &[NodeId],
284
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
a4fad5b0 Andy McCall ↶ 285
        read_change: impl Fn(&ChangeHash) -> Result<Vec<u8>, ObjectError>,
e8d38e47 Andy McCall ↶ 286
    ) -> Result<(), ObjectError> {
287
        let Some(deferred) = self.deferred.as_mut() else {
288
            return Ok(());
289
        };
290
        let mut taken: Vec<(NodeId, Deferred)> = nodes
291
            .iter()
292
            .filter_map(|n| deferred.remove(n).map(|d| (*n, d)))
293
            .collect();
86e1824f Andy McCall ↶ 294
        let mut refs: Vec<ObjectRef> = taken
e8d38e47 Andy McCall ↶ 295
            .iter()
296
            .filter_map(|(_, d)| match &d.base {
297
                Some(DeferredBase::Blob(r)) => Some(*r),
298
                _ => None,
299
            })
300
            .collect();
86e1824f Andy McCall ↶ 301
        // Text blobs of inserts read without their lines, after the bases.
302
        let bases = refs.len();
a4fad5b0 Andy McCall ↶ 303
        refs.extend(taken.iter().flat_map(|(_, d)| {
304
            d.texts.iter().filter_map(|t| match t {
305
                TextRef::Blob(r, _) => Some(*r),
306
                TextRef::Inline { .. } => None,
307
            })
308
        }));
309
        // And the encodings of changes whose inline inserts are needed,
310
        // each read once.
311
        let mut changes: HashMap<ChangeHash, Vec<u8>> = HashMap::new();
312
        for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
313
            if let TextRef::Inline { change, .. } = t {
314
                if !changes.contains_key(change) {
315
                    changes.insert(*change, read_change(change)?);
316
                }
317
            }
318
        }
e8d38e47 Andy McCall ↶ 319
        let mut blobs = if refs.is_empty() {
320
            Vec::new()
321
        } else {
322
            load(&refs)?
86e1824f Andy McCall ↶ 323
        };
324
        if blobs.len() != refs.len() {
325
            return Err(ObjectError::Schema("graph blobs: wrong count".into()));
e8d38e47 Andy McCall ↶ 326
        }
86e1824f Andy McCall ↶ 327
        let mut texts = blobs.split_off(bases).into_iter();
328
        let mut blobs = blobs.into_iter();
cc7a0056 Andy McCall ↶ 329
        // Pair each graph with its blob, then build them all in parallel:
330
        // graphs are independent.
331
        let mut work: Vec<(NodeId, Deferred, Option<Vec<u8>>)> = Vec::with_capacity(taken.len());
86e1824f Andy McCall ↶ 332
        for (node, mut d) in taken.drain(..) {
333
            // Fill in the lines of inserts read without them, in order.
334
            let mut want = std::mem::take(&mut d.texts).into_iter();
335
            for (_, edits) in d.edits.iter_mut() {
336
                for e in edits.iter_mut() {
337
                    if let Edit::Insert { lines, .. } = e {
338
                        if lines.is_empty() {
a4fad5b0 Andy McCall ↶ 339
                            *lines = match want.next() {
340
                                Some(TextRef::Blob(_, count)) => {
341
                                    let content = texts.next().ok_or_else(|| {
342
                                        ObjectError::Schema("text blobs: wrong count".into())
343
                                    })?;
344
                                    crate::objects::text_lines(&content, count)?
345
                                }
346
                                Some(TextRef::Inline { change, start, end }) => {
347
                                    let bytes = &changes[&change];
348
                                    let range = bytes
349
                                        .get(start as usize..end as usize)
350
                                        .ok_or_else(|| {
351
                                            ObjectError::Schema(
352
                                                "an inline insert lies outside its change".into(),
353
                                            )
354
                                        })?;
355
                                    crate::objects::inline_lines(range)?
356
                                }
357
                                None => {
358
                                    return Err(ObjectError::Schema(
359
                                        "an insert's text is missing".into(),
360
                                    ))
361
                                }
362
                            };
86e1824f Andy McCall ↶ 363
                        }
364
                    }
365
                }
366
            }
cc7a0056 Andy McCall ↶ 367
            let bytes = match &d.base {
368
                Some(DeferredBase::Blob(_)) => Some(
369
                    blobs
e8d38e47 Andy McCall ↶ 370
                        .next()
cc7a0056 Andy McCall ↶ 371
                        .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
372
                ),
373
                _ => None,
e8d38e47 Andy McCall ↶ 374
            };
cc7a0056 Andy McCall ↶ 375
            work.push((node, d, bytes));
e8d38e47 Andy McCall ↶ 376
        }
cc7a0056 Andy McCall ↶ 377
        use rayon::prelude::*;
378
        let built: Vec<(NodeId, FileGraph)> = work
379
            .into_par_iter()
380
            .map(|(node, mut d, bytes)| {
381
                let mut graph = match (d.base.take(), bytes) {
382
                    (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
383
                    (Some(DeferredBase::Blob(_)), Some(bytes)) => {
384
                        FileGraph::from_value(&cbor::decode(&bytes)?)?
385
                    }
386
                    _ => FileGraph::default(),
387
                };
388
                for (h, edits) in std::mem::take(&mut d.edits) {
389
                    apply_file_edits(&mut graph, h, edits);
390
                }
391
                Ok((node, graph))
392
            })
393
            .collect::<Result<_, ObjectError>>()?;
dfb23a3a Andy McCall ↶ 394
        self.files
395
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
cc7a0056 Andy McCall ↶ 396
        Ok(())
397
    }
398
c5ce0367 Andy McCall ↶ 399
    /// Drop the built graphs of `nodes`, for a caller rendering a large
400
    /// tree a batch at a time. The state can no longer render those files,
401
    /// so it must not be used for them again.
402
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
403
        for n in nodes {
404
            self.files.remove(n);
405
        }
406
    }
407
cc7a0056 Andy McCall ↶ 408
    /// Build every graph a history-only state has not built, making it full.
409
    pub fn load_all_graphs(
410
        &mut self,
411
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
a4fad5b0 Andy McCall ↶ 412
        read_change: impl Fn(&ChangeHash) -> Result<Vec<u8>, ObjectError>,
cc7a0056 Andy McCall ↶ 413
    ) -> Result<(), ObjectError> {
414
        let nodes: Vec<NodeId> = match &self.deferred {
415
            Some(d) => d.keys().copied().collect(),
416
            None => return Ok(()),
417
        };
a4fad5b0 Andy McCall ↶ 418
        self.load_graphs(&nodes, load, read_change)?;
cc7a0056 Andy McCall ↶ 419
        self.deferred = None;
e8d38e47 Andy McCall ↶ 420
        Ok(())
cc7a0056 Andy McCall ↶ 421
    }
422
423
    /// A key for the graph of `node` in a history-only state that has not
424
    /// built it: equal keys mean equal graphs, so equal renderings (a
425
    /// rendering depends only on the graph and on the changes' own
426
    /// immutable metadata). It names the node, its checkpoint base (a blob,
427
    /// an inline value, or none) and the set of later changes that edited
428
    /// the file.
429
    /// `None` for a full state or a graph already built.
430
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
431
        let deferred = self.deferred.as_ref()?;
432
        if self.files.contains_key(node) {
433
            return None;
434
        }
435
        let mut h = blake3::Hasher::new();
436
        h.update(b"oxy graph key 1\0");
437
        // A change's edits are applied per node: the node is part of it.
438
        h.update(&node.0);
439
        let Some(d) = deferred.get(node) else {
440
            // Never edited: the empty graph.
441
            h.update(&[0]);
442
            return Some(*h.finalize().as_bytes());
443
        };
444
        match &d.base {
445
            None => h.update(&[0]),
446
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
447
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
448
        };
449
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
450
        changes.sort();
451
        changes.dedup();
452
        h.update(&(changes.len() as u64).to_le_bytes());
453
        for c in changes {
454
            h.update(&c.0);
455
        }
456
        Some(*h.finalize().as_bytes())
ff0af1ee unknown 457
    }
458
459
    pub fn len(&self) -> usize {
460
        self.changes.len()
461
    }
462
    pub fn is_empty(&self) -> bool {
463
        self.changes.is_empty()
464
    }
465
    pub fn contains(&self, h: &ChangeHash) -> bool {
466
        self.changes.contains_key(h)
467
    }
252e8cb2 Andy McCall ↶ 468
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
ff0af1ee unknown 469
        self.changes.get(h)
470
    }
252e8cb2 Andy McCall ↶ 471
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
ff0af1ee unknown 472
        self.changes.iter()
473
    }
474
    pub fn tree(&self) -> &TreeGraph {
475
        &self.tree
476
    }
477
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
e8d38e47 Andy McCall ↶ 478
        self.graph(node)
ff0af1ee unknown 479
    }
480
481
    /// Add a change whose dependencies are already present.
482
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
483
        let h = change.hash();
484
        if self.changes.contains_key(&h) {
485
            return Ok(h);
486
        }
487
        for d in &change.deps {
488
            if !self.changes.contains_key(d) {
489
                return Err(StateError::MissingDep(*d, h));
490
            }
491
        }
492
        Ok(self.add_unchecked(change))
493
    }
494
495
    /// Add a change in any order; call `validate` once all are in.
496
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
497
        let h = change.hash();
86e1824f Andy McCall ↶ 498
        self.add_known(h, change, Vec::new());
499
        h
500
    }
501
502
    /// Add a change read from the store under hash `h`, without hashing it
503
    /// again (for a version 2 change that means chunking all its text).
504
    /// `texts` names, in order, the inserts left without their lines (see
505
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
506
    /// takes them, and only for graphs it has not built.
a4fad5b0 Andy McCall ↶ 507
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
ff0af1ee unknown 508
        if self.changes.contains_key(&h) {
86e1824f Andy McCall ↶ 509
            return;
ff0af1ee unknown 510
        }
0bdc3f91 Andy McCall ↶ 511
        let meta = ChangeMeta::of(&change);
86e1824f Andy McCall ↶ 512
        self.apply_with(h, change, texts);
0bdc3f91 Andy McCall ↶ 513
        self.changes.insert(h, meta);
119bbf50 Andy McCall ↶ 514
        self.closure.lock().unwrap().clear();
ff0af1ee unknown 515
    }
516
252e8cb2 Andy McCall ↶ 517
    // ------------------------------------------------------------ checkpoints (spec §11)
518
afaba5f1 Andy McCall ↶ 519
    /// Serialize the whole state in payload version 1: change metadata,
520
    /// tree, file graphs, replaces, all in one value (spec §11).
252e8cb2 Andy McCall ↶ 521
    pub fn checkpoint_payload(&self) -> Vec<u8> {
e8d38e47 Andy McCall ↶ 522
        self.require_full("a checkpoint");
afaba5f1 Andy McCall ↶ 523
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
524
        nodes.sort();
525
        let files = Value::Array(
526
            nodes
527
                .into_iter()
528
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
529
                .collect(),
530
        );
531
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
532
    }
533
534
    /// Each file graph encoded on its own, by node, for a version 2 payload
535
    /// (spec §11): the graphs of large files become blobs of their own.
536
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
537
        use rayon::prelude::*;
e8d38e47 Andy McCall ↶ 538
        self.require_full("a checkpoint");
dfb23a3a Andy McCall ↶ 539
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
540
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
afaba5f1 Andy McCall ↶ 541
        nodes.sort_by_key(|(n, _)| **n);
542
        nodes
543
            .into_par_iter()
544
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
545
            .collect()
546
    }
547
548
    /// The payload version 2 index for the graphs of
549
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
550
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
551
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
552
    pub fn checkpoint_index(
553
        &self,
554
        graphs: &[(NodeId, Vec<u8>)],
555
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
556
    ) -> Vec<u8> {
557
        let files = Value::Array(
558
            graphs
559
                .iter()
560
                .map(|(n, enc)| {
561
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
562
                        cbor::decode(enc).expect("an encoded graph decodes")
563
                    } else {
564
                        Value::Bytes(blob_of(enc).0.to_vec())
565
                    };
566
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
567
                })
568
                .collect(),
569
        );
570
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
571
    }
572
573
    /// The payload map around `files`: changes, tree and replaces as in version 1.
574
    fn payload_value(&self, version: u64, files: Value) -> Value {
252e8cb2 Andy McCall ↶ 575
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
576
        hashes.sort();
577
        let changes = Value::Array(
578
            hashes
579
                .into_iter()
580
                .map(|h| {
581
                    let m = &self.changes[h];
582
                    Value::Array(vec![
583
                        Value::Bytes(h.0.to_vec()),
584
                        Value::Bytes(m.change_id.0.to_vec()),
585
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
586
                        Value::Text(m.message.clone()),
587
                        Value::Uint(m.hlc.wall_ms),
588
                        Value::Uint(m.hlc.logical as u64),
589
                        Value::Uint(m.kind.tag()),
590
                        Value::Bytes(m.author.0.to_vec()),
591
                    ])
592
                })
75167672 Andy McCall 593
                .collect(),
594
        );
252e8cb2 Andy McCall ↶ 595
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
596
        rnodes.sort();
75167672 Andy McCall 597
        let opt =
598
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
252e8cb2 Andy McCall ↶ 599
        let replaces = Value::Array(
600
            rnodes
601
                .into_iter()
602
                .map(|n| {
603
                    Value::Array(vec![
604
                        Value::Bytes(n.0.to_vec()),
75167672 Andy McCall 605
                        Value::Array(
606
                            self.replaces[n]
607
                                .iter()
608
                                .map(|(c, o, nw)| {
609
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
610
                                })
611
                                .collect(),
612
                        ),
252e8cb2 Andy McCall ↶ 613
                    ])
614
                })
615
                .collect(),
616
        );
afaba5f1 Andy McCall ↶ 617
        Value::map([
618
            (0, Value::Uint(version)),
75167672 Andy McCall 619
            (1, changes),
620
            (2, self.tree.to_value()),
621
            (3, files),
622
            (4, replaces),
afaba5f1 Andy McCall ↶ 623
        ])
252e8cb2 Andy McCall ↶ 624
    }
625
afaba5f1 Andy McCall ↶ 626
    /// Decode a version 1 payload (the whole state in one value). A
627
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
252e8cb2 Andy McCall ↶ 628
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
afaba5f1 Andy McCall ↶ 629
        State::from_checkpoint(bytes, |_| {
630
            Err(ObjectError::Schema(
631
                "a version 2 checkpoint needs its graph blobs".into(),
632
            ))
633
        })
634
    }
635
636
    /// Decode a checkpoint payload of either version (spec §11). For
637
    /// version 2, `load` returns the contents of the named graph blobs, in
638
    /// order; the graphs are then decoded in parallel.
639
    pub fn from_checkpoint(
640
        bytes: &[u8],
641
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
642
    ) -> Result<State, ObjectError> {
643
        use rayon::prelude::*;
252e8cb2 Andy McCall ↶ 644
        let v = cbor::decode(bytes)?;
645
        let m = o::map(&v, "checkpoint payload")?;
afaba5f1 Andy McCall ↶ 646
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
647
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
648
            return Err(ObjectError::Schema(format!(
649
                "checkpoint payload version {version} is not supported"
650
            )));
651
        }
652
        let mut st = State::payload_common(m)?;
653
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
654
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
655
        for f in entries {
656
            let e = o::array(f, "file")?;
657
            if e.len() != 2 {
658
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
659
            }
660
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
661
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
662
            parsed.push((node, &e[1]));
663
        }
664
        // Version 2 names large graphs by blob: fetch those in one batch.
665
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
666
        if version == CHECKPOINT_INDEX_VERSION {
667
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
668
                .iter()
669
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
670
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
671
                .collect::<Result<_, ObjectError>>()?;
672
            if !wanted.is_empty() {
673
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
674
                let contents = {
675
                    let _t = crate::timing::phase("load:   graph blobs read");
676
                    load(&refs)?
677
                };
678
                if contents.len() != refs.len() {
679
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
680
                }
681
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
682
            }
683
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
684
            return Err(ObjectError::Schema(
685
                "a version 1 payload holds graphs inline".into(),
686
            ));
687
        }
688
        // File graphs are independent; decode and build them in parallel.
689
        let graphs = parsed
690
            .par_iter()
691
            .map(|(node, entry)| {
692
                let graph = match fetched.get(node) {
693
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
694
                    None => FileGraph::from_value(entry)?,
695
                };
696
                Ok((*node, graph))
697
            })
698
            .collect::<Result<Vec<_>, ObjectError>>()?;
dfb23a3a Andy McCall ↶ 699
        st.files
700
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
afaba5f1 Andy McCall ↶ 701
        Ok(st)
702
    }
703
704
    /// The graph blobs a payload names: empty for version 1.
705
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
706
        let v = cbor::decode(bytes)?;
707
        let m = o::map(&v, "checkpoint payload")?;
708
        let mut out = Vec::new();
709
        for f in o::array(o::field(m, 3, "files")?, "files")? {
710
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
711
                out.push(o::oref(entry, "graph blob")?);
712
            }
713
        }
714
        Ok(out)
e8d38e47 Andy McCall ↶ 715
    }
716
717
    /// Decode a checkpoint payload for history only: a version 2 payload's
718
    /// graphs are noted, not read or built, and come later through
719
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
720
    /// decoded in full.
721
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
722
        let v = cbor::decode(bytes)?;
723
        let m = o::map(&v, "checkpoint payload")?;
724
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
725
        if version != CHECKPOINT_INDEX_VERSION {
726
            return State::from_checkpoint_payload(bytes);
727
        }
728
        let mut st = State::payload_common(m)?;
729
        let mut deferred = HashMap::new();
730
        for f in o::array(o::field(m, 3, "files")?, "files")? {
731
            let e = o::array(f, "file")?;
732
            if e.len() != 2 {
733
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
734
            }
735
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
736
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
737
            let base = match &e[1] {
738
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
739
                other => DeferredBase::Inline(other.clone()),
740
            };
741
            deferred.insert(
742
                node,
743
                Deferred {
744
                    base: Some(base),
745
                    edits: Vec::new(),
86e1824f Andy McCall ↶ 746
                    texts: Vec::new(),
e8d38e47 Andy McCall ↶ 747
                },
748
            );
749
        }
750
        st.deferred = Some(deferred);
751
        Ok(st)
afaba5f1 Andy McCall ↶ 752
    }
753
754
    /// Changes, tree and replaces of a payload of either version.
755
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
252e8cb2 Andy McCall ↶ 756
        let mut st = State::new();
757
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
758
            let e = o::array(c, "change meta")?;
759
            if e.len() != 8 {
760
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
761
            }
762
            let hash = o::oref(&e[0], "hash")?;
763
            let meta = ChangeMeta {
75167672 Andy McCall 764
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
765
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
766
                deps: o::array(&e[2], "deps")?
767
                    .iter()
768
                    .map(|d| o::oref(d, "dep"))
769
                    .collect::<Result<Vec<_>, _>>()?,
252e8cb2 Andy McCall ↶ 770
                message: o::text(&e[3], "message")?.to_owned(),
75167672 Andy McCall 771
                hlc: Hlc {
772
                    wall_ms: o::uint(&e[4], "wall")?,
773
                    logical: o::u32_(&e[5], "logical")?,
774
                },
252e8cb2 Andy McCall ↶ 775
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
776
                author: o::oref(&e[7], "author")?,
777
            };
778
            st.changes.insert(hash, meta);
779
        }
780
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
75167672 Andy McCall 781
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
782
            if v.is_null() {
783
                Ok(None)
784
            } else {
785
                o::oref(v, "blob").map(Some)
786
            }
787
        };
252e8cb2 Andy McCall ↶ 788
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
789
            let e = o::array(r, "replace")?;
790
            if e.len() != 2 {
75167672 Andy McCall 791
                return Err(ObjectError::Schema(
792
                    "replace: expected [node, records]".into(),
793
                ));
252e8cb2 Andy McCall ↶ 794
            }
75167672 Andy McCall 795
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
796
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
252e8cb2 Andy McCall ↶ 797
            let mut recs = Vec::new();
798
            for rec in o::array(&e[1], "records")? {
799
                let x = o::array(rec, "record")?;
800
                if x.len() != 3 {
801
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
802
                }
803
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
804
            }
805
            st.replaces.insert(node, recs);
806
        }
807
        Ok(st)
808
    }
809
ff0af1ee unknown 810
    pub fn validate(&self) -> Result<(), StateError> {
811
        for (h, c) in &self.changes {
812
            for d in &c.deps {
813
                if !self.changes.contains_key(d) {
814
                    return Err(StateError::MissingDep(*d, *h));
815
                }
816
            }
817
        }
818
        Ok(())
819
    }
820
a4fad5b0 Andy McCall ↶ 821
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
ff0af1ee unknown 822
        for (i, op) in c.tree_ops.iter().enumerate() {
823
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
824
        }
e8d38e47 Andy McCall ↶ 825
        if let Some(deferred) = self.deferred.as_mut() {
86e1824f Andy McCall ↶ 826
            // History only: edits of files not built wait, grouped per file,
827
            // with the texts of inserts read without their lines.
828
            let mut texts = texts.into_iter();
829
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
e8d38e47 Andy McCall ↶ 830
            for e in c.edits {
831
                match e {
832
                    Edit::Replace { node, old, new } => {
833
                        self.replaces.entry(node).or_default().push((h, old, new))
834
                    }
86e1824f Andy McCall ↶ 835
                    e => {
836
                        let slot = per_node.entry(e.node()).or_default();
837
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
838
                            slot.1.extend(texts.next());
839
                        }
840
                        slot.0.push(e);
841
                    }
e8d38e47 Andy McCall ↶ 842
                }
843
            }
86e1824f Andy McCall ↶ 844
            for (node, (edits, node_texts)) in per_node {
e8d38e47 Andy McCall ↶ 845
                match self.files.get_mut(&node) {
86e1824f Andy McCall ↶ 846
                    Some(g) => {
847
                        assert!(
848
                            node_texts.is_empty(),
849
                            "a change read without its text applied to a built graph"
850
                        );
851
                        apply_file_edits(Arc::make_mut(g), h, edits)
852
                    }
853
                    None => {
854
                        let d = deferred.entry(node).or_default();
855
                        d.edits.push((h, edits));
856
                        d.texts.extend(node_texts);
857
                    }
e8d38e47 Andy McCall ↶ 858
                }
859
            }
860
            return;
861
        }
86e1824f Andy McCall ↶ 862
        assert!(
863
            texts.is_empty(),
864
            "a change read without its text applied to a full state"
865
        );
ff0af1ee unknown 866
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
0bdc3f91 Andy McCall ↶ 867
        for e in c.edits {
ff0af1ee unknown 868
            match e {
75167672 Andy McCall 869
                Edit::Insert {
870
                    node,
871
                    after,
872
                    before,
873
                    lines,
874
                } => {
0bdc3f91 Andy McCall ↶ 875
                    let idx = counters.entry(node).or_default();
ff0af1ee unknown 876
                    let first = *idx;
877
                    *idx += lines.len() as u32;
dfb23a3a Andy McCall ↶ 878
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
75167672 Andy McCall 879
                        h,
880
                        first,
881
                        vertex(after.resolve(h)),
882
                        vertex(before.resolve(h)),
883
                        lines,
884
                    );
ff0af1ee unknown 885
                }
886
                Edit::Delete { node, atoms } => {
dfb23a3a Andy McCall ↶ 887
                    let g = Arc::make_mut(self.files.entry(node).or_default());
ff0af1ee unknown 888
                    for r in atoms {
889
                        g.delete(h, &r.resolve(h));
890
                    }
891
                }
892
                Edit::Replace { node, old, new } => {
0bdc3f91 Andy McCall ↶ 893
                    self.replaces.entry(node).or_default().push((h, old, new));
ff0af1ee unknown 894
                }
895
            }
896
        }
897
    }
898
899
    /// Transitive dependencies of `h`, excluding `h` itself.
119bbf50 Andy McCall ↶ 900
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
901
        if let Some(c) = self.closure.lock().unwrap().get(h) {
ff0af1ee unknown 902
            return c.clone();
903
        }
904
        let mut out = HashSet::new();
75167672 Andy McCall 905
        let mut stack: Vec<ChangeHash> = self
906
            .changes
907
            .get(h)
908
            .map(|c| c.deps.clone())
909
            .unwrap_or_default();
ff0af1ee unknown 910
        while let Some(d) = stack.pop() {
911
            if out.insert(d) {
912
                if let Some(c) = self.changes.get(&d) {
913
                    stack.extend(c.deps.iter().copied());
914
                }
915
            }
916
        }
119bbf50 Andy McCall ↶ 917
        let rc = Arc::new(out);
918
        self.closure.lock().unwrap().insert(*h, rc.clone());
ff0af1ee unknown 919
        rc
920
    }
921
922
    /// Changes that no other change depends on directly, sorted.
923
    pub fn heads(&self) -> Vec<ChangeHash> {
75167672 Andy McCall 924
        let depended: HashSet<&ChangeHash> =
925
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
926
        let mut heads: Vec<ChangeHash> = self
927
            .changes
928
            .keys()
929
            .filter(|h| !depended.contains(h))
930
            .copied()
931
            .collect();
ff0af1ee unknown 932
        heads.sort();
933
        heads
934
    }
935
07eb99be Andy McCall ↶ 936
    /// Maximal elements among `hashes` (those not in the closure of another),
937
    /// sorted. One walk down from all of them at once: whatever the walk
938
    /// reaches is below some other element. Linear in the changes reached,
939
    /// where comparing every pair's closures was quadratic in the number
940
    /// of heads, which a bookmark of independent changes has many of.
ff0af1ee unknown 941
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
942
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
07eb99be Andy McCall ↶ 943
        let mut below: HashSet<ChangeHash> = HashSet::new();
944
        let mut stack: Vec<ChangeHash> = set
945
            .iter()
946
            .filter_map(|h| self.changes.get(h))
947
            .flat_map(|c| c.deps.iter().copied())
948
            .collect();
949
        while let Some(d) = stack.pop() {
950
            if below.insert(d) {
951
                if let Some(c) = self.changes.get(&d) {
952
                    stack.extend(c.deps.iter().copied());
953
                }
954
            }
955
        }
956
        set.into_iter().filter(|h| !below.contains(h)).collect()
ff0af1ee unknown 957
    }
958
959
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
e8d38e47 Andy McCall ↶ 960
        self.graph(node)
75167672 Andy McCall 961
            .map(|g| g.materialize(self))
962
            .unwrap_or_default()
ff0af1ee unknown 963
    }
964
965
    /// Live lines of a text node in materialized order.
966
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
e8d38e47 Andy McCall ↶ 967
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 968
            return vec![];
969
        };
ff0af1ee unknown 970
        let m = g.materialize(self);
75167672 Andy McCall 971
        m.live_atoms()
972
            .into_iter()
973
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
974
            .collect()
ff0af1ee unknown 975
    }
976
977
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
978
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
62794ecc Andy McCall ↶ 979
        let mut live: Vec<ObjectRef> = self
980
            .live_replaces(node)
981
            .into_iter()
982
            .map(|(_, n)| n)
75167672 Andy McCall 983
            .collect();
ff0af1ee unknown 984
        live.sort();
985
        live.dedup();
986
        live
987
    }
988
62794ecc Andy McCall ↶ 989
    /// The replace records whose blob is live, with the change that set it
990
    /// (spec §9.3). A record's blob is superseded by a later replacement of
991
    /// that blob: one whose change depends on the record's change, as every
992
    /// replacement depends on the change that made its old blob current
993
    /// (§8.1). Two replacements that do not know each other both stay live
994
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
995
    /// A replacement without that dependency, from before the rule, is read
996
    /// as before: it supersedes every record that did not come after it.
997
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
998
        let Some(rs) = self.replaces.get(node) else {
999
            return vec![];
1000
        };
1001
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
1002
            rs.iter()
1003
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
1004
        };
1005
        rs.iter()
1006
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
1007
            .filter(|(c, n)| {
1008
                !rs.iter().any(|(s, o, _)| {
1009
                    s != c
1010
                        && *o == Some(*n)
1011
                        && (self.closure(s).contains(c)
1012
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
1013
                })
1014
            })
1015
            .collect()
1016
    }
1017
ff0af1ee unknown 1018
    /// Short label for conflict markers: `changeid-prefix "message"`.
1019
    pub fn label(&self, h: &ChangeHash) -> String {
1020
        match self.changes.get(h) {
75167672 Andy McCall 1021
            Some(c) => format!(
1022
                "{} \"{}\"",
1023
                c.change_id.short(8),
1024
                c.message.lines().next().unwrap_or("")
1025
            ),
ff0af1ee unknown 1026
            None => format!("#{}", h.short(12)),
1027
        }
1028
    }
1029
20247a03 Andy McCall ↶ 1030
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1031
    /// are not part of any conflict region in order, every live atom that is
1032
    /// part of a region, and every change that contributed to a region.
50a046e4 Andy McCall ↶ 1033
    /// The changes that introduced the live blobs of an opaque node, for a
1034
    /// replace conflict (spec §9.3).
1035
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
1036
        let mut out: Vec<ChangeHash> = Vec::new();
1037
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
1038
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
1039
                out.push(*h);
1040
            }
1041
        }
1042
        out.sort();
1043
        out
1044
    }
1045
20247a03 Andy McCall ↶ 1046
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
1047
        let mut out = ConflictRegions::default();
e8d38e47 Andy McCall ↶ 1048
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 1049
            return out;
1050
        };
20247a03 Andy McCall ↶ 1051
        let m = g.materialize(self);
1052
        let mut contributors = BTreeSet::new();
1053
        for seg in &m.segments {
1054
            match seg {
1055
                crate::graph::Segment::Lines(atoms) => {
1056
                    for a in atoms {
75167672 Andy McCall 1057
                        out.plain
1058
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
20247a03 Andy McCall ↶ 1059
                    }
1060
                }
1061
                crate::graph::Segment::Conflict(sides) => {
1062
                    for side in sides {
1063
                        for a in side {
1064
                            out.region_atoms.push(*a);
1065
                            contributors.insert(a.0);
1066
                        }
1067
                    }
1068
                }
1069
                crate::graph::Segment::Zombie { deleted, inserted } => {
1070
                    for a in deleted {
1071
                        contributors.insert(a.0);
1072
                        contributors.extend(g.deleters(a).copied());
1073
                    }
1074
                    for a in inserted {
1075
                        out.region_atoms.push(*a);
1076
                        contributors.insert(a.0);
1077
                    }
1078
                }
1079
            }
1080
        }
1081
        out.contributors = contributors.into_iter().collect();
1082
        out
1083
    }
1084
ff0af1ee unknown 1085
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
e8d38e47 Andy McCall ↶ 1086
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 1087
            return (Vec::new(), Materialized::default());
1088
        };
ff0af1ee unknown 1089
        let m = g.materialize(self);
1090
        let bytes = g.render(&m, &|h| self.label(h));
1091
        (bytes, m)
1092
    }
1093
e7ddd552 Andy McCall ↶ 1094
    /// Every file rendered, in parallel: files are independent, and
1095
    /// rendering them is most of a snapshot's cost in a large tree.
ff0af1ee unknown 1096
    pub fn materialize(&self) -> Snapshot {
e7ddd552 Andy McCall ↶ 1097
        use rayon::prelude::*;
e8d38e47 Andy McCall ↶ 1098
        self.require_full("materializing a state");
ff0af1ee unknown 1099
        let tree = self.tree.view();
e7ddd552 Andy McCall ↶ 1100
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1101
        let rendered: Vec<(String, FileState)> = entries
1102
            .par_iter()
1103
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
1104
            .collect();
1105
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
cc7a0056 Andy McCall ↶ 1106
        Snapshot {
1107
            tree,
1108
            files,
1109
            unrendered: BTreeSet::new(),
1110
        }
1111
    }
1112
1113
    /// Like [`State::materialize`], leaving the text files of nodes in
1114
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
1115
    /// file's graph must be loaded. For a caller that already knows those
1116
    /// files are unchanged and not conflicted.
1117
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
1118
        use rayon::prelude::*;
1119
        let tree = self.tree.view();
1120
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1121
        let rendered: Vec<(String, FileState, bool)> = entries
1122
            .par_iter()
1123
            .map(|(path, e)| {
1124
                if e.kind == NodeKind::File && !e.mode.opaque && skip.contains(&e.node) {
1125
                    let f = FileState {
1126
                        node: e.node,
1127
                        kind: e.kind,
1128
                        mode: e.mode,
1129
                        content: FileContent::Text {
1130
                            bytes: Vec::new(),
1131
                            materialized: Materialized::default(),
1132
                        },
1133
                    };
1134
                    (path.to_string(), f, true)
1135
                } else {
1136
                    (path.to_string(), self.file_state(e), false)
1137
                }
1138
            })
1139
            .collect();
1140
        let mut files = BTreeMap::new();
1141
        let mut unrendered = BTreeSet::new();
1142
        for (p, f, skipped) in rendered {
1143
            if skipped {
1144
                unrendered.insert(p.clone());
1145
            }
1146
            files.insert(p, f);
1147
        }
1148
        Snapshot {
1149
            tree,
1150
            files,
1151
            unrendered,
1152
        }
e7ddd552 Andy McCall ↶ 1153
    }
1154
1155
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1156
        {
ff0af1ee unknown 1157
            let content = match e.kind {
1158
                NodeKind::Dir => FileContent::Dir,
75167672 Andy McCall 1159
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
1160
                    blobs: self.live_blobs(&e.node),
1161
                },
1162
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
1163
                    blobs: self.live_blobs(&e.node),
1164
                },
ff0af1ee unknown 1165
                NodeKind::File => {
1166
                    let (bytes, materialized) = self.render_file(&e.node);
75167672 Andy McCall 1167
                    FileContent::Text {
1168
                        bytes,
1169
                        materialized,
1170
                    }
ff0af1ee unknown 1171
                }
1172
            };
e7ddd552 Andy McCall ↶ 1173
            FileState {
1174
                node: e.node,
1175
                kind: e.kind,
1176
                mode: e.mode,
1177
                content,
1178
            }
ff0af1ee unknown 1179
        }
1180
    }
1181
}
1182
1183
impl DepOracle for State {
1184
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
1185
        a == b || self.closure(a).contains(b)
1186
    }
1187
}
1188
1189
#[cfg(test)]
1190
mod tests {
1191
    use super::*;
1192
    use crate::ids::ChangeId;
1193
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
1194
1195
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
1196
        let mut c = Change {
6f8aeb99 Andy McCall ↶ 1197
            version: crate::objects::CHANGE_VERSION,
ff0af1ee unknown 1198
            change_id: ChangeId::random(),
1199
            deps,
1200
            author: ObjectRef::ZERO,
75167672 Andy McCall 1201
            hlc: Hlc {
1202
                wall_ms: 1,
1203
                logical: 0,
1204
            },
ff0af1ee unknown 1205
            message: "m".into(),
1206
            tree_ops,
1207
            edits,
1208
            kind: ChangeKind::Normal,
1209
        };
1210
        c.normalize();
1211
        c
1212
    }
1213
1214
    #[test]
1215
    fn build_edit_and_materialize() {
1216
        let mut st = State::new();
1217
        let f = NodeId::random();
1218
        let c1 = change(
1219
            vec![],
75167672 Andy McCall 1220
            vec![TreeOp::AddNode {
1221
                node: f,
1222
                kind: NodeKind::File,
1223
                mode: Mode::TEXT,
1224
                parent: NodeId::ROOT,
1225
                name: "a.txt".into(),
1226
            }],
1227
            vec![Edit::Insert {
1228
                node: f,
1229
                after: AtomRef::Start,
1230
                before: AtomRef::End,
1231
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()],
1232
            }],
ff0af1ee unknown 1233
        );
1234
        let h1 = st.add(c1).unwrap();
1235
        // Depends on h1: append a line and delete "one".
1236
        let c2 = change(
1237
            vec![h1],
1238
            vec![],
1239
            vec![
75167672 Andy McCall 1240
                Edit::Delete {
1241
                    node: f,
1242
                    atoms: vec![AtomRange {
1243
                        change: h1,
1244
                        from: 0,
1245
                        to: 1,
1246
                    }],
1247
                },
1248
                Edit::Insert {
1249
                    node: f,
1250
                    after: AtomRef::Atom {
1251
                        change: h1,
1252
                        index: 1,
1253
                    },
1254
                    before: AtomRef::End,
1255
                    lines: vec![b"three\n".to_vec()],
1256
                },
ff0af1ee unknown 1257
            ],
1258
        );
1259
        let h2 = st.add(c2).unwrap();
1260
        assert_eq!(st.heads(), vec![h2]);
1261
        assert!(st.depends_on(&h2, &h1));
1262
        assert!(!st.depends_on(&h1, &h2));
1263
        let snap = st.materialize();
1264
        assert!(!snap.is_conflicted());
1265
        let a = &snap.files["a.txt"];
1266
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
1267
        assert_eq!(st.live_lines(&f).len(), 2);
1268
    }
1269
1270
    #[test]
1271
    fn missing_dependency_is_rejected() {
1272
        let mut st = State::new();
1273
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
1274
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
1275
    }
1276
1277
    #[test]
1278
    fn self_references_and_multi_insert_indexing() {
1279
        let mut st = State::new();
1280
        let f = NodeId::random();
75167672 Andy McCall 1281
        let me = OpRef {
1282
            change: ObjectRef::ZERO,
1283
            index: 0,
1284
        };
ff0af1ee unknown 1285
        let c1 = change(
1286
            vec![],
1287
            vec![
75167672 Andy McCall 1288
                TreeOp::AddNode {
1289
                    node: f,
1290
                    kind: NodeKind::File,
1291
                    mode: Mode::TEXT,
1292
                    parent: NodeId::ROOT,
1293
                    name: "x".into(),
1294
                },
1295
                TreeOp::SetMode {
1296
                    node: f,
1297
                    old: me,
1298
                    mode: Mode {
1299
                        exec: true,
1300
                        opaque: false,
1301
                    },
1302
                },
ff0af1ee unknown 1303
            ],
1304
            vec![
75167672 Andy McCall 1305
                Edit::Insert {
1306
                    node: f,
1307
                    after: AtomRef::Start,
1308
                    before: AtomRef::End,
1309
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()],
1310
                },
ff0af1ee unknown 1311
                // Insert between the two lines just inserted, using self references.
1312
                Edit::Insert {
1313
                    node: f,
75167672 Andy McCall 1314
                    after: AtomRef::Atom {
1315
                        change: ObjectRef::ZERO,
1316
                        index: 0,
1317
                    },
1318
                    before: AtomRef::Atom {
1319
                        change: ObjectRef::ZERO,
1320
                        index: 1,
1321
                    },
ff0af1ee unknown 1322
                    lines: vec![b"b\n".to_vec()],
1323
                },
1324
            ],
1325
        );
1326
        st.add(c1).unwrap();
1327
        let snap = st.materialize();
1328
        let x = &snap.files["x"];
75167672 Andy McCall 1329
        assert_eq!(
1330
            x.mode,
1331
            Mode {
1332
                exec: true,
1333
                opaque: false
1334
            }
1335
        );
ff0af1ee unknown 1336
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
1337
    }
1338
1339
    #[test]
1340
    fn opaque_replace_and_conflict() {
1341
        let mut st = State::new();
1342
        let f = NodeId::random();
1343
        let b1 = ObjectRef([1; 32]);
1344
        let b2 = ObjectRef([2; 32]);
1345
        let b3 = ObjectRef([3; 32]);
75167672 Andy McCall 1346
        let h1 = st
1347
            .add(change(
1348
                vec![],
1349
                vec![TreeOp::AddNode {
1350
                    node: f,
1351
                    kind: NodeKind::File,
1352
                    mode: Mode::OPAQUE,
1353
                    parent: NodeId::ROOT,
1354
                    name: "img".into(),
1355
                }],
1356
                vec![Edit::Replace {
1357
                    node: f,
1358
                    old: None,
1359
                    new: Some(b1),
1360
                }],
1361
            ))
1362
            .unwrap();
1363
        assert_eq!(st.live_blobs(&f), vec![b1]);
1364
        st.add(change(
1365
            vec![h1],
1366
            vec![],
1367
            vec![Edit::Replace {
1368
                node: f,
1369
                old: Some(b1),
1370
                new: Some(b2),
1371
            }],
1372
        ))
1373
        .unwrap();
1374
        st.add(change(
1375
            vec![h1],
ff0af1ee unknown 1376
            vec![],
75167672 Andy McCall 1377
            vec![Edit::Replace {
1378
                node: f,
1379
                old: Some(b1),
1380
                new: Some(b3),
1381
            }],
ff0af1ee unknown 1382
        ))
1383
        .unwrap();
1384
        let snap = st.materialize();
1385
        assert!(snap.is_conflicted());
75167672 Andy McCall 1386
        assert!(
1387
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
1388
        );
ff0af1ee unknown 1389
    }
1390
1391
    #[test]
252e8cb2 Andy McCall ↶ 1392
    fn checkpoint_payload_round_trip_and_replay() {
1393
        let mut st = State::new();
1394
        let f = NodeId::random();
75167672 Andy McCall 1395
        let h1 = st
1396
            .add(change(
1397
                vec![],
1398
                vec![TreeOp::AddNode {
1399
                    node: f,
1400
                    kind: NodeKind::File,
1401
                    mode: Mode::TEXT,
1402
                    parent: NodeId::ROOT,
1403
                    name: "a".into(),
1404
                }],
1405
                vec![Edit::Insert {
1406
                    node: f,
1407
                    after: AtomRef::Start,
1408
                    before: AtomRef::End,
1409
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()],
1410
                }],
1411
            ))
1412
            .unwrap();
1413
        let h2 = st
1414
            .add(change(
1415
                vec![h1],
1416
                vec![],
1417
                vec![Edit::Delete {
1418
                    node: f,
1419
                    atoms: vec![AtomRange {
1420
                        change: h1,
1421
                        from: 0,
1422
                        to: 1,
1423
                    }],
1424
                }],
1425
            ))
1426
            .unwrap();
252e8cb2 Andy McCall ↶ 1427
        let payload = st.checkpoint_payload();
1428
        let back = State::from_checkpoint_payload(&payload).unwrap();
1429
        assert_eq!(back.len(), 2);
1430
        assert_eq!(back.heads(), vec![h2]);
1431
        assert_eq!(back.get(&h1).unwrap().message, "m");
1432
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
1433
        // Replaying a further change onto the restored state equals a full build.
75167672 Andy McCall 1434
        let c3 = change(
1435
            vec![h2],
1436
            vec![],
1437
            vec![Edit::Insert {
1438
                node: f,
1439
                after: AtomRef::Atom {
1440
                    change: h1,
1441
                    index: 1,
1442
                },
1443
                before: AtomRef::End,
1444
                lines: vec![b"3\n".to_vec()],
1445
            }],
1446
        );
252e8cb2 Andy McCall ↶ 1447
        let mut full = st.clone();
1448
        full.add(c3.clone()).unwrap();
1449
        let mut restored = back;
1450
        restored.add(c3).unwrap();
1451
        let (a, b) = (full.materialize(), restored.materialize());
75167672 Andy McCall 1452
        assert_eq!(
1453
            a.files.keys().collect::<Vec<_>>(),
1454
            b.files.keys().collect::<Vec<_>>()
1455
        );
252e8cb2 Andy McCall ↶ 1456
        assert_eq!(a.files["a"].content, b.files["a"].content);
75167672 Andy McCall 1457
        assert!(
1458
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
1459
        );
252e8cb2 Andy McCall ↶ 1460
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
e8d38e47 Andy McCall ↶ 1461
    }
1462
1463
    /// History-only states (O10f): the same state as a full load once its
1464
    /// graphs are built, by replay and from a version 2 checkpoint with
1465
    /// later changes; unloaded graphs are never read as empty.
cc7a0056 Andy McCall ↶ 1466
    #[test]
1467
    fn graph_keys_change_exactly_when_a_graph_does() {
1468
        let (f, g) = (NodeId::random(), NodeId::random());
1469
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1470
            node,
1471
            kind: NodeKind::File,
1472
            mode: Mode::TEXT,
1473
            parent: NodeId::ROOT,
1474
            name: name.into(),
1475
        };
1476
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
1477
            node,
1478
            after: AtomRef::Start,
1479
            before: AtomRef::End,
1480
            lines: vec![line.to_vec()],
1481
        };
1482
        let c1 = change(
1483
            vec![],
1484
            vec![add(f, "f"), add(g, "g")],
1485
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
1486
        );
1487
        let h1 = c1.hash();
1488
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
1489
        let h2 = c2.hash();
1490
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
1491
        let load = |cs: &[&Change]| {
1492
            let mut st = State::new_history_only();
1493
            for c in cs {
1494
                st.add((*c).clone()).unwrap();
1495
            }
1496
            st
1497
        };
1498
        let s1 = load(&[&c1]);
1499
        let s2 = load(&[&c1, &c2]);
1500
        let s3 = load(&[&c1, &c2, &c3]);
1501
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
1502
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
1503
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
1504
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
1505
        assert_ne!(key(&s2, &f), key(&s3, &f));
1506
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
1507
        let mut built = load(&[&c1]);
a4fad5b0 Andy McCall ↶ 1508
        built
1509
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
1510
            .unwrap();
cc7a0056 Andy McCall ↶ 1511
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
1512
        let mut full = State::new();
1513
        full.add(c1.clone()).unwrap();
1514
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
1515
1516
        // Through a version 2 checkpoint of c1, keys name its graph blobs
1517
        // or inline values: stable across loads, changed by later edits.
1518
        let graphs = full.checkpoint_file_graphs();
1519
        let index = full.checkpoint_index(&graphs, |enc| {
1520
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1521
        });
1522
        let cp = |extra: &[&Change]| {
1523
            let mut st = State::from_checkpoint_history(&index).unwrap();
1524
            for c in extra {
1525
                st.add((*c).clone()).unwrap();
1526
            }
1527
            st
1528
        };
1529
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
1530
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
1531
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
1532
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
1533
1534
        // Partial rendering: skipped files are listed and empty, the others
1535
        // render as in a full state.
1536
        let mut part = load(&[&c1, &c2]);
a4fad5b0 Andy McCall ↶ 1537
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
1538
            .unwrap();
cc7a0056 Andy McCall ↶ 1539
        let snap = part.materialize_except(&[f].into_iter().collect());
1540
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
1541
        let mut whole = State::new();
1542
        whole.add(c1.clone()).unwrap();
1543
        whole.add(c2.clone()).unwrap();
1544
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
1545
        assert!(
1546
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
1547
        );
1548
    }
1549
e8d38e47 Andy McCall ↶ 1550
    #[test]
1551
    fn history_only_states_build_the_same_graphs_on_demand() {
1552
        let small = NodeId::random();
1553
        let big = NodeId::random();
1554
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1555
            node,
1556
            kind: NodeKind::File,
1557
            mode: Mode::TEXT,
1558
            parent: NodeId::ROOT,
1559
            name: name.into(),
1560
        };
1561
        let lines: Vec<Vec<u8>> = (0..300)
1562
            .map(|i| format!("line {i}\n").into_bytes())
1563
            .collect();
1564
        let c1 = change(
1565
            vec![],
1566
            vec![add(small, "small"), add(big, "big")],
1567
            vec![
1568
                Edit::Insert {
1569
                    node: small,
1570
                    after: AtomRef::Start,
1571
                    before: AtomRef::End,
1572
                    lines: vec![b"x\n".to_vec()],
1573
                },
1574
                Edit::Insert {
1575
                    node: big,
1576
                    after: AtomRef::Start,
1577
                    before: AtomRef::End,
1578
                    lines,
1579
                },
1580
            ],
1581
        );
1582
        let h1 = c1.hash();
1583
        let c2 = change(
1584
            vec![h1],
1585
            vec![],
1586
            vec![
1587
                Edit::Delete {
1588
                    node: big,
1589
                    atoms: vec![AtomRange {
1590
                        change: h1,
1591
                        from: 2,
1592
                        to: 9,
1593
                    }],
1594
                },
1595
                Edit::Insert {
1596
                    node: big,
1597
                    after: AtomRef::Atom {
1598
                        change: h1,
1599
                        index: 20,
1600
                    },
1601
                    before: AtomRef::Atom {
1602
                        change: h1,
1603
                        index: 21,
1604
                    },
1605
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()],
1606
                },
1607
                Edit::Insert {
1608
                    node: small,
1609
                    after: AtomRef::Atom {
1610
                        change: h1,
1611
                        index: 0,
1612
                    },
1613
                    before: AtomRef::End,
1614
                    lines: vec![b"y\n".to_vec()],
1615
                },
1616
            ],
1617
        );
1618
        let h2 = c2.hash();
1619
        let c3 = change(
1620
            vec![h2],
1621
            vec![],
1622
            vec![Edit::Delete {
1623
                node: small,
1624
                atoms: vec![AtomRange {
1625
                    change: h1,
1626
                    from: 0,
1627
                    to: 1,
1628
                }],
1629
            }],
1630
        );
1631
1632
        let mut full = State::new();
1633
        for c in [&c1, &c2, &c3] {
1634
            full.add(c.clone()).unwrap();
1635
        }
1636
        // By replay: nothing built until asked, then exactly the full graphs.
1637
        let mut hist = State::new_history_only();
1638
        for c in [&c1, &c2, &c3] {
1639
            hist.add(c.clone()).unwrap();
1640
        }
1641
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
1642
        assert_eq!(hist.len(), 3);
a4fad5b0 Andy McCall ↶ 1643
        hist.load_graphs(
1644
            &[big],
1645
            |_| unreachable!("no checkpoint"),
1646
            |_| unreachable!(),
1647
        )
1648
        .unwrap();
e8d38e47 Andy McCall ↶ 1649
        assert_eq!(
1650
            hist.render_file(&big).0,
1651
            full.render_file(&big).0,
1652
            "one file on its own"
1653
        );
1654
        assert!(!hist.is_full());
a4fad5b0 Andy McCall ↶ 1655
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
1656
            .unwrap();
e8d38e47 Andy McCall ↶ 1657
        assert!(hist.is_full());
1658
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
1659
1660
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
1661
        let mut base = State::new();
1662
        base.add(c1.clone()).unwrap();
1663
        base.add(c2.clone()).unwrap();
1664
        let graphs = base.checkpoint_file_graphs();
1665
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1666
        let index = base.checkpoint_index(&graphs, |enc| {
1667
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1668
            blobs.insert(r, enc.to_vec());
1669
            r
1670
        });
1671
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
1672
        from_cp.add(c3.clone()).unwrap();
1673
        assert!(!from_cp.is_full());
1674
        let mut fetched = 0;
1675
        from_cp
a4fad5b0 Andy McCall ↶ 1676
            .load_graphs(
1677
                &[small, big],
1678
                |refs| {
1679
                    fetched += refs.len();
1680
                    refs.iter()
1681
                        .map(|r| {
1682
                            blobs
1683
                                .get(r)
1684
                                .cloned()
1685
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
1686
                        })
1687
                        .collect()
1688
                },
1689
                |_| unreachable!(),
1690
            )
e8d38e47 Andy McCall ↶ 1691
            .unwrap();
1692
        assert_eq!(
1693
            fetched, 1,
1694
            "the large graph's blob, in one batch; the small one was inline"
1695
        );
1696
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
1697
    }
1698
1699
    #[test]
1700
    #[should_panic(expected = "was not loaded")]
1701
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
1702
        let f = NodeId::random();
1703
        let mut st = State::new_history_only();
1704
        st.add(change(
1705
            vec![],
1706
            vec![TreeOp::AddNode {
1707
                node: f,
1708
                kind: NodeKind::File,
1709
                mode: Mode::TEXT,
1710
                parent: NodeId::ROOT,
1711
                name: "a".into(),
1712
            }],
1713
            vec![Edit::Insert {
1714
                node: f,
1715
                after: AtomRef::Start,
1716
                before: AtomRef::End,
1717
                lines: vec![b"a\n".to_vec()],
1718
            }],
1719
        ))
1720
        .unwrap();
1721
        st.render_file(&f);
1722
    }
1723
1724
    #[test]
1725
    #[should_panic(expected = "needs every file graph")]
1726
    fn materializing_a_history_only_state_is_refused() {
1727
        let f = NodeId::random();
1728
        let mut st = State::new_history_only();
1729
        st.add(change(
1730
            vec![],
1731
            vec![TreeOp::AddNode {
1732
                node: f,
1733
                kind: NodeKind::File,
1734
                mode: Mode::TEXT,
1735
                parent: NodeId::ROOT,
1736
                name: "a".into(),
1737
            }],
1738
            vec![Edit::Insert {
1739
                node: f,
1740
                after: AtomRef::Start,
1741
                before: AtomRef::End,
1742
                lines: vec![b"a\n".to_vec()],
1743
            }],
1744
        ))
1745
        .unwrap();
1746
        st.materialize();
afaba5f1 Andy McCall ↶ 1747
    }
1748
1749
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
1750
    /// blob; the state read back is the same as from version 1.
1751
    #[test]
1752
    fn checkpoint_index_round_trip_matches_version_1() {
1753
        let mut st = State::new();
1754
        let small = NodeId::random();
1755
        let big = NodeId::random();
1756
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1757
            node,
1758
            kind: NodeKind::File,
1759
            mode: Mode::TEXT,
1760
            parent: NodeId::ROOT,
1761
            name: name.into(),
1762
        };
1763
        let big_lines: Vec<Vec<u8>> = (0..400)
1764
            .map(|i| format!("line {i} of a long file\n").into_bytes())
1765
            .collect();
1766
        let h1 = st
1767
            .add(change(
1768
                vec![],
1769
                vec![add(small, "small"), add(big, "big")],
1770
                vec![
1771
                    Edit::Insert {
1772
                        node: small,
1773
                        after: AtomRef::Start,
1774
                        before: AtomRef::End,
1775
                        lines: vec![b"x\n".to_vec()],
1776
                    },
1777
                    Edit::Insert {
1778
                        node: big,
1779
                        after: AtomRef::Start,
1780
                        before: AtomRef::End,
1781
                        lines: big_lines,
1782
                    },
1783
                ],
1784
            ))
1785
            .unwrap();
1786
        st.add(change(
1787
            vec![h1],
1788
            vec![],
1789
            vec![Edit::Delete {
1790
                node: big,
1791
                atoms: vec![AtomRange {
1792
                    change: h1,
1793
                    from: 3,
1794
                    to: 7,
1795
                }],
1796
            }],
1797
        ))
1798
        .unwrap();
1799
1800
        let graphs = st.checkpoint_file_graphs();
1801
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1802
        let index = st.checkpoint_index(&graphs, |enc| {
1803
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1804
            blobs.insert(r, enc.to_vec());
1805
            r
1806
        });
1807
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
1808
        assert_eq!(
1809
            State::checkpoint_graph_refs(&index).unwrap(),
1810
            blobs.keys().copied().collect::<Vec<_>>()
1811
        );
1812
        assert!(
1813
            State::checkpoint_graph_refs(&st.checkpoint_payload())
1814
                .unwrap()
1815
                .is_empty(),
1816
            "version 1 names none"
1817
        );
1818
        assert!(index.len() < st.checkpoint_payload().len());
1819
1820
        let back = State::from_checkpoint(&index, |refs| {
1821
            refs.iter()
1822
                .map(|r| {
1823
                    blobs
1824
                        .get(r)
1825
                        .cloned()
1826
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
1827
                })
1828
                .collect()
1829
        })
1830
        .unwrap();
1831
        assert_eq!(
1832
            back.checkpoint_payload(),
1833
            st.checkpoint_payload(),
1834
            "the same state as version 1"
1835
        );
1836
        assert_eq!(
1837
            back.materialize().files["big"].content,
1838
            st.materialize().files["big"].content
1839
        );
1840
        // Deterministic: the same state gives the same index.
1841
        assert_eq!(
1842
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
1843
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1844
            }),
1845
            index
1846
        );
1847
        // A missing graph blob is an error, not an empty file.
1848
        assert!(
1849
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
1850
        );
1851
        assert!(
1852
            State::from_checkpoint_payload(&index).is_err(),
1853
            "version 2 needs its blobs"
1854
        );
1855
        // Version 1 payloads still read, and unknown versions do not.
1856
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
1857
        let mut v3 = cbor::decode(&index).unwrap();
1858
        if let Value::Map(m) = &mut v3 {
1859
            m.insert(0, Value::Uint(3));
1860
        }
1861
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
252e8cb2 Andy McCall ↶ 1862
    }
1863
1864
    #[test]
ff0af1ee unknown 1865
    fn maximal_elements() {
1866
        let mut st = State::new();
1867
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
1868
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
1869
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
1870
        let mut m = st.maximal(&[h1, h2, h3]);
1871
        m.sort();
1872
        let mut want = vec![h2, h3];
1873
        want.sort();
1874
        assert_eq!(m, want);
1875
        assert_eq!(st.heads(), want);
1876
    }
07eb99be Andy McCall ↶ 1877
1878
    /// The one-walk `maximal` agrees with the definition (not in the
1879
    /// closure of another element) on random graphs, with repeated and
1880
    /// unknown hashes among the input.
1881
    #[test]
1882
    fn maximal_matches_its_definition() {
1883
        use rand::{Rng, SeedableRng};
1884
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
1885
        for _ in 0..20 {
1886
            let mut st = State::new();
1887
            let mut all: Vec<ChangeHash> = Vec::new();
1888
            for _ in 0..60 {
1889
                let deps: Vec<ChangeHash> =
1890
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
1891
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
1892
            }
1893
            let mut pick: Vec<ChangeHash> =
1894
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
1895
            pick.extend(pick.clone().into_iter().take(3));
1896
            pick.push(ObjectRef([0xee; 32]));
1897
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
1898
            let want: Vec<ChangeHash> = set
1899
                .iter()
1900
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
1901
                .copied()
1902
                .collect();
1903
            assert_eq!(st.maximal(&pick), want);
1904
            assert_eq!(st.maximal(&all), st.heads());
1905
        }
1906
    }
ff0af1ee unknown 1907
}