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